我希望我的MainActivity显示不同TextView的列表。 第二个Activity包含一个EditText字段。当我在第二个Activity中点击“Submit”时,我想将EditText中的String添加到MainActivity中的TextViews列表中。
我遇到的问题是每次都启动一个新的MainActivity,因此只显示最新的Text。我想回到我的MainActivity,并在那里“收集”文本。这是一些代码:
MainActivity:
public class FullTimeline extends AppCompatActivity {
private LinearLayout linLayout;
private FloatingActionButton addEntry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_timeline);
linLayout = (LinearLayout) findViewById(R.id.entriesLinear);
addEntry = (FloatingActionButton) findViewById(R.id.floatingActionButton); //starts the second Activity with the EditText
//Here I want to get the text from my second Activity
Intent intent = getIntent();
String entry = intent.getStringExtra(EntryTextActivity.EXTRA_ENTRY);
linLayout.addView(createNewTextView(entry), 0);
}
public void openEntryActivity(View view){
Intent intent = new Intent(this, EntryTextActivity.class);
startActivity(intent);
}
private TextView createNewTextView(String text) {
final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setText(text);
return textView;
}
}
这是EditText的第二个Activity:
public class EntryTextActivity extends AppCompatActivity {
public static final String EXTRA_ENTRY = "com.xyz.ENTRY";
private Button submitButton;
private EditText editTextEntry;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry_text);
submitButton = (Button) findViewById(R.id.submitButton);
submitButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(EntryTextActivity.this, FullTimeline.class);
editTextEntry = (EditText) findViewById(R.id.editTextEntry);
String entryText = editTextEntry.getText().toString();
intent.putExtra(EXTRA_ENTRY, entryText);
startActivity(intent);//this starts a new instance of the MainActivity ?
}
});
}
}
我希望这有助于理解我的问题。我在这里找不到任何有效的解决方案。
答案 0 :(得分:1)
您需要使用startActivityForResult()
这是Nishant关于如何使用它的简单解释: - https://stackoverflow.com/a/10407371/5648172
基本上,您希望使用EntryTextActivity
代替startActivityForResult()
开始startActivity()
。
答案 1 :(得分:0)
我还没有测试过,但我认为如果您不想使用数据库,可以将MainActivity设置为" singleInstance"在你的清单中:
<activity android:name="{your }" android:launchMode= "singleInstance" />
然后,您可以在MainActivity的onResume
中添加新文本 @Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
String entry = intent.getStringExtra(EntryTextActivity.EXTRA_ENTRY);
linLayout.addView(createNewTextView(entry), 0);
}