Android 如何创建自定义视图';以编程方式进行布局?
在“活动”中,可以通过以下方式以编程方式创建LinearLayout:Android 如何创建自定义视图';以编程方式进行布局?,android,android-layout,android-linearlayout,android-view,android-custom-view,Android,Android Layout,Android Linearlayout,Android View,Android Custom View,在“活动”中,可以通过以下方式以编程方式创建LinearLayout: public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); LinearLayout ll = new LinearLayout(this); ll.setOrientation(LinearLayout.VERTICAL); ll.setLayoutParams(new Layo
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);
}
如何在自定义视图子类中执行相同的操作?没有
setContentView
或onCreate
方法…如果我理解您的问题,您需要使用充气,如下所示:
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
好吧,我发现了一种方法。基本上,您不需要直接子类化视图类,而是需要子类化通常在XML中定义的最顶层的类。例如,如果您的自定义视图需要一个LinearLayout作为其最顶层的类,那么您的自定义视图应该只是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是“黑客”吗?我看不远。一些官方视图子类也做同样的事情,比如和(尽管它们从XML扩展了布局)
经过深思熟虑,这实际上是一个非常明显的答案。可以参考此链接