- 描述:界面与界面之间的通信是系统开发非常重要的一个环节,广泛存在于搜索等功能中
- 难度:初级
- 需要使用到Android中Intent机制(也可使用SharedPreferences存储机制)
- 效果展示
第一步:编写两个XXActivityUI布局
- 第一个XXActivity使用配置好的MainActivity,以下为UI布局(activity_main.xml)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="30dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户登录"
android:textSize="28dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="账号:"
android:textSize="25dp"/>
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="密码:"
android:textSize="25dp"/>
<EditText
android:id="@+id/key"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"/>
</LinearLayout>
<Button
android:id="@+id/btn_jump"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Jump"
android:background="#00000000"/>
</LinearLayout>
- 第二个XXActivity随便点就HomeActivity,以下为UI布局(activity_home.xml)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="@+id/showText"
android:textSize="30dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
第二步:编写代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Jump();
}
private void Jump() {
EditText name = findViewById(R.id.name);
EditText key = findViewById(R.id.key);
Button jump = findViewById(R.id.btn_jump);
jump.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,HomeActivity.class);
intent.putExtra("name", name.getText().toString());
intent.putExtra("key", key.getText().toString());
startActivity(intent);
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
init();
}
private void init() {
TextView text = findViewById(R.id.showText);
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String key = intent.getStringExtra("key");
text.setText("用户名:" + name + "\n密码:" + key);
}