我試圖在選擇子活動中的彈出菜單中的項目時更改主要活動的背景顏色。但是,當我運行該應用程序並選擇所述項目時,該應用程序崩潰。這是次活動代碼:選擇彈出菜單項目時發送意圖
public class Modify extends AppCompatActivity {
Button button, submit;
EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.modify);
button = (Button) findViewById(R.id.button);
submit = (Button) findViewById(R.id.submit);
edit = (EditText) findViewById(R.id.editText);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu pop = new PopupMenu(Modify.this, button);
pop.getMenuInflater().inflate(R.menu.menu,pop.getMenu());
pop.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
@Override
public boolean onMenuItemClick(MenuItem item){
Intent i = new Intent(Modify.this, MainActivity.class);
switch (item.getItemId()){
case R.id.red:
i.putExtra("color","red");
break;
//TODO add more colours
default:
return false;
}
return true;
}
});
pop.show();
}
});
submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String message = edit.getText().toString();
Intent intent = new Intent();
intent.putExtra("MESSAGE", message);
setResult(2, intent);
finish();
}
});
}
}
我真的不知道,如果在每一種情況下,我宣佈的意圖實際上是讓回changeBackground方法的主要活動:
public class MainActivity extends AppCompatActivity {
//GLOBALS
TextView txt;
Button btn;
RelativeLayout rel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView) findViewById(R.id.Text);
btn = (Button) findViewById(R.id.Btn);
rel = (RelativeLayout) findViewById(R.id.activity_main);
Intent intent = getIntent();
String color = intent.getStringExtra("color");
changeBackground(color);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//ON CLICK SETS INTENT
Intent intent = new Intent(MainActivity.this, Modify.class);
//INTENT STARTS ACTIVITY 2
startActivityForResult(intent, 2);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
//SET TEXT WHEN RESULT IS ACCEPTED
String message = data.getStringExtra("MESSAGE");
txt.setText(message);
}
}
public void changeBackground(String color) {
if (color.equals("red")) {
rel.setBackgroundColor(Color.RED);
} else if (color.equals("green")) {
rel.setBackgroundColor(Color.GREEN);
} else if (color.equals("blue")) {
rel.setBackgroundColor(Color.BLUE);
}
}
}
你的'startActivityForResult()'在哪裏?顯示logcat – tahsinRupam
我有一個startActivityForResult()文本額外。然而,我可以用一個子活動的意圖來設置主活動的背景顏色,這個子活動會發送額外的東西作爲changeBackground方法的參數傳遞嗎? –
請在下面檢查我的答案。 – tahsinRupam