我有几个定制LinearLayout
我想动态添加到 Activity
的 s的主RelativeLayout
.
这是我的自定义布局之一:
public class MyLayout1 extends LinearLayout {...}
这是 my_layout_1.xml
文件:
<?xml version="1.0" encoding="utf-8"?>
<***myPackageName***.MyLayout1
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
......
</***myPackageName***.MyLayout1>
我将自定义布局添加到 RelativeLayout
使用此代码:
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
View view = getLayoutInflater().inflate(R.layout.my_layout_1, mainLayout, false); //mainLayout is the id of the main RelativeLayout
mainLayout.addView(view, params);
代码运行良好。
但是当我使用 findViewById(...)
在我的自定义功能中 MyLayout1
类,它返回 null
对于所有观点。如何绑定(bind) .xml
文件和 Java 类?我认为在 .xml
中添加包+类名够了,但我错了。
我也试着打电话
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.my_layout_1, null);
在MyLayout1
类,但是 android.view.InflateException: Binary XML file line #2: Error inflating class <unknown>
错误消息显示在日志窗口中。
最佳答案
如果您需要调用 findViewById()
来访问在您的 layout.xml 文件中声明的 View 实例,那么您需要在 View#onfinishInflate()
中执行此操作.一旦 View 完成膨胀,就会调用它。在该函数中,您可以成功使用 findViewById()
。当在构造函数中使用 findViewById()
时,当 View 被膨胀时, subview 将尚未被实例化和添加。这就是它返回 null 的原因。
关于android - 动态添加自定义布局到 Activity 的布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17934273/