Reg*_*_AG 5 android class view android-activity
我有以下问题:我想在我的主要活动中添加自定义视图(custom_view.xml和关联的CustomView.java类).
所以,我做了以下事情:
1)在我的主要活动中(链接到main.xml):
CustomView customView = new CustomView(this);
mainView.addView(customView);
Run Code Online (Sandbox Code Playgroud)
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....
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是aTextView仍然等于null ...很明显,由于我的custom_view.xml没有链接到我的CustomView.java类.我该怎么做这个链接?的确,我尝试了setContentView(R.layout.custom_view); 但它不起作用(编译错误)因为我的类从View类而不是Activity类扩展.
谢谢你的帮助 !!
PH7*_*PH7 12
如果我找到你,你正试图从layoutfile(R.layout.custom_view)构建自定义视图.您想从该布局文件中查找文本视图.是对的吗?
如果是这样,您需要使用上下文来扩展布局文件.然后你可以从布局文件中找到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);
Run Code Online (Sandbox Code Playgroud)