0

Problem:

I've developed a custom compound view and I'm unsure of how to display it in my listview.

What I've done:

-> My custom compound view

public class HZScrollView extends LinearLayout {

public HZScrollView(Context context) {
    super(context);
    initView(context);
}

   private void initView(Context context) {

        mContext = context;

        setOrientation(LinearLayout.HORIZONTAL);
        setGravity(Gravity.CENTER_VERTICAL);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                               ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setLayoutParams(lp);

        //inflate XML resource and attach
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mInflater.inflate(R.layout.hz_scroll_view, this, true);
    }
}

public void addContent(String name, String age, String sex) {
//content is added to the individual widgets within this compound view
}

-> My Adapter

public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
convertView = new HZScrollView(context); //<--- PROBLEM !
}
}

The major problem I'm experiencing is that the line marked with "PROBLEM" causes the exception java.lang.RuntimeException: Unable to start activity ComponentInfo{com.my.app/.MainActivity}: android.view.InflateException: <merge /> can be used only with a valid ViewGroup root and attachToRoot=true

In sample code around the 'net, the getView() usually inflates an XML layout, but in my case the compound view is completely self-contained.

Question:

How is it possible to insert/attach my custom compound view into the listview item ?

4

1 回答 1

1

解决方案:

1)在适配器中,将HZScrollView分配给convertView就可以了

2) 要修复 LayoutParams 的另一个问题,需要更新 initView() 以使用 AbsListView.LayoutParams 而不是 ViewGroup.LayoutParams(因为父容器是 listView)

3) 修复 InflateException,<merge>XML 中使用的子视图,我对其进行了重构以将子视图包装在 LinearLayout 中。注意:<merge>在 XML 中使用“hz_scroll_view”文件就可以了。


对我来说,真正有趣的部分是第 1 点,因为我不确定将自定义复合视图分配给列表视图项是否可行。

于 2013-06-28T18:59:48.677 回答