Theo ví dụ về CommonsWare này, tôi đã quản lý để có được lớp con RelativeLayout được hợp nhất với bố cục được mô tả trong bố cục xml với gốc hợp nhất. Mối quan tâm duy nhất của tôi là tôi không thể mô tả các tham số RelativeLayout của tôi trong xml.Thuộc tính XML từ bố cục phối hợp đến RelativeLayout qua inflate
My layout 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"/>
Tôi nghĩ vấn đề là hợp nhất xảy ra với trẻ em của thẻ hợp nhất, và không phải là hợp nhất của chính nó. Bất kỳ ý tưởng làm thế nào tôi có thể nhận được các thông số của tôi trong hợp nhất để ảnh hưởng đến RelativeLayout của tôi?
My RelativeLayout lớp con, mà không khai báo và nhập khẩu trọn gói:
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);
}
}
Tôi biết tôi có thể thêm tất cả mọi thứ đến một LayoutParams, và sau đó thêm MyRelativeLayoutSubclass tôi với LayoutParams đó, nhưng tôi muốn thoát khỏi đó, đó là rất nhiều mã không cần thiết.
Đây là giải pháp rất rõ ràng và tôi không biết tại sao tôi lại bỏ qua. – gmate
Nó không cho phép bạn có các thuộc tính mặc định một cách dễ dàng mặc dù. Tôi phải nhập lại chúng mỗi khi tôi sử dụng thành phần tùy chỉnh của mình. – Timmmm
@Timmmm: 'MyRelativeLayoutSubclass' chắc chắn có các giá trị mặc định cho các thuộc tính, được sử dụng khi nó cố gắng đọc trong các thuộc tính từ XML (và không gặp phải chúng). – CommonsWare