如何在表格行中以编程方式设置textview和edittext params?

时间:2015-01-24 08:40:15

标签: android android-edittext textview

我想通过代码添加textview和edittext params。 这是我的代码

private void draw_table() {
    // TODO Auto-generated method stub
    TableLayout ll = (TableLayout) findViewById(R.id.input_table_2);

    for (int i = 0; i < 2; i++) {

        TableRow row = new TableRow(this);
        TableRow.LayoutParams lp = new TableRow.LayoutParams(
                TableRow.LayoutParams.MATCH_PARENT,
                TableRow.LayoutParams.WRAP_CONTENT);
        row.setLayoutParams(lp);
        // setting textVIEW
        textview = new TextView(this);
        textview.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        //textview.setPadding(0, 0, 5, 10);
        //textview.setTextAppearance(this,
        //      android.R.style.TextAppearance_Medium);
        textview.setText("Hello"); 
        // setting editText
        edittext = new EditText(this);
        edittext.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));
        //edittext.setEms(10);
        //edittext.setHint("gpa");
        //edittext.setInputType(InputType.TYPE_CLASS_NUMBER);
        row.addView(textview);
        row.addView(edittext);
        ll.addView(row, i);
    }
}

但屏幕上没有任何内容。这段代码有什么问题?提前谢谢:)

2 个答案:

答案 0 :(得分:1)

使用TableRow.LayoutParams设置小部件LayoutParams。喜欢这个

textview.setLayoutParams(new TableRow.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT));

另见how add and delete rows to table layout in java programically

答案 1 :(得分:0)

private void draw_table() { // get a reference for the TableLayout
    TableLayout table = (TableLayout) findViewById(R.id.input_table_2);

    for (int i = 0; i < 2; i++) {
    // create a new TableRow
    TableRow row = new TableRow(this);
    // create a new TextView
    TextView textview = new TextView(this);
    // set the text to "text Hello"
    textview.setText("Hello"); 

    // create a EditText
    EditText  edittext = new EditText(this);

    row.addView(textview);
    row.addView(edittext);

    // add the TableRow to the TableLayout
    table.addView(row,i,new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    }