第一个界面的布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.hzx.simple_intent.MainActivity">
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跳转到第二个Activity"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="第一个Activity"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</LinearLayout>
第二个界面的布局文件
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.hzx.simple_intent.Main2Activity">
<TextView
android:id="@+id/show_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
android:text="Activity2"/>
</android.support.constraint.ConstraintLayout>
第一个Activity
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String data = "Hello";
Intent intent = new Intent (MainActivity.this,Main2Activity.class);
intent.putExtra("extra_data",data);
startActivity(intent);
}
});
}
}
第二个Activity
public class Main2Activity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent = getIntent();
String Extra_data = intent.getStringExtra("extra_data");
TextView text = (TextView)findViewById(R.id.show_text);
text.setText(Extra_data);
}
}
效果
当点击按钮时,会跳转到第二个Activity,且传入字符串"Hello"
image.png
第二个Activity,从Intent获取到传入的字符串,显示到TextView中
image.png
网友评论