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

标签 android class view android-activity

我遇到以下问题:我想将自定义 View (custom_view.xml 和关联的 CustomView.java 类)添加到我的主要 Activity 。

因此,我执行以下操作:

1) 在我的主要 Activity 中(链接到 main.xml):

CustomView customView = new CustomView(this);
mainView.addView(customView);

2) 在我的 CustomView.java 类中(我想链接到 custom_view.xml):

public class CustomView extends View {

public CustomView(Context context)
{
super(context);

/* setContentView(R.layout.custom_view); This doesn't work here as I am in a class extending from and not from Activity */

TextView aTextView = (TextView) findViewById(R.id.aTextView); // returns null

///etc....
}

}

我的问题是 aTextView 仍然等于 null... 显然是因为我的 custom_view.xml 没有链接到我的 CustomView.java 类。我该怎么做这个链接?事实上,我试过 setContentView(R.layout.custom_view);但它不起作用(编译错误),因为我的类是从 View 类而不是 Activity 类扩展的。

感谢您的帮助!!

最佳答案

如果我没听错,你正试图从布局文件 (R.layout.custom_view) 构建自定义 View 。你想从那个布局文件中找到一个 TextView 。那正确吗?

如果是这样,您需要使用您拥有的上下文来扩充布局文件。然后你可以从布局文件中找到 TextView 。

试试这个。

LayoutInflater inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.custom_view, null);
TextView aTextView = (TextView) v.findViewById(R.id.aTextView);

关于Android:如何使 findViewById(R.id.xxx) 在继承/扩展自 View 类的类中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7724508/

相关文章:

Android 的 Wallpapermanager 在 Flutter 中?

android - FloatingActionButton 不能正常工作

android - MenuItem.setIcon() 方法不起作用

c++ - 使用枚举类和运算符重载分隔 header

python - Python 类中的方法命名空间/集合

android - WiFi-Direct Api 和 Alljoyn 框架的区别

ios - iOS 中具有大小等级的自定义字体

ios - 查看 Controller 遏制 Z 位置

android - 如何根据其父 View 大小设置 ImageView 可绘制大小?

c++ - 以 SFML 中的移动位置为中心的 View