0

我正在尝试在点击时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;
}

}

4

1 回答 1

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);

   }
  });

}
于 2013-09-04T20:16:34.950 回答