【问题标题】:Add items to ListView in a fragment in one Activity by clicking a button in another activity通过单击另一个 Activity 中的按钮,将项目添加到一个 Activity 中的片段中的 ListView
【发布时间】:2017-06-26 16:56:32
【问题描述】:

首先,如果已经提出并回答了类似的问题,我深表歉意,但我浏览了大量帖子却没有任何运气。其次,我是一个绝对的初学者(已经编码了 6 周),所以如果我遗漏了一些概念或者如果有更好的做事方式,请随时赐教。

现在,这是我的问题: 在我的 MainActivity 上,我有一个带有 ListView 的 EventsFragment。 MainActivity 上还有一个 FloatingActionBar,单击它会加载另一个名为 CreateEventActivity 的 Activity。 CreateEventActivity 有一个 EditText 字段和一个创建按钮。我想要做的是当用户在 EditText 字段中输入一些文本并单击创建按钮时,它应该从 EditText 字段中获取字符串并在 ListView 上创建一个项目,并以 String 作为它的名称。此外,一旦单击创建按钮,它应该会返回到 MainActivity 中的 EventsFragment。

我按照建议使用了 startActivityForResults(),似乎我能够将 ArrayList 作为意图从 CreateEventActivity 传递回 MainActivity,这是我所能得到的。我认为我将列表发送到 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 -

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;
    }
}

提前感谢您的帮助:)

【问题讨论】:

  • 您可以将字符串作为意图传递回 mainactivity 并使用它创建适配器吗?

标签: java android listview android-fragments android-activity


【解决方案1】:

解决方案 1: 您需要有一个数据集,这对两个活动都是通用的。 每次单击时,都会向该数据集添加一个项目。 使用相同的数据集填充列表视图。 由于它们都处于不同的活动中,因此您需要保留该数据集。

您可以将其保存在本地,方法是使用table(database) 或作为json 字符串将其存储在[shared preference][1] 中。

另一个持久化数据集的捷径是将您的数据集作为Application 类中的属性,因此您可以从应用程序中的任何activity 添加和访问数据集,如application 类在应用程序的整个生命周期中都存在。 我不推荐这个。这很简单,也很有效,但它不是一个好的做法,并且会导致代码质量很差,但如果你只是想要一个快速的方法,你可以做到。

解决方案 2:在您的主要活动中,使用 startActivityForResult() 启动第二个活动。这会让你做的是让第二个活动与第一个活动对话。因此,当它回话时,您可以在第一个中知道在第二个中添加了多少项目,并相应地更新您的第一个活动的 listView。

【讨论】:

  • 我尝试了您的解决方案 2,但我肯定做错了什么,因为我遇到了崩溃。无论如何我可以发布我修改后的代码,这样你就可以看到我做错了什么?谢谢
  • 我已经更新了我的代码。你能看看吗?谢谢
  • 您遇到的崩溃是什么?请发布 logcat 行。还要调试列表的内容,尝试调试直到事情正常工作,就像你认为的那样。我不能为你调试它,而且它是程序员的必备技能。这是一个专业提示:不要假设,知道!记住这一点,直到你死!
  • 对不起,我可能应该提到这一点。我不会再撞车了。我修好了。现在代码编译并且应用程序运行,但它没有做它应该做的事情:即 listView 没有更新。只需检查我传递意图的代码,获取结果,然后将结果传递给片段。我只会将我的帖子编辑为该代码,以便您更轻松
  • 只是一个更新:您的解决方案有效。它崩溃的原因是因为我犯了一些新手错误。一旦我在片段中实现了 onResume,我就会更新列表。所以谢谢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-12
  • 2017-05-24
  • 1970-01-01
  • 2018-12-25
相关资源
最近更新 更多