java - Android 在使用 Activity、Fragment、Listview 和 Tabs 时传递数据

标签 java android listview android-fragments

在我的 MainActivity 中,我派生了一个数据数组列表。这里的技巧是,我试图根据所选的选项卡以不同的方式在 ListView 中重新排列此数据集合(按字母顺序、按时间顺序等),我有执行此操作的代码。

以下是我的主要 Activity 。

public class MainActivity extends AppCompatActivity {

    private SectionsPagerAdapter mSectionsPagerAdapter;

    private ViewPager mViewPager;
    private FloatingActionButton fab;
    private final int PICK = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        fp_get_Android_Contacts();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // 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);
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Intent.ACTION_PICK,
                        ContactsContract.Contacts.CONTENT_URI);
                // calling OnActivityResult with intenet And Some conatct for Identifie
                startActivityForResult(intent, PICK);
            }
        });
    }

    public class Android_Contact {
        public String android_contact_Name = "";
        public String android_contact_TelefonNr = "";
        public int android_contact_ID = 0;
    }

    public void fp_get_Android_Contacts() {
        ArrayList<Android_Contact> arrayListAndroidContacts = new ArrayList<Android_Contact>();

        Cursor cursor_Android_Contacts = null;
        ContentResolver contentResolver = getContentResolver();
        try {
            cursor_Android_Contacts = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
        } catch (
                Exception ex
                )

        {
            Log.e("Error on contact", ex.getMessage());
        }
        if (cursor_Android_Contacts.getCount() > 0)

        {

            while (cursor_Android_Contacts.moveToNext()) {

                Android_Contact android_contact = new Android_Contact();
                String contact_id = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts._ID));
                String contact_display_name = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

                android_contact.android_contact_Name = contact_display_name;

                int hasPhoneNumber = Integer.parseInt(cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
                if (hasPhoneNumber > 0) {

                    Cursor phoneCursor = contentResolver.query(
                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI
                            , null
                            , ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"
                            , new String[]{contact_id}
                            , null);

                    while (phoneCursor.moveToNext()) {
                        String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        android_contact.android_contact_TelefonNr = phoneNumber;

                    }
                    phoneCursor.close();
                }

                arrayListAndroidContacts.add(android_contact);

            }
            Collections.reverse(arrayListAndroidContacts);
            ListView listView_Android_Contacts = (ListView) findViewById(R.id.listview_Android_Contacts);

            Adapter_for_Android_Contacts adapter = new Adapter_for_Android_Contacts(this, arrayListAndroidContacts);

            listView_Android_Contacts.setAdapter(adapter);
        }
    }

    public class Adapter_for_Android_Contacts extends BaseAdapter {

        Context mContext;
        List<Android_Contact> mList_Android_Contacts;

        public Adapter_for_Android_Contacts(Context mContext, List<Android_Contact> mContact) {
            this.mContext = mContext;
            this.mList_Android_Contacts = mContact;
        }

        public int getCount() {
            return mList_Android_Contacts.size();
        }

        public Object getItem(int position) {
            return mList_Android_Contacts.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            View view = View.inflate(mContext, R.layout.contactlist_android_items, null);
            TextView textview_contact_Name = (TextView) view.findViewById(R.id.textview_android_contact_name);
            textview_contact_Name.setText(mList_Android_Contacts.get(position).android_contact_Name);
            view.setTag(mList_Android_Contacts.get(position).android_contact_Name);
            return view;
        }

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch (position) {
                case 0:

                    Tab2AZ tab2 = new Tab2AZ();
                    return tab2;
                case 1:
                    Tab1Recents tab1 = new Tab1Recents();
                    return tab1;
                case 2:
                    Tab3Location tab3 = new Tab3Location();
                    return tab3;
                case 3:
                    Tab4Groups tab4 = new Tab4Groups();
                    return tab4;
                default:
                    return null;
            }
        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "A-Z";
                case 1:
                    return "RECENT";
                case 2:
                    return "LOCATION";
                case 3:
                    return "TAGS";
            }
            return null;
        }
    }
}

为了节省时间,fp_get_Android_Contacts() 方法会获取数组列表,然后使用适配器将内容放入主 Activity xml 中的 ListView 中。结果是所有选项卡在视觉上显示相同的 View 。 (因为 MainActivity 的 ListView 覆盖了 fragment 的 ListView )我实际上只是想将从 fp_get_Android_Contacts() 方法检索到的内容一次显示在一个 fragment 上。我研究过使用 bundle 、可分包、 Intent 和最近的接口(interface),但考虑到我的经验水平,成功的实现可能很难实现。希望有一种具体的方法而不是引用来阅读一些东西,因为我已经做了很多研究并尝试了很多事情。

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View rootView = inflater.inflate(R.layout.tab1_recent, container, false);
        return rootView;
    }
}

最佳答案

创建接口(interface)

public interface FragmentListener {
  void setArrayListAndroidContacts(List<Android_Contact> contacts);
  List<Android_Contact> getArrayListAndroidContacts();
}

让你的MainActivity实现这个接口(interface)

public class MainActivity extends AppCompatActivity implements FragmentListener {
//global field
private List<Android_Contact> arrayListAndroidContacts;
...
//your code
...
//override methods of interface
@Override
void setArrayListAndroidContacts(List<Android_Contact> contacts){
this.arrayListAndroidContacts = contacts;
}

@Override
List<Android_Contact> getArrayListAndroidContacts(){
return this.arrayListAndroidContacts;
}

你的 fragment

public class YourFragment extends Fragment{

private FragmentListener mListener;

...
//in onCreateView
//this will give you list 
mListener.getArrayListAndroidContacts();
....

@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof FragmentListener) {
            mListener = (FragmentListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement FragmentListener");
        }
    }
}

另一种方法是在 MainActivity 中创建 arrayListAndroidContacts 的公共(public) getter setter,并在 fragment 中使用 (MainActivity getActivity()).getArrayListAndroidContacts() 来获取列表。由于可重用性,我更喜欢接口(interface)方法。

如果您想通过过滤器选择(按 alpha、chrono 排序)重新排列数据而不更改任何 View ,为什么还要创建 viewpager、fragments。

只需在 float 菜单/工具栏侧边菜单、回收器 View (任何 ListView )中添加过滤器菜单操作,并在 Mainactivity 中为其添加自定义适配器。根据过滤器选择重新排序您的联系人列表,notifydatasetchanged 将完成您的所有工作。

如果您希望在单个屏幕中显示联系人类别(如 Collection 夹、业务等),请使用选项卡。

建议:- 请将您的自定义 BaseAdapter 代码与 MainActivity 分开,以便更好地维护源代码。

关于java - Android 在使用 Activity、Fragment、Listview 和 Tabs 时传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41967108/

相关文章:

android - SDK 管理器未在 Android Studio 中打开

android - 即使有 Intent 过滤器,我的应用程序在共享对话框中也不可见

当正则表达式正确时 Java 正则表达式问题

Java 附加 API

java - 艾玛(Emma)错误地仪表化了类(class)

android - eclipse adt 17 和 libs 文件夹

java - Android listView.setOnItemClickListener(this)在运行时崩溃

android - ListView 和可变高度项目导致滚动问题

c# - 如何避免重复代码提高效率

java - 对 REF 游标使用 SqlOutParameter(String name, int sqlType)