Android UI未以编程方式更新

时间:2013-05-12 18:06:44

标签: java android xml android-xml

我正在编写以下代码..但有些部分正在运行,有些部分无效,我无法弄明白为什么......

这些工作正常

    ScrollView deviceList = (ScrollView) findViewById(R.id.deviceManager);
    deviceList.setBackgroundColor(Color.CYAN);
    TableLayout deviceTable = new TableLayout(getApplicationContext());
    deviceTable.setId(951357);
    TableRow tr = new TableRow(getApplicationContext());
    LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    tr.setLayoutParams(layout);
    TextView tv = new TextView(getApplicationContext());
    tv.setText("Searching");
    tv.setVisibility(1);
    tr.addView(tv);
    deviceTable.addView(tr);
    deviceList.addView(deviceTable);
    Thread.sleep(1000)
    deviceTable.removeAllViews();
    LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
    TableRow tr = new TableRow(getApplicationContext());
    TextView tv = new TextView(getApplicationContext());
    tv.setLayoutParams(layout);
    tr.setLayoutParams(layout);
    tv.setText("No more devices");
    if(rowCounter%2==0)
    {
        System.out.println("rowCounter%2==0");
        tv.setTextColor(Color.WHITE);
        tr.setBackgroundColor(Color.DKGRAY);
    }
    else
    {
        System.out.println("rowCounter%2==1");
        tv.setTextColor(Color.WHITE);
        tr.setBackgroundColor(Color.GRAY);
    }

不工作

    tv.setVisibility(1);
    tv.setEnabled(true);
    tr.addView(tv);
    tr.setVisibility(1);
    deviceTable.addView(tr);

再次工作

    System.out.println(tv+" "+tr+" "+deviceTable+" "+tv.getText());
    deviceTable.setBackgroundColor(Color.BLACK);
    System.out.println("No more devices");

修改

tv.setVisibility(View.VISIBLE);
tv.setEnabled(true);
tr.addView(tv);
tr.setVisibility(View.VISIBLE);
deviceTable.addView(tr);
System.out.println(tv+" "+tr+" "+deviceTable+" "+tv.getText());
deviceTable.setBackgroundColor(Color.BLACK);
System.out.println("No more devices");

2 个答案:

答案 0 :(得分:0)

使用

tr.setVisibility(View.VISIBLE);

而不是

tr.setVisibility(1);

请注意,View.VISIBLE的常量值为0而不是1.因此,如果设置为1,则无法获得正确的结果。因此,不要使用int总是使用View.VISIBLEView.INVISIBLEView.GONE。它既可以提高可读性,又可以减少出错的几率

答案 1 :(得分:0)

错误:

LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tv.setLayout(layout);

错误是:

The TableRow Layout Params being applied to TextView.