Android在使用Activity,Fragment,Listview和Tabs时传递数据

时间:2017-01-31 20:42:13

标签: java android listview android-fragments

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

以下是我的主要活动。

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()方法抓取arraylist,然后使用适配器将内容放入主活动xml中的listview中。结果是所有选项卡在视觉上显示相同的视图。 (因为MainActivity的Listview覆盖了片段的列表视图)我真的只是试图从fp_get_Android_Contacts()方法中检索的内容一次显示在一个片段上。我已经研究过使用bundle,parcelables,intents和最近的接口,但是考虑到我的经验水平,成功的实现很难实现。我会欣赏一种特定的方法,而不是参考阅读的东西,因为我已经做了很多研究,并尝试了很多东西。

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

2 个答案:

答案 0 :(得分:2)

创建界面

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

让您的MainActivity实现此界面

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

你的片段

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的公共getter setter,并在片段中使用(MainActivity getActivity()).getArrayListAndroidContacts()来获取列表。由于可重用性,我更喜欢接口方法。

另外,为什么要创建viewpager,片段,如果你想通过过滤器选择(按alpha,chrono排序)重新排列数据,而不进行任何视图更改。

只需在mainmentivity中的floatingmenu / toolbarsidemenu,recyclerview(任何列表视图)和customadapter中添加过滤器菜单操作即可。根据过滤器选择重新排序您的联系人列表和notifydatasetchanged将完成您的所有工作。

如果您希望在单个屏幕中显示收藏夹,商家等类别的联系人,请转到标签页。

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

答案 1 :(得分:1)

您应该为这些标签设置多个标签和相应的片段。对 ? 我在你的代码中找不到。 对于每个片段,生成一个单独的.xml文件,并在每个片段中创建单独的列表视图,并相应地传递每个片段中的数据。你完成了。

例如,按字母顺序:创建片段AlphabetSortFragment,并为其创建一个.xml文件和listview或者回收者视图。

相关问题