我有一个扩展活动的类,并以这种方式获取它的视图:
setContentView((View) viewClass);
viewClass是从视图扩展的类。
我需要在这个类中实现一些按钮和图像视图。但是如何?
答案 0 :(得分:0)
您可以执行以下操作
让您的主要活动如下
public class MainActivity extends Activity{
MyView view;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Context ctx = getApplicationContext();
view=new MyView(ctx);
setContentView(view);
}
}
让您的视图类扩展任何容器布局。
public class MyView extends RelativeLayout{
public MyView(Context context) {
super(context);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
this.setLayoutParams(layoutParams);
RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv = new TextView(context);
tv.setText("hello");
tv.setId(1);
Button b = new Button(context);
params1.addRule(RelativeLayout.BELOW, tv.getId());
b.setText("Hi");
b.setId(2);
this.addView(tv);
this.addView(b, params1);
}
}
答案 1 :(得分:0)
您需要从ViewGroup或布局类型(例如LinearLayout)扩展自定义视图,这将有助于您通过以下活动以编程方式向布局添加其他视图:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout view = new LinearLayout(this);
setContentView(view);
TextView tv = new TextView(this);
tv.setText("asas");
view.addView(tv);
}
}