我有多个这样的骨架布局:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
...
</merge>
我需要将此布局包装在LinearLayout中,但不要制作多个xml文件,因为他们只有一个linearlayout和一个include标签,就像这样......
<LinearLayout
<include layout="@layout/layout1"
</LinearLayout>
有没有什么方法可以以编程方式实现与@ layout / layout1相同的效果?喜欢选择要包含的布局?我在recyclerview中为ViewHolder充实了这个布局,现在我正在这样做。
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ViewHolder vh = null;
View inflatedView;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (x) {
case 1:
inflatedView = inflater.inflate(R.layout.cool_layout, parent, false);
inflater.inflate(R.layout.layout1, (LinearLayout)inflatedView, true);
vh = new ViewHolder(inflatedView);
case 2:
inflatedView = inflater.inflate(R.layout.cool_layout, parent, false);
inflater.inflate(R.layout.layout2, (LinearLayout)inflatedView, true);
vh = new ViewHolder(inflatedView);
它会进行两次inflate()调用,这可能不是一个好主意,所以除了制作一堆xml文件外,我还在寻找另一种选择。
答案 0 :(得分:0)
您可以使用开关选择布局,然后只有一个inflater调用:
int layout = 0;
switch(mLayoutType){
case "layout_1":{
layout = R.layout.layout_1;
break;
}
case "layout_2":{
layout = R.layout.layout_2;
break;
}
default:{
Log.e(LOG_TAG,"Invalid layout type.");
}
}
View v = LayoutInflater.from(parent.getContext())
.inflate(layout, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
答案 1 :(得分:0)
this will be in your parent root...
<ViewStub android:id="@+id/stub"
android:inflatedId="@+id/subTree"
android:layout="@layout/mySubTree"
android:layout_width="120dip"
android:layout_height="40dip" />
in java file
ViewStub stub = new ViewStub(this);
stub.setLayoutResource(R.layout.mySubTree);
stub.inflate();