Ⅰ android 如何動態布局自定義view,不用XML.
可以直接new View來得到View對象來實現代碼布局。以下為示例代碼:
1.絕對布局
AbsoluteLayout abslayout=new AbsoluteLayout (this);
setContentView(abslayout);
Button btn1 = new Button(this);
btn1.setText(」this is a button」);
btn1.setId(1);
AbsoluteLayout.LayoutParams lp1 =
new AbsoluteLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0,100);
abslayout.addView(btn1, lp1);
2.相對布局
RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);
AbsoluteLayout abslayout=new AbsoluteLayout (this);
RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp1.addRule(RelativeLayout.ALIGN_PARENT_TOP);
lp1.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
relativeLayout.addView(abslayout ,lp1);
3.線性布局
LinearLayout ll = new LinearLayout(this);
EditText et = new EditText();
ll.addView(et);
//動態添加布局的方法1. LinearLayout ll = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null); setContentView(ll); LinearLayout ll2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,ll); //這樣 main2 作為 main1的子布局 加到了 main1的 根節點下
//動態添加布局的方法2 addView. LinearLayout ll = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main1,null); setContentView(ll); LinearLayout ll2 = (LinearLayout)this.getLayoutInflater().inflate(R.layout.main2,null); ll.addView(ll2);
Ⅱ android 怎麼把倆個xml文件整合到一起
private ViewGroup group;
private ViewGroup main;
main = (ViewGroup) inflater.inflate(R.layout.main, null);//這里的R。latout.main就是當前布局
group = (ViewGroup) main.findViewById(R.id.viewGroup);
group.addView(imageViews[i]);//這樣就把一個imageview(你可添加一個任意復雜的View,這個View實例化的時候指向你所謂的其他布局文件)加入當前布局中的某個ViewGroup里了,你布局時可定義一個LinearLayout id 設為(R.id.viewGroup),oratation設為垂直,放到下面就是了。