我正在尝试以下列方式动态添加TextView。但是在我运行应用程序后无法看到我的新TextView。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
TextView textView= (TextView) new TextView(this);
textView.setText("Hello");
textView.setBackgroundColor(0xff66ff66); // hex color 0xAARRGGBB
textView.setPadding(20, 20, 20, 20);
LinearLayout ll = (LinearLayout)findViewById(R.id.LinearLayout1);
textView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
ll.addView(textView);
ViewGroup vg = (ViewGroup) findViewById (R.id.LinearLayout1);
vg.invalidate();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
databaseHelper = new DatabaseHelper(getBaseContext());
try {
databaseHelper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
databaseHelper.openDataBase();
}
答案 0 :(得分:0)
删除这些行
ViewGroup vg = (ViewGroup) findViewById (R.id.LinearLayout1);
vg.invalidate();
答案 1 :(得分:0)
将textview添加到linearlayout后请求布局如下
ll.requestLayout();
答案 2 :(得分:0)
LayoutParams lparams = new LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tv=new TextView(this);
tv.setLayoutParams(lparams);
tv.setText("test");
this.linerLayout.addView(tv);
答案 3 :(得分:0)
删除xml并重新创建它后工作。