[英]Android UI not Updating programmatically
我正在編寫下面的代碼..但是某些部分正在工作,而某些部分卻無法工作,我不知道為什么。
這些工作正常
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");
采用
tr.setVisibility(View.VISIBLE);
代替
tr.setVisibility(1);
請注意,View.VISIBLE的常量值為0而不是1。因此,如果將其設置為1,則不會得到正確的結果。 因此,始終使用View.VISIBLE
, View.INVISIBLE
, View.GONE
而不是int。 它既可以提高可讀性,又可以減少出錯的機會
錯誤:
LayoutParams layout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
tv.setLayout(layout);
錯誤是:
The TableRow Layout Params being applied to TextView.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.