1.点击跳转页面
@Override
public void onClick(View v) {
Intent intent = new Intent(this, MyActivity2.class);
// 1.当你想打开一个界面,并且从新的界面获取数据时候,需要调用此方法
// requestCode 请求码
startActivityForResult(intent, 1);
}
2.新的页面回传值
public class MyActivity2 extends AppCompatActivity implements View.OnClickListener {
private ImageView img1;
private ImageView img2;
private ImageView img3;
private ImageView img4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my2);
img1 = findViewById(R.id.e1);
img2 = findViewById(R.id.e3);
img3 = findViewById(R.id.e2);
img4 = findViewById(R.id.e4);
img1.setOnClickListener(this);
img2.setOnClickListener(this);
img3.setOnClickListener(this);
img4.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent();
switch (v.getId()) {
case R.id.e1:
intent.putExtra("icon", R.mipmap.e0);
break;
case R.id.e3:
intent.putExtra("icon", R.mipmap.e1);
break;
case R.id.e2:
intent.putExtra("icon", R.mipmap.e2);
break;
case R.id.e4:
intent.putExtra("icon", R.mipmap.e3);
break;
}
// 给旧的页面传值
setResult(0, intent);
// 返回页面,如果没有这句,数据返不回去
finish();
}
}
3.获取回调的值
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// 推荐使用resultCode
if (data != null) {
if requestCode == 1 {
int iconResId = data.getIntExtra("icon", 0);
imgV.setImageResource(iconResId);
}
}
}