Android动态生成控件

MainActivity:

public class MainActivity extends AppCompatActivity {
    private final int WC = ViewGroup.LayoutParams.WRAP_CONTENT;
    private final int MP = ViewGroup.LayoutParams.MATCH_PARENT;
    private EditText row;
    private EditText column;
    private Button bt1;
    private TableLayout tableLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt1 = (Button) findViewById(R.id.button1);
        row = (EditText) findViewById(R.id.editText1);
        column = (EditText) findViewById(R.id.editText2);

        bt1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (row.getText().length() > 0 && column.getText().length() > 0) {
                    int row_int = Integer.parseInt(row.getText().toString());
                    int col_int = Integer.parseInt(column.getText().toString());

                    tableLayout = (TableLayout) findViewById(R.id.table1);
                    tableLayout.removeAllViews();
                    tableLayout.setStretchAllColumns(true);
                    for (int i = 1; i <= row_int; i++) {
                        TableRow tableRow = new TableRow(MainActivity.this);
                        for(int j = 1; j <= col_int; j++) {
                            TextView tv = new TextView(MainActivity.this);
                            tv.setText("(" + i + "," + j + ")");
                            tableRow.addView(tv);
                        }
                        tableLayout.addView(tableRow, new TableLayout.LayoutParams(MP, WC, 1));
                    }
                }
                else {
                    Toast.makeText(MainActivity.this, "请输入行和列", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

activity_main:




    

        

        
            
        
    

    

        

        

        

    

    

        

你可能感兴趣的:(Android动态生成控件)