我有一个使用putextra方法将数据从活动推送到另一个的代码,我想使用相同的密钥推送不同的值 代码:
String int_value = "int_value";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondScreen.class);
intent.putExtra(int_value , 0);
startActivity(intent);
}
});
Button btn2 = (Button) findViewById(R.id.btn2);
btn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, SecondScreen.class);
intent.putExtra(int_value , 1);
startActivity(intent);
}
});
在下一个活动中:
int value;
String int_value = "int_value";
View myLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second_screen);
Intent intent = getIntent();
int temp = intent.getIntExtra(int_value, value);
myLayout = findViewById(R.id.myLayout);
switch (value){
case 0:
myLayout.setBackgroundResource(R.drawable.a);
Log.e("VALUE" , String.valueOf(value));
break;
case 1:
myLayout.setBackgroundResource(R.drawable.b);
Log.e("VALUE" , String.valueOf(value));
break;
}
但是背景总是变成a.jpg虽然我通过0& 1(或者至少我以为我做过......) 这有什么问题?
答案 0 :(得分:1)
只需在切换为 temp
时更改值即可switch ( temp){
case 0:
myLayout.setBackgroundResource(R.drawable.a);
Log.e("VALUE" , String.valueOf(value));
break;
case 1:
myLayout.setBackgroundResource(R.drawable.b);
Log.e("VALUE" , String.valueOf(value));
break;
}
因为您要将值保存在 temp
中
int temp = intent.getIntExtra(int_value, value);