[英]Add items to ListView in a fragment in one Activity by clicking a button in another activity
first off I apologize if a similar question has already been asked and answered, but I have looked through tons of posts without any luck. 首先,我很抱歉是否已经提出并回答了类似的问题,但是我浏览了无数帖子,没有任何运气。 Second, I am an absolute beginner (been coding for 6 weeks), so if I'm missing some concepts or if there is a better way to do things, feel free to enlighten me.
其次,我是一个绝对的初学者(学习6周的时间),因此,如果我缺少某些概念或有更好的做事方法,请随时给我启发。
Now, here is my question: On my MainActivity, I have an EventsFragment which has a ListView . 现在,这是我的问题:在MainActivity上,我有一个EventsFragment,其中有一个ListView 。 There is also a FloatingActionBar on the MainActivity, which when clicked loads another Activity called CreateEventActivity.
MainActivity上还有一个FloatingActionBar,单击它会加载另一个称为CreateEventActivity的Activity。 The CreateEventActivity has an EditText field and a Create Button.
CreateEventActivity具有一个EditText字段和一个Create按钮。 What I wanna do is when the User enters some text in the EditText field and clicks the create Button, it should take the string from the EditText field and create an item on the ListView with String as it's name.
我要做的是,当用户在EditText字段中输入一些文本并单击create按钮时,它应该从EditText字段中获取字符串,并在ListView上创建一个名称为String的项目。 Also, as soon as the create button is clicked, it should go back to the EventsFragment in the MainActivity.
同样,一旦单击创建按钮,它应该回到MainActivity中的EventsFragment。
I used startActivityForResults(), as suggested and it seems that I am able to pass an ArrayList as an intent from CreateEventActivity back to MainActivity, and that is as far as I'm able to get. 我按照建议使用了startActivityForResults(),看来我能够将ArrayList作为一个意图从CreateEventActivity传递回MainActivity,据我所知。 I think the way I'm sending the list to the EventsFragment is wrong, as the listView is not updating.
我认为我将列表发送到EventsFragment的方式是错误的,因为listView没有更新。
MainActivity - 主要活动 -
public class MainActivity extends AppCompatActivity {
/**
* The {@link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {@link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {@link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {@link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), MainActivity.this);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//Iterate over all TabLayouts to set the custom View
for (int i = 0; i < tabLayout.getTabCount(); i++){
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(mSectionsPagerAdapter.getTabView(i));
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loadCreateEventActivity();
// Snackbar.make(view, "Here the create a New Event Screen will be displayed", Snackbar.LENGTH_LONG)
// .setAction("Action", null).show();
}
});
}
private void loadCreateEventActivity(){
Intent intent = new Intent(MainActivity.this, CreateEventActivity.class);
startActivityForResult(intent, 2);
}
public ArrayList<String>list = new ArrayList<>();
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2){
if (resultCode == RESULT_OK) {
list = data.getStringArrayListExtra("LIST_ITEMS");
}
}
}
public ArrayList<String> getList() {
return list;
}
CreatEventsActivity - CreatEventsActivity-
public class CreateEventActivity extends AppCompatActivity {
EditText createEventName;
Button createButton;
ArrayList<String> listItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_event);
createEventName = (EditText) findViewById(R.id.createEventName);
createButton = (Button) findViewById(R.id.createButton);
listItems = new ArrayList<String>();
listItems.add("First Item - added on Activity Create");
createButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(createEventName.getText().toString());
Intent intent = new Intent();
intent.putStringArrayListExtra("LIST_ITEMS", listItems);
setResult(RESULT_OK, intent);
createEventName.setText("");
finish();
}
});
}
}
EventsFragment - 活动片段-
public class EventsFragment extends Fragment {
public EventsFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_events, container, false);
MainActivity mainActivity = (MainActivity) getActivity();
ArrayList<String>list = mainActivity.getList();
ListView listView = (ListView)view.findViewById(R.id.list_view);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(),android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
return view;
}
}
Thanks for any help in advance :) 感谢您的任何帮助:)
Solution 1 : You need to have one data set, that is common to both activities. 解决方案1:您需要拥有一个数据集,这对于两个活动都是相同的。 Every time you click, you add add an item to that data set.
每次单击时,都会添加一个项目来添加该数据集。 The list view is populated using that very same data set.
列表视图是使用相同的数据集填充的。 Since they are both in different activities, you need to persist that data set.
由于它们都处于不同的活动中,因此您需要保留该数据集。
You can persist it locally, by storing it using a table(database) or as a json
string, in [shared preference][1]
. 您可以通过使用表(数据库)或将其存储为
[shared preference][1]
的json
字符串将其存储在本地。
Another short cut to persist the data set is to have your data set as a property in your Application
class, so you can add and access the dataSet from any activity
in the app, as the application
class is alive for the entire lifecycle of the app. 保留数据集的另一个捷径是将数据集作为
Application
类中的一个属性,因此您可以从应用程序中的任何activity
添加和访问dataSet,因为application
类在application
的整个生命周期中都有效。 I DON'T RECOMMEND THIS . 我不建议这样做 。 This is easy and it works, but it is not good practice and leads to terrible code quality, but if you just want a quick way to do it, you can do it.
这很容易并且有效,但是它不是很好的做法,并且会导致糟糕的代码质量,但是如果您只是想一种快速的方法,可以这样做。
Solution 2 : In your main activity, start the second activity using startActivityForResult()
. 解决方案2:在您的主要活动中,使用
startActivityForResult()
启动第二个活动。 What this will let you do is let second activity talk back to the first one. 这将使您做的是让第二个活动与第一个活动对话。 So when it talks back, you can know in the first one, how many items were added in the second one and update your first activity's listView accordingly.
因此,当它回话时,您可以在第一个活动中知道第二个活动中添加了多少项,并相应地更新了第一个活动的listView。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.