Android:活动之间数据的传递
建立两个活动,点击第一个活动的按钮,跳转到第二个活动,同将一句话“这个数据要被传过去”传到第二个活动上,且作为第二个活动中一个文本框的文本内容。
第一个活动页面布局activity_main.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="传递"
android:id="@+id/button1"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
第二个活动页面布局activity_data.xml代码:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".data">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/textView"/>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
第二个活动data.java代码:
package com.example.week4;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class data extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_data);
Intent intent = getIntent();
String data = intent.getStringExtra("extra_data");
TextView textView = findViewById(R.id.textView);
textView.setText(data);
}
}
第一个活动MainActivity.java代码:
package com.example.week4;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String data = "这个数据要被传出去";
Intent intent = new Intent(MainActivity.this, data.class);
intent.putExtra("extra_data",data);
startActivity(intent);
}
});
}
}
运行结果: