如何将数据从一个活动中的EditText传递到另一个活动中的TextView而不切换到第二个活动?

问题描述:

我想发送一个字符串变量,输入到ActivityOne的EditText中以传递数据并在ActivityThree上显示为TextView。但是,我遇到了问题,因为唯一的解决方案是我可以找到导致活动切换到ActivityThree的唯一解决方案。我想避免这种情况,或者甚至可以将数据发送到ActivityThree,然后单击按钮切换到ActivityTwo。任何帮助或重定向到当前的解决方案将不胜感激。如何将数据从一个活动中的EditText传递到另一个活动中的TextView而不切换到第二个活动?

+0

使用sharedpreference将当前输入保存到当前活动中并显示给其他活动。 –

如果要通过避免ActivityTwo将Activity1中的数据发送到ActivityThree,然后将该数据保存到静态变量中,然后在ActivityThree中使用该变量来设置TextView数据。

您可以简单地使用SharedPreferences来做到这一点。

  1. 设置在PreferenceEditText值从ActivityOne

    // EditText 
    EditText editText = (EditText) findViewById(R.id.editText); 
    
    SharedPreferences.Editor editor = getSharedPreferences("Your_Preference_Name", MODE_PRIVATE).edit(); 
    editor.putString("KEY_VALUE", editText.getText().toString()); 
    editor.commit(); 
    
  2. ActivityThree,从Preference检索值:

    SharedPreferences prefs = getSharedPreferences("Your_Preference_Name", MODE_PRIVATE); 
    String editTextValue = prefs.getString("KEY_VALUE", null); 
    
    // TextView 
    TextView textView = (TextView) findViewById(R.id.textView); 
    textView.setText(editTextValue); 
    

希望这将有助于〜

请在Application类中使用全局变量,并在ActivityOne中设置其值,并从ActivityThree中读取相同的值。全局变量可用于整个项目活动。

最好的方法是使用输入额外。在活动这一块做

Intent i = new Intent(ActivityOne.this, ActivityThree.class); 
i.putExtra("label", "label_text"); 
startActivity(i); 

然后接收字符串在活动三这样:

EditText input = //intialize it in OnCreate 
Intent intent = getIntent(); 
String data = intent.getExtras().getString("label"); 
input.setText(data); 

有这么多的方式来做到这一点。但它在很大程度上取决于你打算做什么数据和你的情况.. 如果你想显示的活动中三个数据比可以使数据persist后来表现出来活动时三是创建或恢复,现在:

1 - 如果你想显示数据在活动三中,并且您希望该值仅在当前会话中持续存在时,您可以使用Global Variable或甚至静态其中一个,如果您将期望值定义为活动三中的静态变量,那么您可以轻松访问它并使用它它不需要甚至创建活动:

public ActivityThree extends Activity { 
    public static String myValue; 

2 - 如果你想显示在活动的三个数据以及要将数据坚持即使应用程序被关闭可以使用SharedPreferences如下所述: https://developer.android.com/training/basics/data-storage/shared-preferences.html

3-如果您想在活动三中运行后台任务确定价值,您可以使用LocalBroadcastManagerhttps://www.intertech.com/Blog/using-localbroadcastmanager-in-service-to-activity-communications/