使用代碼來控制組件更加的靈活,容易控制接奈。
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private LinearLayout root;
private Button btnClickme;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
setContentView(root);
for (int i = 0;i<5;i++){
btnClickme = new Button(this);
btnClickme.setText("Remove me");
btnClickme.setOnClickListener(this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight = 1;
root.addView(btnClickme,lp);
}
// root.addView(btnClickme);
// root.addView(btnClickme,LinearLayout.LayoutParams.MATCH_PARENT,200);
// LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
//
// root.addView(btnClickme,lp);
}
@Override
public void onClick(View v) {
root.removeView(v);
}
}