我必须在Android中构建更复杂的自定义视图。最终布局应如下所示:
<RelativeLayout> <SomeView /> <SomeOtherView /> <!-- maybe more layout stuff here later --> <LinearLayout> <!-- the children --> </LinearLayout> </RelativeLayout>
但是,我只想在XML文件中定义它(不定义SomeView,SomeOtherView等):
<MyCustomView> <!-- the children --> </MyCustomView>
这在Android中可行吗?如果可以,那么最干净的方法是什么?我想到的可能解决方案是“重写addView()方法”和“删除所有视图并在以后再次添加它们”,但是我不确定该走哪条路…
在此先感谢您的帮助!:)
绝对有可能并且鼓励创建自定义容器视图。这就是Android所谓的复合控件。所以:
public class MyCustomView extends RelativeLayout { private LinearLayout mContentView; public MyCustomView(Context context) { this(context, null); } public MyCustomView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public MyCustomView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); //Inflate and attach your child XML LayoutInflater.from(context).inflate(R.layout.custom_layout, this); //Get a reference to the layout where you want children to be placed mContentView = (LinearLayout) findViewById(R.id.content); //Do any more custom init you would like to access children and do setup } @Override public void addView(View child, int index, ViewGroup.LayoutParams params) { if(mContentView == null){ super.addView(child, index, params); } else { //Forward these calls to the content view mContentView.addView(child, index, params); } } }
您可以根据需要覆盖尽可能多的版本addView(),但最后它们都会回调到我在样本中放置的版本。仅重写此方法将使框架将在XML标记内找到的所有子代传递给特定的子代容器。
addView()
然后像这样修改XML:
RES /布局/custom_layout.xml
<merge> <SomeView /> <SomeOtherView /> <!-- maybe more layout stuff here later --> <LinearLayout android:id="@+id/content" /> </merge>
使用的原因<merge>是简化层次结构。所有子视图都将附加到您的自定义类(即)上RelativeLayout。如果不使用<merge>,则最终会在所有子项上RelativeLayout附加一个RelativeLayout附加项,这可能会引起问题。
<merge>
RelativeLayout
高温超导