Android开发笔记3-- 动态布局

由于项目需要,需要研究动态布局,发现其实Android动态布局很方便

写几个Layout Params共用

private LayoutParams LP_FF = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);   
private LayoutParams LP_FW = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);   
private LayoutParams LP_WW = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);  

在TableLayout中动态各种控件

LinearLayout linearLayout= (LinearLayout)findViewById(R.id.LinearLayout1);
        TableLayout tableLayout = (TableLayout)findViewById(R.id.tableLayout1);
        //tableLayout.setColumnStretchable(1, true);
        TextView label1 = new TextView(this);
        label1.setText("Test1");
        label1.setBackgroundColor(Color.RED);
        TextView label3 = new TextView(this);
        label3.setText("Test3");
        Spinner spinner = new Spinner(this);
        spinner.setPrompt("Select...");
        String[] abcStrings ={"123","456","789"};
        ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, abcStrings);
        adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
        spinner.setAdapter(adapter);
        LayoutParams lpp= new LayoutParams(30,30);
        //spinner.setLayoutParams(LP_FF);
       // spinner.setVisibility(View.VISIBLE);
        //linearLayout.addView(spinner);
        TableRow row1 = new TableRow(this);
        Button bt1= new Button(this);
        bt1.setText("Testbutton");
        bt1.setLayoutParams(LP_FF);
        
        TableRow row2 = new TableRow(this);
        TextView label2 = new TextView(this);
        label2.setText("Test2");
        
        tableLayout.addView(row1,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        tableLayout.addView(row2,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        row1.addView(label1);
        row1.addView(spinner);
        row2.addView(label2);
        row2.addView(bt1);

注意必须先添加TableRow再添加各种控件,否则控件显示不出来





你可能感兴趣的:(Android开发笔记3-- 动态布局)