Android - Writing a custom (compound) component

孤街醉人 提交于 2019-11-27 10:12:18

Use merge tag as your XML root

<merge xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Your Layout -->
</merge>

Check this article.

I think the way you're supposed to do it, is use your class name as the XML root element:

<com.example.views.MyView xmlns:....
       android:orientation="vertical" etc.>
    <TextView android:id="@+id/text" ... />
</com.example.views.MyView>

And then have your class derived from whichever layout you want to use. Note that if you are using this method you don't use the layout inflater here.

public class MyView extends LinearLayout
{
    public ConversationListItem(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }
    public ConversationListItem(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
    }


    public void setData(String text)
    {
        mTextView.setText(text);
    }

    private TextView mTextView;

    @Override
    protected void onFinishInflate()
    {
        super.onFinishInflate();

        mTextView = (TextView)findViewById(R.id.text);
    }
}

And then you can use your view in XML layouts as normal. If you want to make the view programmatically you have to inflate it yourself:

MyView v = (MyView)inflater.inflate(R.layout.my_view, parent, false);

Unfortunately this doesn't let you do v = new MyView(context) because there doesn't seem to be a way around the nested layouts problem, so this isn't really a full solution. You could add a method like this to MyView to make it a bit nicer:

public static MyView create(Context context)
{
    return (MyView)LayoutInflater.fromContext(context).inflate(R.layout.my_view, null, false);
}

Disclaimer: I may be talking complete bollocks.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!