如何在程序中创建自定义视图的布局?

21
在Activity中,您可以按照以下方式通过编程方式创建LinearLayout:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(LinearLayout.VERTICAL);
    ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    TextView tv1 = new TextView(this);
    tv1.setText("HELLO");
    ll.addView(tv1);

    TextView tv2 = new TextView(this);
    tv2.setText("WORLD");
    ll.addView(tv2);

    setContentView(ll);
}

如何在自定义View子类中执行相同的操作?没有setContentViewonCreate方法...


请参考此链接:http://stackoverflow.com/questions/14054197/how-to-get-the-name-of-textview-included-in-linear-layout-in-onclicklistener - Mohammed Azharuddin Shaikh
请参考此链接:http://stackoverflow.com/questions/14081339/how-can-i-declare-textview-as-global-variable-to-use-in-other-class/14081472#14081472 - Dixit Patel
2个回答

36

好的,我发现一种做法。基本上,你需要子类化通常在XML中定义的最高层级的类,而不是直接子类化View类。例如,如果您的自定义View需要LinearLayout作为其最高层级类,则您的自定义View应该简单地继承LinearLayout。

例如:

public class MyCustomView extends LinearLayout
{
    public MyCustomView(Context context, AttributeSet attrs)
    {
        super(context, attrs);

        setOrientation(LinearLayout.VERTICAL);
        setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        TextView tv1 = new TextView(context);
        tv1.setText("HELLO");
        addView(tv1);

        TextView tv2 = new TextView(context);
        tv2.setText("WORLD");
        addView(tv2);
    }
}

将LinearLayout作为子类是否算是一种“hack”?就我所知,这并不算。一些官方的View子类也会这样做,例如NumberPickerSearchView(尽管它们会从XML中填充其布局)。

仔细想一想,这其实是一个相当明显的答案。


0

如果我理解你的问题,你需要使用inflate函数,像这样:

public final class ViewHolder {
        public TextView title;
        public TextView artist;
        public TextView duration;
        public ImageView thumb_image;
    //A class for the ViewHolder

    }

// Put this where you want to inflate this layout, could be a customlistview
View view = getLayoutInflater().inflate(R.layout.your_layout, null);
holder = new ViewHolder();
    holder.title = (TextView)view.findViewById(R.id.title); // title
    holder.artist = (TextView)view.findViewById(R.id.artist); // artist name
    holder.duration = (TextView)view.findViewById(R.id.duration); // duration
    holder.thumb_image=(ImageView)view.findViewById(R.id.list_image); // thumb image

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接