XML属性从合并布局到RelativeLayout通过膨胀

gma*_*ate 9 xml layout user-interface android commonsware

根据这个CommonsWare示例,我设法将我的RelativeLayout子类与我在xml布局中描述的具有合并根的布局合并.我唯一担心的是我无法在xml中描述我的RelativeLayout参数.

我的xml布局:

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:my="http://schemas.android.com/apk/res/hu.someproject"
  android:layout_width="36dp"
  android:layout_height="wrap_content"
  android:layout_marginLeft="3dp"
  android:layout_marginRight="3dp"
  android:width="36dp" >

 <RelativeLayout
    android:id="@+id/upper_container"
    style="?pretty_style"
    android:layout_alignLeft="@+id/image_title"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/image_title"
    android:layout_centerHorizontal="true" >

    <View
        android:id="@+id/upper_indicator"
        android:layout_width="fill_parent"
        android:layout_height="5dp"
        android:layout_alignParentTop="true"
        android:background="@color/mycolor" />

    <TextView
        android:id="@+id/text_degree"
        style="?pretty_style"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="23°" />
</RelativeLayout>

<hu.MyView
    android:id="@+id/image_title"
    style="?my_image_title"
    android:layout_below="@+id/upper_container"
    android:layout_centerHorizontal="true"
    my:myColor="#2f8741"/>
Run Code Online (Sandbox Code Playgroud)

我认为问题是合并标签的子节点发生合并,而不是合并本身.任何想法如何在合并中获取我的参数以影响我的RelativeLayout?

我的RelativeLayout子类,没有包声明和导入:

public class MyRelativeLayoutSubclass extends RelativeLayout {

    public MyRelativeLayoutSubclass(Context context) {
        super(context);

        initTile(null);
    }

    public MyRelativeLayoutSubclass(Context context, AttributeSet attrs) {
        super(context, attrs);

        initTile(attrs);
    }

    public MyRelativeLayoutSubclass(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initTile(attrs);
    }

    private void initTile(Object object) {
        final LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        inflater.inflate(R.layout.my_great_little_layout, this, true);
    }
}
Run Code Online (Sandbox Code Playgroud)

我知道我可以将所有内容添加到LayoutParams中,然后将我的MyRelativeLayoutSubclass与LayoutParams一起添加,但我想逃避这一点,这是很多不必要的代码.

Com*_*are 18

我认为问题是合并标签的子节点发生合并,而不是合并本身.

AFAIK,你是对的.<merge>是一个占位符,而不是一个ViewGroup.

我知道我可以将所有内容添加到LayoutParams中,然后将我的MyRelativeLayoutSubclass与LayoutParams一起添加,但我想逃避这一点,这是很多不必要的代码.

创建包含MyRelativeLayoutSubclass元素的XML布局文件,并将属性放在那里.然后,膨胀该布局.

  • @CommonsWare,当然是马克,但我的意思是,一旦使用合并,就无法通过 XML 传递参数。如果您必须使用合并将自定义视图包装到其他内容中才能实现它,那么您就失去了合并的全部意义,即减少视图层次结构深度。这种优化对于列表特别有用。与在列表视图中一样,您可以使用其代码构造函数实例化自定义视图,无法再通过 XML 参数对其进行自定义,只能以编程方式进行自定义。抱歉我没说清楚。顺便说一句,我也参加了 andev con。明天我们一起吃午饭吗? (2认同)