I know that there are many topics. I also read the documentation many times, but I cannot find a better way to pass data from activity to fragment.
I want to show the results of my search activity in two different layouts (list and map) by scrolling through tabbed views . I need to pass 2 data into fragments: "currentLocation", which is the current location of the user, and "result", which is a list of objects.
I skipped some parts of my code to make it more understandable.
SearchableActivity.java
public class SearchableActivity extends ActionBarActivity implements TabListener { List<PlaceModel> result = new ArrayList<PlaceModel>(); private SearchView mSearchView; private String currentLocation; AppSectionsPagerAdapter mAppSectionsPagerAdapter; ViewPager mViewPager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_searchable); final ActionBar actionBar = getSupportActionBar(); actionBar.setHomeButtonEnabled(true); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager()); mViewPager = (ViewPager) findViewById(R.id.pager); mViewPager.setAdapter(mAppSectionsPagerAdapter); mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); } }); actionBar.addTab(actionBar.newTab().setText("List").setTabListener(this)); actionBar.addTab(actionBar.newTab().setText("Map").setTabListener(this));
}
PlaceListFragment.java
public class PlaceListFragment extends Fragment { ListView listViewData; PlaceAdapter placeAdapter; List<PlaceModel> result = new ArrayList<PlaceModel>(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_list, container, false); Bundle args = getArguments(); listViewData = (ListView) rootView.findViewById(android.R.id.list);
AppSectionsPagerAdapter.java
public class AppSectionsPagerAdapter extends FragmentPagerAdapter { final int PAGE_COUNT = 2; public AppSectionsPagerAdapter(FragmentManager fm) { super(fm); } @Override public Fragment getItem(int arg0) { Bundle data = new Bundle(); switch(arg0) { case 0: PlaceListFragment fragment1 = new PlaceListFragment(); fragment1.setArguments(data); return fragment1; default: PlaceListFragment fragment2 = new PlaceListFragment(); fragment2.setArguments(data); return fragment2; } } @Override public int getCount() { return PAGE_COUNT; } }
android android-layout android-fragments android-view android-tabs
tsil
source share