1. Intent传递数据
简单的创建一个输入文本框Edtext 一个button按钮进行跳转页面保存数据
editText=findViewById(R.id.editext);
btn_save=findViewById(R.id.btn_save);
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent(MainActivity.this,MainActivity2.class);
intent.putExtra("content",editText.getText().toString());
startActivity(intent);
}
});
跳转第二页后,一个获取数据按钮,和一个查看是否传递成功的文本框
之后在java文件里面 点击按钮获取数据并将数据传递到textview文本框里面
btn_save=findViewById(R.id.btn_save);
text=findViewById(R.id.text);
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = getIntent();
text.setText("获取的内容:"+intent.getStringExtra("content"));
}
});
2.使用SharedPreferences方法将数据存储下来,之后再用这个方法取出数据
一个(输入文本框)两个button按钮 (保存数据和获取数据)一个(textview查看是否获取数据)
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="10"
android:id="@+id/editext"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center">
<Button
android:id="@+id/btn_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="传递数据"/>
<Button
android:id="@+id/btn_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="保存数据"/>
</LinearLayout>
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#CC9490"
android:layout_marginTop="10dp"
android:textSize="30dp"/>
editText=findViewById(R.id.editext);
btn_save=findViewById(R.id.btn_save);
btn_pass=findViewById(R.id.btn_pass);
text=findViewById(R.id.text);
btn_save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("count", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("content",editText.getText().toString());
editor.apply();
Toast.makeText(MainActivity.this, "保存数据", Toast.LENGTH_SHORT).show();
}
});
btn_pass.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("count",Context.MODE_PRIVATE);
text.setText(sharedPreferences.getString("content",""));
Toast.makeText(MainActivity.this, "获取数据", Toast.LENGTH_SHORT).show();
}
});
3.还有bundle传递方法
这里就不做过多说明直接上代码
在发送方中,创建一个Bundle对象,并使用putXxx()方法将数据存储在Bundle中:
Intent intent = new Intent(context, TargetActivity.class);
Bundle bundle = new Bundle();
bundle.putXxx("key", value);
intent.putExtras(bundle);
在接收方中,使用getExtras()方法获取Intent附带的Bundle对象,然后从Bundle中获取数据:
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
dataType value = bundle.getXxx("key");
可以的话,点点关注打赏打赏!谢谢