将数据从一个活动转移到另一个活动时,可以从一个EditText
转移到另一个EditText
的另一个Activity
我正在尝试将数据从一个EditText
的{{1}}传输到另一个Activity
的{{1}}。
答案 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;
您可以使用
访问textviewSceondActivity.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
的哈希图 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");