我想在android studio中添加一個按鈕到我的應用程序,我跟着一個YouTube視頻,但每次運行它時,都會關閉。我不知道爲什麼會發生這種情況,也不知道如何讓按鈕工作。如果任何人都可以幫到那會很好如何在android工作室添加按鈕
public class MainActivity extends Activity {
Draw draw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout l = new LinearLayout(this);
l.setOrientation(LinearLayout.VERTICAL);
setContentView(l);
l.addView(new Draw(this));
setContentView(R.layout.activity_main);
draw = new Draw(this);
draw.setBackgroundColor(Color.BLUE);
setContentView(draw);
setUpBlockBtn();
}
private void setUpBlockBtn(){
Button addBlockButton = (Button)findViewById(R.id.btnBlock);
addBlockButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("DemoButtonApp", "you clicked the button");
//finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
把你的logcat輸出這裏瞭解錯誤?但可能會發生這種情況,因爲你使用了setContentView(l);兩次。 –
可能重複[如何在android中動態添加按鈕?](http://stackoverflow.com/questions/1851633/how-to-add-button-dynamically-in-android) –