将数据从EditText从一个活动传输到另一个活动的EditText

时间:2019-02-19 05:28:48

标签: android

将数据从一个活动转移到另一个活动时,可以从一个EditText转移到另一个EditText的另一个Activity

我正在尝试将数据从一个EditText的{​​{1}}传输到另一个Activity的{​​{1}}。

4 个答案:

答案 0 :(得分:1)

1)方式

第一次活动

Intent i = new Intent(this, ActivityTwo.class);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete);
String getrec=textView.getText().toString();



//Create the bundle
Bundle bundle = new Bundle();

//Add your data to bundle
bundle.putString(“data”, getrec);

//Add the bundle to the intent
i.putExtras(bundle);

//Fire that second activity
startActivity(i);

您获得的第二次活动

//Get the bundle
Bundle bundle = getIntent().getExtras();

//Extract the data…
String stuff = bundle.getString(“data”); 

2)方式

public static AutoCompleteTextView textView;

您可以使用

访问textview
SceondActivity.textview;

3种方式

将值存储在首选项或数据库中

答案 1 :(得分:0)

您可以将1st EditText的内容作为额外的意图发送给另一个活动。在目标“活动”中,调用getIntent()提取额外的意图,然后可以在该活动的EditText上调用setText()。

活动A:

String data=myEditText.getText().toString();
Intent i=new Intent(ActivityA.this,ActivityB.class); //Create Intent to call ActivityB
i.putExtra("editTextKey",data);
startActivity(i);

活动B:

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_b_layout);
EditText newEditText=findViewById(R.id.new_edittext_id); //Get the reference to your edittext
String receivedData = getIntent().getStringExtra("editTextKey");
newEditText.setText(receivedData); //Set the data to new editteext
...
}

答案 2 :(得分:0)

意图用于活动之间的通信。您应该使用EditText.getText()。toString()从EditText中获取文本,并创建一个Intent来包装要传递的值,例如;

Intent in = new Intent(FirstActivity.this, TargetActivity.class).putExtra("STRING IDENTIFIER","string value from edittext");

您可以检索此值并将其设置在EditText中 选项B使用共享的首选项,例如我使用的此类:

class QueryPreferences 
{
private static final String TEXT_ID = "2";
    static void setPreferences(String text, Context context)
    {
         PreferenceManager.getDefaultSharedPreferences(context)
                          .edit()
                          .putString(TEXT_ID,text)
                          .apply();
    }
    static String getPreferences(Context context)
    {
         return PreferenceManager.getDefaultSharedPreferences(context).getString(TEXT_ID,"");
    }
}

答案 3 :(得分:0)

Ref:What's the best way to share data between activities?

您可以通过以下方式实现此目标

  • 在意图内发送数据
  • 静态字段
  • WeakReferences的哈希图
  • 持久对象(sqlite,共享首选项,文件等)

TL; DR :共有两种共享数据的方式:在意向附加中传递数据或将其保存在其他地方。如果数据是原语,字符串或用户定义的对象:请将其作为附加意图的一部分发送(用户定义的对象必须实现Parcelable)。如果传递复杂对象,则将一个实例保存在其他地方的一个实例中,然后从启动的活动中访问它们。

有关如何以及为何实施每种方法的一些示例:

在意图内发送数据

Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("some_key", value);
startActivity(intent);

关于第二个活动:

Bundle bundle = getIntent().getExtras();
int value = bundle.getInt("some_key");