使用代码控制子对象

2017-03-08  本文已影响2人  csp

使用代码来控制组件更加的灵活,容易控制。
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);
}

}

上一篇下一篇

猜你喜欢

热点阅读