现有 Activity, 分別方 UserinfoActivity 和 ShowActivity。現在要以UserlntoActivity 中通ート“査看” 按钮切换界面到 showActivity. 井代通如下参数:id=1 userame="eric', states=True, 切Showactivity/使用 Toast 显示接收到的参数,请写出两个 Actvity 中的楼心代码
时间: 2024-03-16 21:41:59 浏览: 15
以下是 `UserinfoActivity` 中的代码:
```java
public class UserinfoActivity extends AppCompatActivity {
private int id = 1;
private String username = "eric";
private boolean states = true;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_userinfo);
Button btnShow = findViewById(R.id.btn_show);
btnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 跳转到 ShowActivity,并传递参数
Intent intent = new Intent(UserinfoActivity.this, ShowActivity.class);
intent.putExtra("id", id);
intent.putExtra("username", username);
intent.putExtra("states", states);
startActivity(intent);
}
});
}
}
```
在 `UserinfoActivity` 中,我们首先获取了 `id`、`username` 和 `states` 参数。然后,我们在“查看”按钮的点击事件中,创建了一个 `Intent` 对象,并使用 `putExtra` 方法传递参数。最后,我们通过 `startActivity` 方法跳转到 `ShowActivity`。
以下是 `ShowActivity` 中的代码:
```java
public class ShowActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show);
// 获取传递的参数
int id = getIntent().getIntExtra("id", 0);
String username = getIntent().getStringExtra("username");
boolean states = getIntent().getBooleanExtra("states", false);
// 使用 Toast 显示接收到的参数
String text = "id=" + id + "\nusername=" + username + "\nstates=" + states;
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
}
```
在 `ShowActivity` 中,我们首先使用 `getIntent` 方法获取传递过来的参数。然后,我们使用 `Toast` 显示接收到的参数。