动态添加视图

时间:2013-09-04 20:13:32

标签: android dynamic view textview

我正在尝试在Textview点击的主要活动中动态添加Button。当我运行它时,AVm说你的应用程序已被意外停止。 这是我的代码

public class MainActivity extends Activity {

Button addText = (Button) findViewById(R.id.btnAddText);    
//Creatinag object of RelativeLaout and referencing to Main actvivty layout. 
RelativeLayout rl = (RelativeLayout) findViewById(R.id.rellayout_Id);   
TextView tv ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

addText.setOnClickListener( new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        tv = new TextView(MainActivity.this);
        tv.setText("Dynamix TextView");
        tv.setPadding(2, 15, 0, 0);         
        rl.addView(tv);

    }
});

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

1 个答案:

答案 0 :(得分:2)

如果未在第一次更改中设置,则无法在布局中找到元素请尝试:

 Button addText;
 RelativeLayout rl;       
 TextView tv ;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);//layout first
 addText  = (Button) findViewById(R.id.btnAddText);
 rl = (RelativeLayout) findViewById(R.id.rellayout_Id);    
 addText.setOnClickListener( new View.OnClickListener() {

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    tv = new TextView(MainActivity.this);
    tv.setText("Dynamix TextView");
    tv.setPadding(2, 15, 0, 0);         
    rl.addView(tv);

   }
  });

}
相关问题