自定义视图,在Android的XML布局自定义、视图、布局、Android

2023-09-07 04:20:03 作者:爱你等于作孽

我有很多不同的布局中行的ListAdapter。有一个干净的code我希望外包的布局从适配器的getView()在视图类的行。是否有可能夸大一个XML布局到一个自定义的看法?我只找到了LayoutInflater但它返回一个视图,并没有帮助。我想有类似的活动的setLayout()。这可能吗?

I have a ListAdapter with a lot of different layouts for the rows. To have a clean code I want to outsource the layouts for the rows from the getView() of the adapter in View classes. Is it possible to inflate a XML layout into a custom view? I've only found the LayoutInflater but it returns a View and that does not help. I want to have something like the setLayout() of an Activity. Is this possible?

谢谢!

推荐答案

您可以有一个自定义列视图,并夸大你的XML在它的构造函数:

You can have a custom row view and inflate your xml in its constructor:

public MyRow extends LinearLayout {
    public MyRow(Context context) {
        super(context);
        LayoutInflater.from(context).inflate(R.layout.my_row, this, true);
          ... other initialization ...
    }
}

然后用在合并 my_row.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">
  ... your row layout ...
</merge>

合并元素会导致其子被添加为自定义视图的孩子。请查看合并布局获取更多的信息。

The merge element causes its children to be added as children of your custom view. Check out Merging Layouts for more info.