向下一个Activity发送数据
Intent使用Bundle对象存放待传递的数据信息。
Bundle对象操作各类型数据的读写方法
a页面发送
package com.example.chapter03;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.chapter03.util.DateUtil;
import com.example.chapter03.util.Utils;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView tv_send;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_send = findViewById(R.id.tv_send);
findViewById(R.id.tv_send).setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent = new Intent(this, TextViewActivity.class);
Bundle bundle = new Bundle();
bundle.putString("request_time", DateUtil.getNowTime());
bundle.putString("request_content", tv_send.getText().toString());
intent.putExtras(bundle);
startActivity(intent);
}
}
b页面接收
package com.example.chapter03;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.chapter03.util.Utils;
public class TextViewActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_view);
TextView tv_receive = findViewById(R.id.tv_receive);
Bundle bundle = getIntent().getExtras();
String request_time = bundle.getString("request_time");
String request_content = bundle.getString("request_content");
String desc = String.format("受到请求消息:\n请求时间%s\n请求内容%s", request_time, request_content);
tv_receive.setText(desc);
}
@Override
public void onClick(View view) {
finish();
}
}