Examples in pictures:
Empty PagerView
PagerView with new content(SlidingTabLayout doesn't update)
New instance of view(SlidingTabLayout updated);
This is my code:
public class CharSortFragment extends Fragment {
private final String TAG = "CharSortFragment";
private ViewPager viewPager;
private TabsPagerAdapter tabsAdapter;
private SlidingTabLayout slidingTabLayout;
private FragmentActivity activity;
public CharSortFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d(TAG, "OnCreate view...");
final View view = inflater.inflate(R.layout.char_sort_fragment, container, false);
activity = getActivity();
Log.d(TAG, "Init add button...");
FloatingActionButton addButton = (FloatingActionButton) view.findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "Add button was clicked...");
startActivityForResult(new Intent(getActivity(), EditActivity.class), 1);
}
});
viewPager = (ViewPager) view.findViewById(R.id.pager);
tabsAdapter = new TabsPagerAdapter(activity.getSupportFragmentManager());
viewPager.setAdapter(tabsAdapter);
Log.d(TAG, "Connecting PagerSlidingTabStrip...");
slidingTabLayout = (SlidingTabLayout) view.findViewById(R.id.tabs);
slidingTabLayout.setViewPager(viewPager);
Log.d(TAG, "OnCreate finished!");
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "On activity result: " + resultCode);
if(resultCode == 1) {
Log.d(TAG, "Notify data changes...");
tabsAdapter.updateCharSet();
tabsAdapter.notifyDataSetChanged();
slidingTabLayout.invalidate();
CardListFragment cardListFragment = tabsAdapter.currentFragment;
/* Обновляем TabsAdapter всегда, ибо я ленивая жопа
if(tabsAdapter.currentFragment == null) {
tabsAdapter.updateCharSet();
tabsAdapter.notifyDataSetChanged();
cardListFragment = tabsAdapter.currentFragment;
}
*/
RecyclerViewAdapter recyclerViewAdapter = cardListFragment.getAdapter();
recyclerViewAdapter.updateDataSet();
recyclerViewAdapter.notifyDataSetChanged();
Log.d(TAG, "Views was notified!");
}
}
public class TabsPagerAdapter extends FragmentPagerAdapter {
private final String TAG = "TabsPagerAdapter";
private final HashSet<TongueTwister> data = TongueTwistersStorageManager.getInstance().getData();
private final ArrayList<Character> characters = new ArrayList<>();
private CardListFragment currentFragment;
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
Log.i(TAG, "Creating TabsPagerAdapter...");
updateCharSet();
}
#Override
public Fragment getItem(int position) {
char charAtCurrentPos = characters.get(position);
return CardListFragment.newInstance(charAtCurrentPos);
}
protected void updateCharSet() {
this.characters.clear();
this.characters.addAll(generateCharList());
}
private ArrayList<Character> generateCharList() {
Log.i(TAG, "Generating char list...");
Log.i(TAG, "Total tongue twisters: " + data.size());
HashSet<Character> hashCharacters = new HashSet<>();
for (TongueTwister tongueTwister : data) {
for(char character : tongueTwister.getCharacters()) {
if(!hashCharacters.contains(character)) {
Log.i(TAG, "Char: " + character);
hashCharacters.add(character);
}
}
}
Log.i(TAG, "Sorting...");
ArrayList<Character> characters = new ArrayList<>(hashCharacters);
Collections.sort(characters);
Log.i(TAG, "Char list was generated!");
return characters;
}
#Override
public int getCount() {
return characters.size();
}
#Override
public CharSequence getPageTitle(int position) {
return String.valueOf(characters.get(position));
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
currentFragment = (CardListFragment) object;
}
}
}
How can i refresh SlidingTabLayout? (slidingTabLayout.invalidate() doesn't works for me)
Found the solution!
Just set ViewPager after you update its adapter:
tabsAdapter.updateCharSet(); // Updating FragmentPagerAdapter
tabsAdapter.notifyDataSetChanged();
slidingTabLayout.setViewPager(viewPager); // Updating SlidingTabStrip
Related
I want to delete a fragment and it's view from a tablayout when a checkbox is checked from a recyclerview. I have skipped the initializing codes and will share only the adapter codes (as that's where the work is) like below:
ViewpagerAdapter code:
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String TAG = ViewPagerAdapter.class.getSimpleName();
private List<Fragment> fragmentList = new ArrayList<>();
private List<String> titlesList = new ArrayList<>();
private Context context;
private TabLayout tabLayout;
private ViewPager viewPager;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public ViewPagerAdapter(FragmentManager fm, Context ctx, ViewPager viewPager, TabLayout tabLayout) {
super(fm);
this.context = ctx;
this.viewPager = viewPager;
this.tabLayout = tabLayout;
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentList.size();
}
public void addFragTab(Fragment fragment, String name){
fragmentList.add(fragment);
titlesList.add(name);
}
public void addFragLastPosition(Fragment fragment, String name){
fragmentList.add(fragmentList.size(), fragment);
titlesList.add(name);
}
public void removeFrag(int position){
removeTab(position);
Fragment fragment = fragmentList.get(position);
fragmentList.remove(fragment);
titlesList.remove(position);
destroyFragmentView(viewPager, position, fragment);
notifyDataSetChanged();
}
private void destroyFragmentView(ViewGroup container, int position, Object obj) {
FragmentManager manager = ((Fragment) obj).getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.remove((Fragment) obj).commit();
}
private void removeTab(int position) {
if (tabLayout.getChildCount() > 2){
tabLayout.removeTabAt(position);
}
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return titlesList.get(position);
}
}
and recyclerview adapter with checkbox to delete and add fragment:
public class PrefsAdapter extends RecyclerView.Adapter<PrefsCustomizeViewHolder> {
private static final String TAG = PrefsAdapter.class.getSimpleName();
private final Context context;
private List<Customize> itemsList;
private long id_nature, id_space;
private Customize cust;
private String nature, space;
private ViewPagerAdapter pagerAdapter;
public PrefsAdapter(Context context, List<Customize> itemsList) {
this.context = context;
this.itemsList = itemsList;
pagerAdapter = new ViewPagerAdapter(((AppCompatActivity)context).getSupportFragmentManager());
}
#Override
public PrefsCustomizeViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.prefs_customize_items_layout, parent, false);
return new PrefsCustomizeViewHolder(view);
}
#Override
public void onBindViewHolder(final PrefsCustomizeViewHolder viewholder, final int position) {
final Customize customize = itemsList.get(position);
Picasso.with(context)
.load(customize.getIcon())
.fit()
.into(viewholder.prefsSelImg);
switch (position) {
case 0:
cust = new Select()
.from(Customize.class)
.where("tabName = ? ", Constants.NATURE)
.executeSingle();
if (cust != null) {
nature = cust.tabName;
Log.d(TAG, "Nature Tab From DB:\t" + nature);
id_nature = cust.getId();
Log.d(TAG, "Nature Tab Id from DB:\t" + id_nature);
viewholder.prefsCheckBox.setChecked(true);
} else {
viewholder.prefsCheckBox.setVisibility(View.INVISIBLE);
viewholder.prefsCheckBox.setChecked(false);
}
break;
case 1:
cust = new Select()
.from(Customize.class)
.where("tabName = ? ", Constants.SPACE)
.executeSingle();
if (cust != null) {
space = cust.tabName;
Log.d(TAG, "Space Tab From DB:\t" + space);
id_space = cust.getId();
Log.d(TAG, "Space Tab Id from DB:\t" + id_space);
viewholder.prefsCheckBox.setChecked(true);
} else {
viewholder.prefsCheckBox.setVisibility(View.INVISIBLE);
viewholder.prefsCheckBox.setChecked(false);
}
break;
}
viewholder.prefsSelImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (position) {
case 0:
if (viewholder.prefsCheckBox.isChecked()){
viewholder.prefsCheckBox.setChecked(false);
//Customize.delete(Customize.class, id_nature);
pagerAdapter.removeFrag(1); // not working
} else {
viewholder.prefsCheckBox.setChecked(true);
customize.setTabId(UUID.randomUUID().toString());
customize.setTabName(Constants.NATURE);
customize.save();
pagerAdapter.addFragTab(new NatureFrag(), Constants.NATURE); // not working too
viewholder.prefsCheckBox.setVisibility(View.VISIBLE);
}
break;
case 1:
if (viewholder.prefsCheckBox.isChecked()){
viewholder.prefsCheckBox.setChecked(false);
Customize.delete(Customize.class, id_space);
Log.d(TAG, "Deleted Space id:\t" + id_space); // prints right log detail
pagerAdapter.removeTab(new SpaceFragment(), Constants.SPACE);
} else {
viewholder.prefsCheckBox.setChecked(true);
customize.setTabId(UUID.randomUUID().toString());
customize.setTabName(Constants.NATURE);
customize.save();
pagerAdapter.addTab(new SpaceFragment(), Constants.SPACE);
viewholder.prefsCheckBox.setVisibility(View.VISIBLE);
}
break;
}
}
});
}
#Override
public int getItemCount() {
if (itemsList == null) {
return 0;
}
return itemsList.size();
}
}
The method to delete the tab doesn't work. Can anyone help out with this implementation or another way? Thanks.
I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}
I am implementing nested fragments in a ViewPager. When I perform the transaction by replacing the child fragment in the parent fragment after executing addToBackStack(), I am able to see the view shown below. But when I press back button and the code reaches the MainActivity's onBackPressed() method, I notice the stack size is 1, and I successfully popout the Fragment. The problem starts now
My app closes and for a brief amount of time, I see my child fragment closing and then the app closing.
MainActivity
public class MainActivity extends FragmentActivity implements FragmentCommunicationListener {
ViewPager viewPager;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//createTabs();
viewPager = (ViewPager) findViewById(R.id.pager);
Fragment[] fragments = new Fragment[]{
new ViewStudentsFragment(),
new AddStudentFragment()
};
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), this, fragments);
viewPager.setAdapter(pagerAdapter);
}
#Override
public void passMsg(Fragment fragment, Bundle msg) {
int currentItem = viewPager.getCurrentItem();
Fragment targetFragment;
if (currentItem == 0) {
targetFragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + 1);
((AddStudentFragment) targetFragment).renderData(msg);
viewPager.setCurrentItem(1);
} else {
targetFragment = getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + 0);
((ViewStudentsFragment) targetFragment).updateList(msg,viewPager);
viewPager.setCurrentItem(0);
}
}
#Override
public void onBackPressed() {
ViewStudentsFragment fragment = (ViewStudentsFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + 0);
super.onBackPressed();
if (fragment.getChildFragmentManager().getBackStackEntryCount() != 0) {
fragment.getChildFragmentManager().popBackStack();
}
}
}
Parent Fragment
public class ViewStudentsFragment extends Fragment {
ArrayList<Student> studentList = new ArrayList<Student>();
ListView list;
ListViewAdapter listAdapter;
GridView grid;
FragmentCommunicationListener fragComm = null;
int resIdView, resIdSort;
GridViewAdapter gridAdapter;
static ImageButton toggleView, toggleSort;
View view;
ViewPager viewPager=null;
public ViewStudentsFragment() {
}
private static ViewStudentsFragment viewStudentsFragment;
FragmentTransaction transaction;
Fragment details ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_view_students, container, false);
toggleView = (ImageButton) view.findViewById(R.id.viewImageButton);
toggleSort = (ImageButton) view.findViewById(R.id.sortImageButton);
transaction= getChildFragmentManager().beginTransaction();
view.findViewById(R.id.container).setVisibility(View.GONE);
...
toggleView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
}
});
toggleSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
...
}
});
registerForContextMenu(list);
registerForContextMenu(grid);
return view;
}
public void updateList(Bundle bundle,ViewPager vp) {
viewPager=vp;
...
}
listAdapter.notifyDataSetChanged();
gridAdapter.notifyDataSetChanged();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof FragmentCommunicationListener) {
fragComm = (FragmentCommunicationListener) activity;
} else {
throw new ClassCastException();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
...
}
#Override
public boolean onContextItemSelected(MenuItem item) {
...
switch (menuItemIndex) {
case Constant.VIEW_STUDENT_DETAIL:
bundle.putSerializable("viewField", student); view.findViewById(R.id.container).setVisibility(View.VISIBLE);
transaction.addToBackStack(null);
details = new Details();
transaction.replace(R.id.container, details, "task");
transaction.commit();
details.setArguments(bundle);
break;
...
default:
}
listAdapter.setStudentList(studentList);
gridAdapter.setStudentList(studentList);
listAdapter.notifyDataSetChanged();
gridAdapter.notifyDataSetChanged();
return true;
}
}
ChildFragment
public class Details extends Fragment {
View view;
static Details details;
Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
context=container.getContext();
Bundle bundle = getArguments();
view=inflater.inflate(R.layout.display_details, container, false);
...
return view;
}
#Override
public void onDetach() {
super.onDetach();
view.findViewById(R.id.displayDetails).setVisibility(View.GONE);
}
#Override
public void onDestroyView() {
super.onDestroyView();
view.findViewById(R.id.displayDetails).setVisibility(View.GONE);
}
#Override
public void setArguments(Bundle bundle) {
super.setArguments(bundle);
}
}
PagerAdapter
public class PagerAdapter extends FragmentPagerAdapter {
private String[] tabMenu;
private int pageCount;
private Context context;
private Fragment[] fragments;
public PagerAdapter(FragmentManager fm, Context context, Fragment[] fragments) {
super(fm);
this.context = context;
tabMenu = context.getResources().getStringArray(R.array.tab_menu);
pageCount = tabMenu.length;
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return fragments[position];
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public CharSequence getPageTitle(int position) {
return tabMenu[position];
}
}
If you use FragmentTransaction.addToBackStack(), the back button is handled automatically for you.
When you do this:
#Override
public void onBackPressed() {
ViewStudentsFragment fragment = (ViewStudentsFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + 0);
super.onBackPressed();
if (fragment.getChildFragmentManager().getBackStackEntryCount() != 0) {
fragment.getChildFragmentManager().popBackStack();
}
}
you are basically popping the backstack twice, which is why your application quit.
Replace the onBackPressed() method in your Activity with this:
#Override
public void onBackPressed() {
ViewStudentsFragment fragment = (ViewStudentsFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + 0);
if (fragment.getChildFragmentManager().getBackStackEntryCount() != 0) {
fragment.getChildFragmentManager().popBackStack();
}
else {
super.onBackPressed();
}
}
Why does my pager adapter doesn't want to start from my first item. When I start ContainerIspiti activity, and show first fragment, the view pager dones't show the right element. Insted of first, view pager shows the second element, and I can't to swipe to first element of my array list. Does anybody have solution.
Here is my code for ConainterIspiti
public class ContainerIspiti extends FragmentActivity{
private Button next, previous, odgovori, informacije;
private TextView textPitanja, brojPitanja;
private ViewPager pager;
private PagerAdapter mPagerAdapter;
public static ArrayList<Pitanja> getAllPitanja;
public static ArrayList<Pitanje_has_Slika> getAllImages;
private Intent intent;
private DBTools db = new DBTools(this);
private ProgressDialog pDialog;
private int broj;
#Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
setContentView(R.layout.activity_container_pitanja);
Bundle bundle = new Bundle();
intent = getIntent();
Dohvati d = new Dohvati();
d.execute();
textPitanja = (TextView) findViewById(R.id.kategorijaTextViewPitanjeActivity);
brojPitanja = (TextView) findViewById(R.id.brojPitanjaTextViewPitanjeActivity);
pager = (ViewPager) findViewById(R.id.pagerPitanja);
pager.setCurrentItem(0, true);
bundle.putString("NAZIV_KATEGORIJE", intent.getStringExtra("NAZIV_KATEGORIJE"));
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Log.i("Position je sljedeci ", String.valueOf(position));
return PitanjaFragment.create(position);
}
#Override
public int getCount() {
Log.i("Velicina polja je ", String.valueOf(getAllPitanja.size()));
Log.i("Prvi eleemnt liste je", getAllPitanja.get(0).getTextPitanja());
return getAllPitanja.size();
}
}
private class Dohvati extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ContainerIspiti.this);
pDialog.setCancelable(false);
pDialog.setIndeterminate(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
getAllPitanja = db
.getAllPitanja(intent.getStringExtra("id_kategorije"));
Log.i("Ovoliki je get all pitanja", String.valueOf(getAllPitanja.size()));
getAllImages = db.getAllPitanjaImages();
Log.i("ovoliko je slika", String.valueOf(getAllImages.size()));
return null;
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
pager.setAdapter(mPagerAdapter);
pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
brojPitanja.setText(String.valueOf(position) + "/" + String.valueOf(getAllPitanja.size()));
broj = position;
}
});
textPitanja.setText(intent.getStringExtra("NAZIV_KATEGORIJE"));
brojPitanja.setText(String.valueOf(broj) + "/" + getAllPitanja.size());
}
}
}
and here is my fragment activity
public class PitanjaFragment extends Fragment implements API{
public static final String ARG_PAGE = "page";
private int broj;
private ImageView image;
private TextView textPitanja;
private String uri;
private View view;
private ListView listView;
private Typeface custom_font;
private boolean odgovoreno, tocno;
private ArrayList<Odgovor> odgovorList;
private PitanjaAdapter adapter;
private DBTools db;
private List<Integer> kliknuti;
private HashMap<Integer, List<Integer>> odgBrojPitanja;
public static PitanjaFragment create(int pageNumber) {
PitanjaFragment fragment = new PitanjaFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public PitanjaFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
broj = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_pitanja, container, false);
image = (ImageView) view.findViewById(R.id.imageSlikaImageView);
image.setOnClickListener(this);
textPitanja = (TextView) view.findViewById(R.id.textPitanjaTextViewPitanjaActivity);
db = new DBTools(getActivity());
listView = (ListView) view.findViewById(R.id.listView);
updateDisplay((broj+1));
return view;
}
public void updateDisplay(int z) {
odgovoreno = false;
tocno = true;
textPitanja.setText(stripHtml(String.valueOf(ContainerIspiti.getAllPitanja.get(z).getTextPitanja())));
image.setImageBitmap(null);
//info = ContainerIspiti.getAllPitanja.get(z).getInfo();
Log.d("Postoji", ContainerIspiti.getAllImages.get(z).getNazivSlike() + ", ");
for (int j = 0; j < ContainerIspiti.getAllImages.size(); j++) {
if (ContainerIspiti.getAllImages.get(j).getIdPitanja() == ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
&& ContainerIspiti.getAllImages.get(j).getNazivSlike() != null) {
Log.i("Id pitanja slike + idpitanja pitanja + idSlike",
ContainerIspiti.getAllImages.get(j).getIdPitanja()
+ ", "
+ String.valueOf(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()
+ ", "
+ ContainerIspiti.getAllImages.get(j).getIdSlika()));
image.setVisibility(View.VISIBLE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi);
//povecalo.setEnabled(true);
uri = PregledZnakova.PHOTOS_BASE_URL
+ ContainerIspiti.getAllImages.get(j).getNazivSlike();
int rounded_value = 40;
DisplayImageOptions options = new DisplayImageOptions.Builder().showImageForEmptyUri(R.drawable.placeholder).showStubImage(R.drawable.placeholder).cacheInMemory().cacheOnDisc().displayer(new RoundedBitmapDisplayer(rounded_value)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity().getApplicationContext()).defaultDisplayImageOptions(options).build();
ImageLoader.getInstance().init(config);
ImageLoader.getInstance().displayImage(uri, image,options);
break;
// }
} else {
image.setVisibility(View.GONE);
//povecalo.setImageResource(R.drawable.gumb_pretrazi_neaktivno);
//povecalo.setEnabled(false);
}
}
odgovorList = db.getAllOdgovore(Integer.toString(ContainerIspiti.getAllPitanja.get(z)
.getIdPitanja()));
adapter = new PitanjaAdapter(getActivity(),
R.layout.pitanja_entry, odgovorList);
listView.setAdapter(adapter);
for (int i=0;i<ContainerIspiti.getAllPitanja.size();i++){
if (ContainerIspiti.getAllPitanja.get(i).isTocno()){
Log.i("Ovo pitanje je tocno", ContainerIspiti.getAllPitanja.get(i).getTextPitanja());
}
}
}
#Override
public int getItemBroj() {
return broj;
}
#Override
public int getPosition() {
return broj;
}
#Override
public void setPosition(int position) {
this.broj = position;
}
#Override
public Fragment getFragment() {
return this;
}
}
Thanks for your time and your help.
In the onCreateView() method of your PitanjaFragment class, replace:
updateDisplay((broj+1));
with
updateDisplay(broj);
Try this. It should work.
I'm creating a demo app with the new android compatibility library. I want to show two listfragments with ViewPager. The first shows the root categories and the second shows the subcategories. After somebody clicks on root category the viewpager move to the subcategory, but it won't work, because always show the root category elements.
I spend few minutes with debug and I'm realised the ViewPager creates the second fragment after the first one.(I think the pager cache the next view or fragment.)
Is it possible to load the second fragment after onListItemClick?
Here is the code:
public class ViewPagerDemoActivity extends FragmentActivity implements OnBookSelectedListener {
private static int mSelectedCategoryId;
private MyAdapter mMyAdapter;
private ViewPager mPager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupPager();
}
private void setupPager() {
mPager = (ViewPager) findViewById(R.id.pager);
mMyAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyAdapter);
}
#Override
public void onBookSelected(int categoryId) {
mSelectedCategoryId = categoryId;
if (mSelectedCategoryId == 0) {
mPager.setCurrentItem(1);
} else {
mPager.setCurrentItem(0);
}
}
public static class MyAdapter extends FragmentPagerAdapter {
private static final int NUMBER_OF_FRAGMENTS = 2;
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return BookListFragment.newInstance(mSelectedCategoryId);
}
#Override
public int getCount() {
return NUMBER_OF_FRAGMENTS;
}
}
}
public class BookListFragment extends ListFragment {
private static final String ARGUMENT_KEY = "categoryId";
private OnBookSelectedListener mOnBookSelectedListener;
private int mCategoryId;
public static BookListFragment newInstance(int categoryId) {
BookListFragment bookListFragment = new BookListFragment();
Bundle argument = new Bundle();
argument.putInt(ARGUMENT_KEY, categoryId);
bookListFragment.setArguments(argument);
return bookListFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCategoryId = getArguments() != null ? getArguments().getInt(ARGUMENT_KEY) : 0;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, Books.getBooks(mCategoryId)));
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.pager_list, container, false);
View tv = v.findViewById(R.id.text);
((TextView) tv).setText("Category :" + mCategoryId);
return v;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (mCategoryId == 0) {
mOnBookSelectedListener.onBookSelected(1);
} else {
mOnBookSelectedListener.onBookSelected(0);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mOnBookSelectedListener = (OnBookSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + "Must Implement OnBookSelectedListener.");
}
}
public interface OnBookSelectedListener {
public void onBookSelected(int categoryId);
}
}
public class Books {
private static final String[] fruits = new String[] { "Apple", "Banana", "Orange" };
private static final String[] category = new String[] { "Lorem", "Dolor", "Ipsum" };
public static String[] getBooks(int categoryId) {
return categoryId == 0 ? category : fruits;
}
}
I solved the problem, I need to add List to the adapter and after that the getItem don't create new instance, only gets the item from the list.
This is the new code.
public class ViewPagerDemoActivity extends FragmentActivity implements OnBookSelectedListener {
private MyAdapter mMyAdapter;
private ViewPager mPager;
private BookOnPageChangeListener mBookOnPageChangeListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupPager();
}
private void setupPager() {
mPager = (ViewPager) findViewById(R.id.pager);
mMyAdapter = new MyAdapter(getSupportFragmentManager());
mPager.setAdapter(mMyAdapter);
mBookOnPageChangeListener = new BookOnPageChangeListener();
mPager.setOnPageChangeListener(mBookOnPageChangeListener);
}
#Override
public void onBookSelected(int categoryId) {
mMyAdapter.addPage(categoryId);
mPager.setCurrentItem(mBookOnPageChangeListener.getCurrentPage() + 1);
}
public static class MyAdapter extends FragmentPagerAdapter {
private List<Fragment> pages;
public MyAdapter(FragmentManager fm) {
super(fm);
initPages();
}
/**
* Create the list and add the first ListFragment to the ViewPager.
*/
private void initPages() {
pages = new ArrayList<Fragment>();
addPage(0);
}
/**
* Add new BookListFragment to the ViewPager.
*
* #param categoryId
* - the category id
*/
public void addPage(int categoryId) {
pages.add(BookListFragment.newInstance(categoryId));
}
#Override
public Fragment getItem(int position) {
return pages.get(position);
}
#Override
public int getCount() {
return pages.size();
}
}
/**
* Get the current view position from the ViewPager.
*/
public static class BookOnPageChangeListener extends ViewPager.SimpleOnPageChangeListener {
private int currentPage;
#Override
public void onPageSelected(int position) {
// current page from the actual position
currentPage = position;
}
public int getCurrentPage() {
return currentPage;
}
}
}
Have you tried using setOnItemClickListener()?