我有以下问题:我想向我的主要 Activity 中添加一个自定义 View (custom_view.xml和关联的CustomView.java类)。

因此,我执行以下操作:

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类扩展的。

谢谢你的帮助 !!

最佳答案

如果我正确地理解了您,则您正在尝试从layoutfile(R.layout.custom_view)构建customview。您想从该布局文件中找到一个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/

10-12 03:39