Chr*_*yle 90 xml layout android
我有一个res/layout/main.xml包括这些元素和其他:
<some.package.MyCustomView android:id="@+id/foo" (some other params) />
<TextView android:id="@+id/boring" (some other params) />
Run Code Online (Sandbox Code Playgroud)
在我的Activity的onCreate中,我这样做:
setContentView(R.layout.main);
TextView boring = (TextView) findViewById(R.id.boring);
// ...find other elements...
MyCustomView foo = (MyCustomView) findViewById(R.id.foo);
if (foo == null) { Log.d(TAG, "epic fail"); }
Run Code Online (Sandbox Code Playgroud)
其他元素成功找到,但foo返回null.MyCustomView有一个构造函数,MyCustomView(Context c, AttributeSet a)并且Log.d(...)该构造函数的末尾在"史诗失败"之前的logcat中成功出现.
为什么是foonull?
Chr*_*yle 176
因为在构造函数中,我有super(context)而不是super(context, attrs).
有道理,如果你没有传递属性,比如id,那么视图将没有id,因此无法使用该id找到.:-)
Ale*_*huk 25
我有同样的问题,因为在我的自定义视图中我覆盖了构造函数,但调用了超级构造函数withot attrs paramete.那是复制粘贴)
我以前的构造函数版本:
public TabsAndFilterRelativeLayout(Context context, AttributeSet attrs) {
super(context);
}
Run Code Online (Sandbox Code Playgroud)
我现在有:
public TabsAndFilterRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);}
Run Code Online (Sandbox Code Playgroud)
这有效!
Vin*_*ent 18
我有同样的问题.我的错误在于:我写道
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout=inflater.inflate(R.layout.dlg_show_info, null);
alertDlgShowInfo.setView(layout);
TableRow trowDesc=(TableRow)findViewById(R.id.trowDesc);
Run Code Online (Sandbox Code Playgroud)
当我使用inflater从XML文件"加载"视图时,最后一行是错误的.要解决它,我不得不写:
TableRow trowDesc=(TableRow)layout.findViewById(R.id.trowDesc);
Run Code Online (Sandbox Code Playgroud)
我写了我的解决方案,以防有人遇到同样的问题.
Dan*_*iel 11
同样的问题,但不同的解决方案:我没有打电话
setContentView(R.layout.main)
Run Code Online (Sandbox Code Playgroud)
在我试图找到这里所说的观点之前
| 归档时间: |
|
| 查看次数: |
51605 次 |
| 最近记录: |