首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Android:如何使findViewById(R.id.xxx)在从View类继承/扩展的类中工作?

在Android中,如果你想在从View类继承或扩展的类中使用findViewById(R.id.xxx),你需要确保你的类是一个Activity或者是一个ViewGroup。以下是一个简单的例子,展示了如何在一个自定义的ViewGroup中使用findViewById(R.id.xxx):

  1. 首先,在你的布局文件中创建一个自定义的ViewGroup,并为其分配一个ID。例如,在activity_main.xml中:
代码语言:xml
复制
<com.example.myapplication.MyCustomViewGroup
    android:id="@+id/my_custom_view_group"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <Button
        android:id="@+id/button_inside_custom_view_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button inside Custom ViewGroup" />

</com.example.myapplication.MyCustomViewGroup>
  1. 然后,在你的自定义ViewGroup类中,使用findViewById(R.id.xxx)来查找子视图。例如,在MyCustomViewGroup.java中:
代码语言:java
复制
package com.example.myapplication;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

public class MyCustomViewGroup extends RelativeLayout {

    public MyCustomViewGroup(Context context) {
        super(context);
        init(context);
    }

    public MyCustomViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public MyCustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        View.inflate(context, R.layout.activity_main, this);

        Button buttonInsideCustomViewGroup = findViewById(R.id.button_inside_custom_view_group);
        buttonInsideCustomViewGroup.setText("Button inside Custom ViewGroup (modified)");
    }
}

在这个例子中,我们创建了一个名为MyCustomViewGroup的自定义ViewGroup,它继承自RelativeLayout。我们在init()方法中使用findViewById(R.id.xxx)来查找布局文件中的Button,并修改其文本内容。

需要注意的是,在自定义ViewGroup中使用findViewById(R.id.xxx)时,你需要确保布局文件已经被加载,否则会返回null。在上面的例子中,我们使用View.inflate()方法来加载布局文件,并将其添加到自定义ViewGroup中。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券