I am creating an application which is based on Tabs using tablayout. I didn't use viewpager. My logic is that users can create fragments (Tabs) like adding tabs in chrome so that whenever user clicks add button a new tab is created with a fragment. Now i need to save unique time stamp of each fragment created time in shared preference so that whenever i move to one fragment i can use that shared reference timestamp value to do unique function intended for that particular fragment.
But i don't know where to save that timestamp. I tried to get the time in milliseconds in Oncreate function of Fragment but whenever I switch between tabs everytime the onCreate call so that each time i switch between tabs the shared preference value changes as i added it in onCreate in Fragments.
My Logic is that it should only create once a fragment is created when user clicks add and must be able to use that in fragments.
As every time i switch to other fragement it just reinitilize all view and onCreate in called. so i could not set timestamp in oncreate..
Please help me
my Activity code is:
public class TabActivity extends AppCompatActivity{
public static TabActivity instance;
private FragmentChild fragmentOne;
private TabLayout allTabs;
ImageView add;
ImageView imageButtonAdd2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_activity);
getAllWidgets();
bindWidgetsWithAnEvent();
setupTabLayout();
}
public static TabActivity getInstance() {
return instance;
}
private void getAllWidgets() {
allTabs = (TabLayout) findViewById(R.id.simpleTabLayout);
add = findViewById(R.id.addButton);
imageButtonAdd2 = findViewById(R.id.imageButtonAdd2);
}
private void setupTabLayout() {
allTabs.addTab(allTabs.newTab().setText("ONE"),true);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
allTabs.addTab(allTabs.newTab().setText("NEW_TAB"),true);
bindWidgetsWithAnEvent();
}
});
imageButtonAdd2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(0));
fragmentSecond = new SecondFragment();
fragmentSecond.setArguments(bundle);
replaceFragment(fragmentSecond,"SecondFragment");*/
}
});
}
private void bindWidgetsWithAnEvent()
{
allTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
setCurrentTabFragment(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
private void setCurrentTabFragment(int tabPosition)
{
Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(tabPosition));
fragmentOne = new FragmentChild();
fragmentOne.setArguments(bundle);
replaceFragment(fragmentOne,"FirstFragment");
}
public void replaceFragment(Fragment fragment, String fragmentName) {
long time= System.currentTimeMillis();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment,fragmentName);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
public void backStackFragment(Fragment fragment, String fragmentName) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment,fragmentName);
ft.addToBackStack(null);
//ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
}
FragmentChild class:
public class FragmentChild extends Fragment {
String childname;
TextView textViewChildName;
EditText editText;
private GridView mGridView;
private ListItem mListItem;
private ListView mListview;
private ProgressBar mProgressBar;
private ProductViewAdapter mGridAdapter;
private ListViewAdapter mListAdapter = null;
private ArrayList<GridItem> mGridData;
private ArrayList<ListItem> mListData = null;
ListView listView;
CheckInterNetConnection check ;
Boolean isInternetPresent = false;
PreferenceHelper prefs;
private TabLayout tabLayout;
private ViewPagerAdapter adapter;
public static ViewPager viewPager;
String posid = "";
int page =0;
String title = "";
TabLayout allTabs;
int tab_position = 0;
long time=0;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//GlobalBus.getBus().register(this);
View view = inflater.inflate(R.layout.fragment_child, container, false);
Bundle bundle = getArguments();
childname = bundle.getString("data");
Log.e("onCreateView","onCreateView");
getIDs(view);
setEvents();
return view;
}
// Store instance variables based on arguments passed
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
time= System.currentTimeMillis();
page = getArguments().getInt("someInt", 0);
title = getArguments().getString("someTitle");
Log.e("onCreate","onCreate");
}
private void getIDs(View view) {
//textViewChildName = (TextView) view.findViewById(R.id.textViewChild);
//textViewChildName.setText(childname);
//editText = (EditText) view.findViewById(R.id.editText);
//editText.setText("");
}
private void setEvents() {
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.e("onViewCreated","onViewCreated");
}
#Override
public void onDestroyView() {
super.onDestroyView();
// Unregister the registered event.
EventBus.getDefault().unregister(this);
}
public static FragmentChild newInstance(int page, String title) {
FragmentChild fragmentFirst = new FragmentChild();
Bundle args = new Bundle();
args.putInt("someInt", page);
args.putString("someTitle", title);
fragmentFirst.setArguments(args);
return fragmentFirst;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.e("onActivityCreated","onActivityCreated");
allTabs = (TabLayout) getActivity().findViewById(R.id.simpleTabLayout);
mGridView = (GridView) getView().findViewById(R.id.gridView);
prefs = new PreferenceHelper(getActivity());
mGridData = new ArrayList<>();
mGridAdapter = new ProductViewAdapter(getActivity(), R.layout.grid_product_layout, mGridData);
mGridView.setAdapter(mGridAdapter);
mListview = (ListView) getView().findViewById(R.id.list);
mListData = new ArrayList<>();
mListAdapter = new ListViewAdapter(getActivity(), R.layout.list_row, mListData);
mListview.setAdapter(mListAdapter);
adapter = new ViewPagerAdapter(getFragmentManager(), getActivity(), viewPager, tabLayout);
}
#Override
public void onStart() {
super.onStart();
Log.e("onStart","onStart");
EventBus.getDefault().register(this);
tab_position=allTabs.getSelectedTabPosition();
//Log.e("TAB ID",String.valueOf(tab_position));
prefs.save(String.valueOf(tab_position),"tab-"+time);
check = new CheckInterNetConnection(getActivity());
isInternetPresent = check.isConnectingToInternet();
if (isInternetPresent) {
fetchProducts(tab_position);
}
}
#Override
public void onResume() {
super.onResume();
Log.e("onResume","onResume");
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
Log.e("onPause","onPause");
super.onPause();
}
#Subscribe
public void onEvent(GlobalBus event){
posid = event.getMessage();
//Toast.makeText(getActivity(), event.getMessage(), Toast.LENGTH_SHORT).show();
}
public void fetchProducts(int tabPosition){
String tabid = prefs.getString(String.valueOf(tabPosition),"0");
Fragment fragment = getFragmentManager().findFragmentById(R.id.simpleFrameLayout);
String tag = (String) fragment.getTag();
//Log.e("URL","http://35.184.41.163/phpmyadmin/app/demo/products.php?tabid="+tabid+"&tab_position="+tabPosition);
RestClientHelper.getInstance().get("http://35.184.41.163/phpmyadmin/app/demo/products.php", new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
parseResult(response);
mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
try {
ListItem items;
GridItem item = (GridItem) parent.getItemAtPosition(position);
items = new ListItem();
items.setName(item.getTitle());
items.setType(item.getDescription());
mListData.add(items);
}
catch(Exception e){
}
finally {
mListAdapter.setGridData(mListData);
}
}
});
}
#Override
public void onError(String error) {
}
});
}
private void parseResult(String result) {
try {
JSONObject response = new JSONObject(result);
JSONArray posts = response.optJSONArray("products");
GridItem item;
if(posts.length() <= 0){
RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
ly.setVisibility(View.VISIBLE);
}
else {
// RelativeLayout ly = (RelativeLayout) getView().findViewById(R.id.noOps);
//ly.setVisibility(View.INVISIBLE);
mGridData.clear();
mGridAdapter.setGridData(mGridData);
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String title = post.optString("name");
String description = post.optString("description");
String image = post.optString("image");
String qty = post.optString("qty");
String quantityin = post.optString("quantityin");
String price = post.optString("price");
item = new GridItem();
item.setId(id);
item.setTitle(title);
item.setDescription(description);
item.setImage(image);
item.setQuantity(qty);
item.setQuantityIn(quantityin);
item.setUnitprice(price);
mGridData.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
finally {
mGridAdapter.setGridData(mGridData);
}
}
}
UPDATE as suggested by #Larry Hsiao
public class TabActivity extends AppCompatActivity{
public static TabActivity instance;
private FragmentChild fragmentOne;
PreferenceHelper prefs;
private TabLayout allTabs;
ImageView add;
ImageView imageButtonAdd2;
private final List<Fragment> fragments = new ArrayList<>(); // maintain the instance for switching
private int currentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_activity);
prefs = new PreferenceHelper(TabActivity.this);
getAllWidgets();
//bindWidgetsWithAnEvent();
setupTabLayout();
bindWidgetsWithAnEvent();
}
public static TabActivity getInstance() {
return instance;
}
private void getAllWidgets() {
allTabs = (TabLayout) findViewById(R.id.simpleTabLayout);
add = findViewById(R.id.addButton);
add.performClick();
imageButtonAdd2 = findViewById(R.id.imageButtonAdd2);
}
private void setupTabLayout() {
int locfirst = allTabs.getSelectedTabPosition();
locfirst = locfirst+1;
allTabs.addTab(allTabs.newTab().setText("TAB"+locfirst),true);
/*long time= System.currentTimeMillis();
prefs.save("tab_"+locfirst,"tab_"+time);*/
fragments.add(newFragment(0));
addFragment(fragments.get(0));
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int loc = allTabs.getSelectedTabPosition();
loc = loc+1;
allTabs.addTab(allTabs.newTab().setText("TAB"+loc),true);
fragments.add(newFragment(loc));
addFragment(fragments.get(loc));
/*bindWidgetsWithAnEvent();
long time= System.currentTimeMillis();
prefs.save("tab_"+loc,"tab_"+time);*/
}
});
imageButtonAdd2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(0));
fragmentSecond = new SecondFragment();
fragmentSecond.setArguments(bundle);
replaceFragment(fragmentSecond,"SecondFragment");*/
}
});
}
private Fragment newFragment(int position) {
Fragment fragment = new FragmentChild();
Bundle bundle = new Bundle();
bundle.putString("position", String.valueOf(position));
fragment.setArguments(bundle);
return fragment;
}
private void addFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.simpleFrameLayout, fragment);
transaction.commit();
}
private void changingTab(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.hide(fragments.get(currentIndex));
if (manager.getFragments().contains(fragment)) {
transaction.show(fragment);
}else {
transaction.add(R.id.simpleFrameLayout,fragment);
}
transaction.commit();
}
private void bindWidgetsWithAnEvent()
{
allTabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int nextPageIndex = (currentIndex + 1) % 2; // only two fragment switching
changingTab(fragments.get(nextPageIndex));
currentIndex = nextPageIndex;
//setCurrentTabFragment(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
\
#Override
public void onBackPressed(){
FragmentManager fm = getSupportFragmentManager();
if (fm.getBackStackEntryCount() > 0) {
Log.i("MainActivity", "popping backstack");
fm.popBackStack();
} else {
Log.i("MainActivity", "nothing on backstack, calling super");
super.onBackPressed();
}
}
}
This force closes with this error:
FATAL EXCEPTION: main
Process: com.eazypos.app, PID: 13624
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.get(ArrayList.java:308)
at com.eazypos.app.TabActivity$3.onTabSelected(TabActivity.java:115)
at android.support.design.widget.TabLayout.dispatchTabSelected(TabLayout.java:1165)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1158)
at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:483)
at android.support.design.widget.TabLayout.addTab(TabLayout.java:465)
at com.eazypos.app.TabActivity$1.onClick(TabActivity.java:62)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
REMOVE TAB FUNCTION
public void removeTab(int position) {
Toast.makeText(getActivity(), "REMOVING --> "+position, Toast.LENGTH_SHORT).show();
prefs.remove("tab_"+position);
if (allTabs.getChildCount() > 0) {
allTabs.removeTabAt(position);
}
}
To save the value only once.. in timeStamp in the shared prefs just use this in each fragment..
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (getActivity() == null)
{
// generate time stamp in miliseconds as you are doing
// and save it in shared prefs
// this will be called only once..
}
}
OR YOU CAN TRY IN :-
UPDATE onCreate of fragmentChild
time= System.currentTimeMillis();
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("My_prefs_name",Context.MODE_PRIVATE);
String timeStamp = sharedPreferences.getString("timeStamp","");
if ( timeStamp.isEmpty())
{
// SAVE TIME IN SHAREPREFS
sharedPreferences.edit().putString("timeStamp",time).apply();
}
You should maintain the Fragment instance which you already create. (With FragmentManager or just keep it with variable might do the job)
The method setCurrentTabFragment() in Activity which creating new Fragment is invoked every time user click tab. As the result, fragment always run through the onCreate()
// this method invoke every time user click the tab
private void setCurrentTabFragment(int tabPosition){
Bundle bundle = new Bundle();
bundle.putString("data", String.valueOf(tabPosition));
fragmentOne = new FragmentChild(); // creating new Fragment
fragmentOne.setArguments(bundle);
replaceFragment(fragmentOne,"FirstFragment");
}
Edited:
Use List to maintain the Fragment instance we already create.
Switch Fragment with hide()/show() provided by FragmentManager, using add() if the Fragment not added to FragmentManager before.
Sample Code:
public class MainActivity extends AppCompatActivity {
private final List<Fragment> fragments = new ArrayList<>();
private int currentIndex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabLayout tabLayout = findViewById(R.id.tabLayout);
// initial with one page
Fragment firstFragment = newFragment(0);
fragments.add(firstFragment);
addFragment(firstFragment);
tabLayout.addTab(tabLayout.newTab().setText("Initial tab"));
// user events
findViewById(R.id.main_createTab).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fragments.add(newFragment(tabLayout.getTabCount()));
tabLayout.addTab(tabLayout.newTab().setText("Pages " + tabLayout.getTabCount()));
}
});
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
int nextPageIndex = tab.getPosition();
if (currentIndex == nextPageIndex){
return;
}
changingTab(fragments.get(nextPageIndex));
currentIndex = nextPageIndex;
}
#Override public void onTabUnselected(TabLayout.Tab tab) {}
#Override public void onTabReselected(TabLayout.Tab tab) {}
});
}
private Fragment newFragment(int position) {
Fragment fragment = new FragmentWithLog();
Bundle bundle = new Bundle();
bundle.putString("position", String.valueOf(position));
fragment.setArguments(bundle);
return fragment;
}
private void addFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.main_fragmentFrame, fragment);
transaction.commit();
}
private void changingTab(Fragment fragment) {
FragmentManager manager = getSupportFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.hide(fragments.get(currentIndex));
if (manager.getFragments().contains(fragment)) {
transaction.show(fragment);
} else {
transaction.add(R.id.main_fragmentFrame, fragment);
}
transaction.commit();
}
}
Related
I have one activity, fragment with listView and fragment with details for each listView item. I am getting fragments data from API. How should I save loaded date and listView position correctly to be able to restore it when I am returning back to the listView?
I tried to implement this solution Once for all, how to correctly save instance state of Fragments in back stack? but I cannot restore my listView correctly.
My MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
listFragment = new ListFragment();
fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, listFragment);
fragmentTransaction.commit();
if (savedInstanceState != null) {
//Restore the fragment's instance
listFragment = (ListFragment)getSupportFragmentManager().getFragment(savedInstanceState, "listContent");
}
...
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "listContent", listFragment);
}
and ListFragment
public class ListFragment extends Fragment {
public static final String REQUEST_TAG = "ProjectListFragment";
private int page;
private View view;
private RelativeLayout loading ;
private PagingListView listView;
private PagingProjectListAdapter adapter;
private ArrayList<String> projects = new ArrayList<>();
private ArrayList<String> loadedProjects = new ArrayList<>();
public ListFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_list, container, false);
listView = (PagingListView) view.findViewById(R.id.projectsListView);
loading = (RelativeLayout) view.findViewById(R.id.loading);
//page = 1;
adapter = new PagingProjectListAdapter(getContext(), ListFragment.this);
listView.setAdapter(adapter);
listView.setHasMoreItems(true);
// Inflate the layout for this fragment
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// FIXME not used
listView.onFinishLoading(true, projects);
//Restore the fragment's state here
} else {
projects.clear();
page = 1;
listView.setPagingableListener(new PagingListView.Pagingable() {
#Override
public void onLoadMoreItems() {
new CustomVolleyAsyncTask().execute();
}
});
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("currentPosition", 0);
//Save the fragment's state here
}
public void itemClickMethod(View detailsView) {
LinearLayout linearLayout = (LinearLayout) detailsView;
String bid = linearLayout.getContentDescription().toString();
Bundle bundle = new Bundle();
String k = "ProjectID";
bundle.putString(k, bid);
DetailsFragment detailsFragment = new DetailsFragment();
detailsFragment.setArguments(bundle);
final FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, detailsFragment, "DetailsFragmentTag");
ft.addToBackStack(null);
ft.commit();
}
private class CustomVolleyAsyncTask extends SafeAsyncTask<List<String>> implements Response.Listener,
Response.ErrorListener {
public List<String> status = null;
private RequestQueue mQueue;
#Override
public List<String> call() throws Exception {
mQueue = CustomVolleyRequestQueue.getInstance(view.getContext())
.getRequestQueue();
String url = "http://www.myapi.com/api/v1/data/" + Integer.toString(page);
final CustomJSONObjectRequest jsonRequest = new CustomJSONObjectRequest(Request.Method
.GET, url,
new JSONObject(), this, this);
jsonRequest.setTag(REQUEST_TAG);
mQueue.add(jsonRequest);
// TODO rm redundant result
return status;
}
#Override
public void onErrorResponse(VolleyError error) {
// FIXME check no response case crash
//mTextView.setText(error.getMessage());
}
#Override
public void onResponse(Object response) {
try {
JSONArray projectsJSON = new JSONArray(((JSONObject) response).getString("projects"));
loadedProjects.clear();
for (int i=0; i < projectsJSON.length(); i++) {
loadedProjects.add(projectsJSON.getJSONObject(i).toString());
}
page++;
listView.onFinishLoading(true, loadedProjects);
if (loading.getVisibility() == View.VISIBLE && !listView.isLoading()){
listView.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
} catch (JSONException e) {
e.printStackTrace();
}}}
}
currently, my savedInstanceState is always null, what am I missing?
I think, that your fragment created twice, when configuration changed. Here Staffan explain, why this happend. I resolve similar problem by this way (in activity onCreate):
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(TAG);
if(fragment==null)
fragmentManager.beginTransaction()
.add(R.id.container, NewsFragment.newInstance(),TAG)
.commit();
I have a MainActivity which has AppBar containing toolbar and TabLayout, and also ViewPager.
MainActivity holds 4 fragments home, cash, card and account.
public class MainActivity extends AppCompatActivity {
private TabLayout tabLayout;
private ViewPager viewPager;
private AppBarLayout appBarLayout;
Window window;
#Override
#SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
window = this.getWindow();
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(this.getResources().getColor(R.color.color_primary_green_dark));
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar ab = getSupportActionBar();
ab.setTitle("Example Wallet");
toolbar.setTitleTextColor(getResources().getColor(android.R.color.white));
appBarLayout = (AppBarLayout) findViewById(R.id.appBarLayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
setupViewPager(viewPager);
tabLayout = (TabLayout) findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(getBaseContext(), "Tab " + position + " Onpage Selected " + viewPager.getCurrentItem(), Toast.LENGTH_SHORT).show();
if (position == 0) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_green_dark));
}
} else if (position == 1) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
tabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
}
} else if (position == 2) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_yellow));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_yellow_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_yellow_dark));
}
} else if (position == 3) {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_red));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_red_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_red_dark));
}
} else {
appBarLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green));
tabLayout.setBackgroundColor(getResources().getColor(R.color.color_primary_green_dark));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.setStatusBarColor(getResources().getColor(R.color.color_primary_green_dark));
}
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
FloatingActionButton fab1 = (FloatingActionButton) findViewById(R.id.fab);
if (fab1 != null) {
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent registerIntent = new Intent(MainActivity.this, Detail.class);
startActivity(registerIntent);
}
});
}
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
adapter.addFrag(new FragmentMain(), "Home");
adapter.addFrag(new FragmentCash(), "Cash");
adapter.addFrag(new FragmentCard(), "Card");
adapter.addFrag(new FragmentAccount(), "Account");
adapter.addFrag(PartThreeFragment.createInstance(20), "Tab1");
viewPager.setAdapter(adapter);
}
class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public ViewPagerAdapter(FragmentManager manager) {
super(manager);
}
#Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
#Override
public int getCount() {
return mFragmentList.size();
}
public void addFrag(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
#Override
public CharSequence getPageTitle(int position) {
// return null to display only the icon
return mFragmentTitleList.get(position);
}
}
}
home fragment code
public class FragmentMain extends Fragment {
private List<Movie> movieList1 = new ArrayList<>();
private List<Movie> movieList2 = new ArrayList<>();
private RecyclerView recyclerView,recyclerView1;
private MovieAdapter mAdapter1,mAdapter2;
private LinearLayout cash_layout,card_layout,account_layout;
private ViewGroup c;
public FragmentMain() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.content_main, container, false);
//final android.app.ActionBar actionBar = getActivity().getActionBar();
//c=container;
recyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
cash_layout = (LinearLayout) v.findViewById(R.id.linearLayout_cash_bal);
card_layout = (LinearLayout) v.findViewById(R.id.linearLayout_card_bal);
account_layout = (LinearLayout) v.findViewById(R.id.linearLayout_account_bal);
mAdapter1 = new MovieAdapter(movieList1);
RecyclerView.LayoutManager mLayoutManager1 = new LinearLayoutManager(v.getContext());
recyclerView.setLayoutManager(mLayoutManager1);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter1);
prepareMovieData1();
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
getContext().getActionBar().setSelectedNavigationItem(2);
/*actionBar.selectTab(actionBar.getTabAt(1));
FragmentManager fm=getFragmentManager();
fm.beginTransaction().replace(R.layout.content_cash, (Fragment)new FragmentCash()).commit();
getActivity().getActionBar().setTitle("Home");
//ActionBar actionBar = getActivity().getActionBar();*/
/*FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();*/
}
});
/*mAdapter2 = new MovieAdapter(movieList2);
RecyclerView.LayoutManager mLayoutManager2 = new LinearLayoutManager(v.getContext());
recyclerView1.setLayoutManager(mLayoutManager2);
recyclerView1.setItemAnimator(new DefaultItemAnimator());
recyclerView1.setAdapter(mAdapter2);
prepareMovieData2();*/
return v;
}
private void prepareMovieData1() {
movieList1.clear();
Movie movie = new Movie("info","List is empty", "To create an item, click on (+) button", "","");
movieList1.add(movie);
mAdapter1.notifyDataSetChanged();
}
/*public void onClick1(View v) {
FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}*/
/*private void prepareMovieData2() {
Movie movie = new Movie("card","Card", "New Dress", "Rs.50.00","11/09/2016");
movieList2.add(movie);
mAdapter2.notifyDataSetChanged();
}*/
}
I am trying to call cash, card and account fragment from home fragment but this code
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
FragmentCash fragment2 = new FragmentCash();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container,fragment2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
adds other fragment with home fragment visible.
The solution I need is, in the below image when I click the cash balance it slide to the cash tab with cash fragment onscreen.
It looks like you are trying to add the cash fragment on top of the view pager, or replace it all together. Instead of replacing it in the current view, I'm assuming you would like to navigate to it within the viewPager.
To do that, replace all of your onClick code with pager.setCurrentItem(//Page number with cash fragment on it)
So, your onClick would look something like this:
cash_layout.setOnClickListener(new View.OnClickListener() {
#Override
#SuppressWarnings("deprecation")
public void onClick(View v) {
((MainActivity) getActivity()).getViewPager().setCurrentItem(//Your desired page number as int);
}
});
Or you could solve this easily with an interface.
Just create an interface to access your viewPager's operations like so.
public interface ViewPagerInterface {
ViewPager getViewPager();
}
Have your activity implement it:
public MainActivity extends AppCompatActvity implements ViewPagerInterface {
#Override
public ViewPager getViewPager() {
return this.viewPager;
}
}
Then pass that interface to your Fragments and call the getViewPager method.
viewPagerInterface.getViewPager().setCurrentItem(<my-int>);
I have a viewpager with 3 fragments to make a swipeable widget. When I first load the app they show properly and all the click events work as expected. Same with hitting the back button after clicking each OnClick, sends me back to landingpagenotlogged in and the viewpager/fragments are displayed as expected. My problem is when I hit my menu button and come back to the landing page my view pager disappears.
I did try to use getChildFragmentManager() when setting the adapter and it works but then my onClick events do not work any more as I get no view to id *******.
I have also tried to place the adapter in the onResume(); with no luck at all.
Along with the viewpager, my viewpagerindicator is not working for the homewidget but working for the carousel. Not sure if that is the code or the layout. But I set it up the same way as the carousel and still not seeing it within the screen when run.
Landingpagenotlogged
public class LandingPageFragmentLoggedOut extends LandingPageFragment {
private static final String TAG = LandingPageFragmentLoggedOut.class.getSimpleName();
private ViewPager viewPager;
private RelativeLayout myStoreTab;
private Button signIn;
private final static Fragment instance = new LandingPageFragmentLoggedOut();
LoggedOutWidgetAdapter mAdapter;
ViewPager mPager;
public static final int ITEMS = 3;
static public Fragment getInstance() {
return instance;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
setShoppingListFocusChangeListener();
setSignInBtnClickListener();
super.setViewPagerMotionListeners(viewPager);
setMenuTouchListener();
setTabClickListener();
return view;
}
#Override
protected void inflateFragmentView(LayoutInflater inflater, ViewGroup container) {
view = inflater.inflate(R.layout.landingpage_not_logged_in, container,
false);
RelativeLayout thisLayout = (RelativeLayout) view
.findViewById(R.id.landingpage_logged_out_parent_layout);
TileBackground.fixBackgroundRepeat(thisLayout);
imgArch = view.findViewById(R.id.frag_tab);
}
private void setSignInBtnClickListener() {
signIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, String> params = new HashMap<>();
Intent intent = new Intent(getActivity(), SignInActivity.class);
startActivity(intent);
getActivity().overridePendingTransition(
R.anim.enter_in_from_bottom, R.anim.anim_static);
params.put("Module", "Home");
FlurryAgent.logEvent(FlurryConstants.GOTO_SIGN_IN, params);
}
});
}
private void setTabClickListener() {
myStoreTab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tabSelection = 1;
tabSelectionListener.onTabSelectionListener(tabSelection);
toggleStoreTabIndicator(1);
}
});
}
#Override
#SuppressLint("WrongViewCast")
protected void setUIreferences() {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
overlay = view.findViewById(R.id.landingpage_screenOverlay);
indicator = (LinePageIndicator) view.findViewById(R.id.image_slider_indicator);
this.signIn = (Button) view.findViewById(R.id.landingpg_sign_in_btn);
shoppingListBtn = (ImageView) view.findViewById(R.id.icnlistoptions);
myStoreTab = (RelativeLayout) view.findViewById(R.id.frag_tab);
menuButton = (Button) view.findViewById(R.id.imgBanner_list);
logoButton = (ImageView) view.findViewById(R.id.headerLogo);
addShoppingListItemWidget = (EditText) view.findViewById(R.id.editAddItemNotLoggedIn);
addShoppingListItemWidget.setOnKeyListener(null);
addedItemConfirmation = view.findViewById(R.id.addedItemConfirmation);
imgScanner = (ImageView) view.findViewById(R.id.imgScannerNotLoggedIn);
toggleScannerVisibility(true);
itemAddedText = (TextView) view.findViewById(R.id.item_added_text);
weeklyAdImg = (ImageView) view.findViewById(R.id.weeklyad_img);
defaultWelcomeMsg = (ImageView) view.findViewById(R.id.landing_page_default_img);
setWeeklyAdThumbNail();
if(imgUrl!=null)
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
//setWeeklyAdOnClickListener();
setWeeklyAdClickListener();
couponsGrid = view.findViewById(R.id.coupons_grid);
couponsPlaceholderImg = (ImageView) view.findViewById(R.id.feat_coupons);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
itemAddedText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
}
imgScanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
mShoppingListAdd = (RelativeLayout) view.findViewById(R.id.shoppinglis_shortcut);
mShoppingListAdd.setVisibility(View.GONE);
mAdapter = new LoggedOutWidgetAdapter(getFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(mAdapter);
LinePageIndicator mLoggedOutWidgetIndicator = (LinePageIndicator)view.findViewById(R.id.homewidgetLoggedOutIndicator);
mLoggedOutWidgetIndicator.setViewPager(mPager);
}
// MSM - 214
private void setWeeklyAdThumbNail() {
try {
if (LocalDb.getStoreId() != LocalDb.DEFAULT_VAL) {
if (weeklyAdBundle != null && !weeklyAdBundle.isEmpty()) {
//MSM - 155
if (!Utils.isStringNull(weeklyAdBundle.getString("WeeklyAdThumbnail"))) {
Log.e("BANNER ID SET: ", weeklyAdBundle.getString("WeeklyAdThumbnail"));
imgUrl = weeklyAdBundle.getString("WeeklyAdThumbnail");
}
else
imgUrl = weeklyAdBundle.getString("0FirstThumbnail");
}
}
if (urls == null || !urls.contains(imgUrl)) {
Picasso.with(getActivity()).load(imgUrl).transform(new MyTransformTop()).error(R.drawable.img_ad_default).into(weeklyAdImg);
}
else
Picasso.with(getActivity()).load(R.drawable.img_ad_default).into(weeklyAdImg);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void sendRequest() {
if (CheckNetworkConnection.isConnectionAvailable(activity)) {
jsonParser = new CarouselJSONParser(this);
jsonParser.execute();
} else {
setDefaultOfflineImage();
weeklyAdImg.setImageResource(R.drawable.img_ad_default);
// TODO Set OFFLINE message here
}
}
#Override
public void setCarouselData(ArrayList<CarouselImageData> imageDatas) {
Log.v(TAG, "Set Carousel Data hit");
if (imageDatas != null) {
this.advertisements = imageDatas;
runnable(advertisements.size());
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
viewPager
.setAdapter(new ImageSliderAdapter(activity, imageDatas, this, weeklyAdBundle));
indicator.setViewPager(viewPager);
if (isFirstTimeLaunched) {
fadeInWelcomMsg();
Log.v(TAG, "first time launched, welcome message initaited");
} else {
viewPager.setVisibility(View.VISIBLE);
indicator.setVisibility(View.VISIBLE);
Log.v(TAG, "Returning user, viewpager set visible");
}
} else {
setDefaultOfflineImage();
}
}
#Override
public void onResume() {
if (LocalDb.isLoggedIn()) {
Fragment fragment = new LandingPageFragment();
launchNavigationItemFragment(fragment);
}
getActivity().startService(new Intent(getActivity().getApplicationContext(),
WeeklyAdService.class));
if (viewPager == null) {
viewPager = (ViewPager) view.findViewById(R.id.home_carousel);
}
mAdapter = new LoggedOutWidgetAdapter(getChildFragmentManager());
super.onResume();
if (newItemIsAdded) {
onShoppingListResult();
}
// addShoppingListItemWidget.clearFocus();
}
#Override
void runnable(final int size) {
handler = new Handler();
animateViewPager = new Runnable() {
#Override
public void run() {
if (!pageIsSliding) {
if (viewPager.getCurrentItem() == size - 1) {
viewPager.setCurrentItem(0);
} else {
viewPager.setCurrentItem(
viewPager.getCurrentItem() + 1, true);
}
handler.postDelayed(animateViewPager, ANIM_VIEW_PAGER_DELAY);
}
}
};
}
#Override
void toggleStoreTabIndicator(int tab) {
if (storeTabIsClosed) {
storeTabIsClosed = false;
imgArch.setBackgroundResource(R.drawable.img_single_arch_my_store);
} else {
storeTabIsClosed = true;
imgArch.setBackgroundResource(R.drawable.img_arch);
}
}
#Override
protected void setFontsOnTextViews(View view) {
}
#Override
protected void setTabClickListeners() {
}
#Override
public void setViewPagerMotionListeners(ViewPager vPager) {
}
public class LoggedOutWidgetAdapter extends FragmentPagerAdapter {
public LoggedOutWidgetAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return ProductLocatorHomeWidgetFragment.init(position);
case 1:
return ProductScanHomeWidgetFragment.init(position);
case 2:
return MyShoppingListHomeWidgetFragment.init(position);
default:
return null;
}
}
#Override
public int getCount() {
return ITEMS;
}
}
}
The three fragments that are tied to the viewpager
ProductLocatorHomeWidgetFragment
public class ProductLocatorHomeWidgetFragment extends Fragment {
int fragVal;
int storeId;
String storeName, storeLat, storeLong, retail_store_id;
TextView mProductLocatorClickZone;
StoreList sList;
public static ProductLocatorHomeWidgetFragment init(int val) {
ProductLocatorHomeWidgetFragment productLocatorFragment = new ProductLocatorHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodLocator", val);
productLocatorFragment.setArguments(args);
return productLocatorFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("prodLocator") : 1;
sList = new StoreList();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_locator_search_widget, container, false);
mProductLocatorClickZone = (TextView) layoutView.findViewById(R.id.editSearchItemNotLoggedIn);
mProductLocatorClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sList = LandingPageFragment.storeList;
if(sList.getId() != null){
storeId = Integer.parseInt(sList.getId());
storeLat = sList.getLatitude();
storeLong = sList.getLongitude();
storeName = sList.getName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
else if (sList.getId() == null) {
if (LocalDb.getStoreId() > 0) {
storeId = LocalDb.getStoreId();
storeLat = LocalDb.getStoreLat();
storeLong = LocalDb.getStoreLng();
storeName = LocalDb.getMyStoreName();
Intent mIntent = new Intent(getActivity(), ProductSearchActivity.class);
FlurryTrackerHelper.onProductLocatorWidget();
mIntent.putExtra("store_id", String.valueOf(storeId));
mIntent.putExtra("store_lat", storeLat);
mIntent.putExtra("store_lng", storeLong);
mIntent.putExtra("retail_id", retail_store_id);
startActivity(mIntent);
}
}
else {
StoreLocatorDetailsSearchFragment storeLocatorDetailsSearchFragment = new StoreLocatorDetailsSearchFragment();
Bundle b1 = new Bundle();
b1.putInt("currentFragment", 10);
storeLocatorDetailsSearchFragment.setArguments(b1);
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, storeLocatorDetailsSearchFragment);
transaction.addToBackStack(null);
transaction.commit();
}
}
});
return layoutView;
}
}
MyShoppingListHomeWidgetFragment
public class MyShoppingListHomeWidgetFragment extends Fragment {
int fragVal;
EditText mShoppingListClickZone;
ImageView mShoppinglistScanClickZone;
public static MyShoppingListHomeWidgetFragment init(int val) {
MyShoppingListHomeWidgetFragment myShoppingListFragment = new MyShoppingListHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("myShoppingList", val);
myShoppingListFragment.setArguments(args);
return myShoppingListFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// fragVal = getArguments() != null ? getArguments().getInt("myShoppingList") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.shopping_list_widget, container, false);
mShoppingListClickZone = (EditText) layoutView.findViewById(R.id.editAddItemNotLoggedIn);
mShoppingListClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ShoppingListItemsFragment shoppingListItemsFragment = new ShoppingListItemsFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, shoppingListItemsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
mShoppinglistScanClickZone = (ImageView) layoutView.findViewById(R.id.imgScannerNotLoggedIn);
mShoppinglistScanClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PermissionHandler.openCamera(getActivity());
}
});
return layoutView;
}
}
ProductScanHomeWidgetFragment
public class ProductScanHomeWidgetFragment extends Fragment {
int fragVal;
LinearLayout mCouponSearchClickZone, mRefillPrescriptionClickZone;
View mDivider;
public static ProductScanHomeWidgetFragment init(int val) {
ProductScanHomeWidgetFragment productScanFragment = new ProductScanHomeWidgetFragment();
Bundle args = new Bundle();
args.putInt("prodScan", val);
productScanFragment.setArguments(args);
return productScanFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragVal = getArguments() != null ? getArguments().getInt("prodScan") : 1;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View layoutView = inflater.inflate(R.layout.product_scan_widget, container, false);
mRefillPrescriptionClickZone = (LinearLayout) layoutView.findViewById(R.id.refillPrescriptionClickZone);
mCouponSearchClickZone = (LinearLayout) layoutView.findViewById(R.id.couponSearchClickZone);
mCouponSearchClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ECouponsViewFragment eCouponsViewFragment = new ECouponsViewFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, eCouponsViewFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
if (LocalDb.getBannerSupportRefillPrescriptions().equalsIgnoreCase(
UtilConstants.KEY_WORD_FALSE)) {
mDivider = layoutView.findViewById(R.id.divider);
mDivider.setVisibility(View.GONE);
mRefillPrescriptionClickZone.setVisibility(View.GONE);
} else {
mRefillPrescriptionClickZone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddPharmacyFragment addPharmacyFragment = new AddPharmacyFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.in_from_right, R.anim.out_to_left, R.anim.in_from_left, R.anim.out_to_right);
transaction.replace(R.id.nav_item_fragment_container, addPharmacyFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
}
return layoutView;
}
}
I was able to solve this using a FragmentStatePagerAdapter and not the FragmentPagerAdapter.
So I removed the old FragmentPagerAdapter in LadingPageLoggedOut and replaced it with
inal String [] fragmentClasses = {"com.supervalu.mobile.android.HomeScreenWidget.ProductLocatorHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.ProductScanHomeWidgetFragment",
"com.supervalu.mobile.android.HomeScreenWidget.MyShoppingListHomeWidgetFragment"};
mPager = (ViewPager) view.findViewById(R.id.vpHomePageWidget);
mPager.setAdapter(new FragmentStatePagerAdapter(getFragmentManager()) {
#Override
public Fragment getItem(int position) {
Fragment fragmentAtPosition = null;
// Check to make sure that your array is not null, size is greater than 0 ,
// current position is greater than equal to 0, and position is less than length
if((fragmentClasses != null) && (fragmentClasses.length > 0)&&(position >= 0)&& (position < fragmentClasses.length))
{
// Instantiate the Fragment at the current position of the Adapter
fragmentAtPosition = Fragment.instantiate(getContext(), fragmentClasses[position]);
fragmentAtPosition.setRetainInstance(true);
}
return fragmentAtPosition;
}
#Override
public int getCount() {
return fragmentClasses.length;
}
});
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();
}
}
I have a parent SherlockFragmentActivity class that contains ViewPager with 4 Fragments inside.
One of them extends from SherlockListFragment and I want to scroll it to top by click on it's tab.
MainActivity class:
public class MainActivity extends SherlockFragmentActivity {
ViewPager viewPager;
TabAdapter tabAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
setTheme(Constants.THEME);
viewPager = new ViewPager(this);
viewPager.setId(R.id.pager);
viewPager.setBackgroundResource(R.color.background_color);
tabAdapter = new TabAdapter(this,viewPager);
super.onCreate(savedInstanceState);
setContentView(viewPager);
// Action bar setup
setupTabs(savedInstanceState);
}
private void setupTabs(Bundle savedInstanceState) {
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i = 1; i <= 4; i++) {
ActionBar.Tab tab = getSupportActionBar().newTab();
switch (i) {
case 1:
tab.setText(R.string.feed).setTabListener(tabAdapter);
tabAdapter.addTab(EventListFragment.class);
break;
case 2:
tab.setText(R.string.downloads).setTabListener(tabAdapter);
tabAdapter.addTab(LocalEventListFragment.class);
break;
case 3:
tab.setText(R.string.tags).setTabListener(tabAdapter);
tabAdapter.addTab(TagsFragment.class);
break;
case 4:
tab.setText(R.string.settings).setTabListener(tabAdapter);
tabAdapter.addTab(SettingsFragment.class);
break;
}
getSupportActionBar().addTab(tab);
}
}
TabAdapter class:
public static class TabAdapter extends FragmentPagerAdapter implements ViewPager.OnPageChangeListener, ActionBar.TabListener {
private final Context mContext;
private final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
private final ActionBar mActionBar;
private final ViewPager mViewPager;
public TabAdapter(SherlockFragmentActivity activity, ViewPager pager){
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(Class<?> clss){
classes.add(clss);
mFragments.add(Fragment.instantiate(mContext, clss.getName(),
null));
}
#Override
public Fragment getItem(int i) {
return mFragments.get(i);
}
public int getId(int index){
return mFragments.get(index).getId();
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
// fixed double call onTabReselected
if (mActionBar.getSelectedNavigationIndex() != position)
mActionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrollStateChanged(int i) {
}
#Override
public int getCount() {
return 4;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
final int position = tab.getPosition();
final Fragment fragment = mFragments.get(position);
if (fragment != null) {
switch (position) {
case 0:
// call tab's ListFragment scroll to top item
((EventListFragment) fragment).scrollToTop();
break;
case 1:
// do something
break;
}
}
}
onTabReselected called, then user press current tab, so I try to do EventListFragment scrolling:
EventListFragment class:
public class EventListFragment extends SherlockListFragment {
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mAdapter = new EventListAdapter(getSherlockActivity());
setListAdapter(mAdapter);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
}
#Override
public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View eventListLayout = inflater.inflate(R.layout.eventlist_fragment,null);
ListView lv = (ListView) eventListLayout.findViewById(android.R.id.list);
ViewGroup parent = (ViewGroup) lv.getParent();
//Remove ListView and add PullToRefreshListView in its place
int lvIndex = parent.indexOfChild(lv);
parent.removeViewAt(lvIndex);
mPullToRefreshListView = onCreatePullToRefreshListView(inflater, savedInstanceState);
parent.addView(mPullToRefreshListView, lvIndex, lv.getLayoutParams());
return eventListLayout;
}
public void scrollToTop() {
if (getSherlockActivity() != null) { // null after screen rotation
final ListView listView = getListView();
listView.post(new Runnable(){
public void run() {
listView.smoothScrollToPosition(0);
}});
}
}
It works on application start, but after screen rotation scrollToTop - getSherlockActivity() returns null.
If remove this condition check, have an exception:
java.lang.IllegalStateException: Content view not yet created
at android.support.v4.app.ListFragment.ensureList(ListFragment.java:328)
at android.support.v4.app.ListFragment.getListView(ListFragment.java:222)
at com.project.fragment.EventListFragment.scrollToTop(EventListFragment.java:337)
at com.project.MainActivity$TabAdapter.onTabReselected(MainActivity.java:411)
at com.actionbarsherlock.internal.app.ActionBarWrapper$TabWrapper.onTabReselected(ActionBarWrapper.java:327)
I haven't totally understatinding how to ViewPager and its FragmentPagerAdapter works. So can't find a problem, that occurs.
Use this FragmentPageAdapter:
public class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "CATEGORIAS", "PRINCIPAL", "AS MELHORES", };
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms,
};
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {Fragment f = null;
switch(position){
case 0:
{
f = new ArrayListFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 1:
{
f = new HomeFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 2:
{
f = new EndlessCustomView();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
return f;
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
This Activity:
public class BaseSampleActivity extends SlidingFragmentActivity {
private static final Random RANDOM = new Random();
TestFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
protected ListFragment mFrag;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.themed_titles);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mAdapter = new TestFragmentAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(1);
mIndicator = (TitlePageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
Applied solution according to this post:
MainActivity class:
//...
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
FragmentManager manager = getSupportFragmentManager();
for (int i = 0; i < tabAdapter.getClasses().size(); i++) {
String className = tabAdapter.getClasses().get(i).getName();
if (manager.findFragmentByTag(className) != null) {
manager.putFragment(outState, className, manager.findFragmentByTag(className));
}
}
}
//...
TabAdapter class:
//...
public void addTab(Class<?> clss, FragmentManager manager, Bundle savedInstanceState) {
classes.add(clss);
String className = clss.getName();
tags.add(className);
Fragment fragment;
if (savedInstanceState != null) {
fragment = manager.getFragment(savedInstanceState, className);
if (fragment == null) {
fragment = createFragment(className);
manager.beginTransaction().add(fragment, className);
}
} else {
fragment = createFragment(className);
manager.beginTransaction().add(fragment, className);
}
mFragments.add(fragment);
}
//...
where createFragment is a simple method, that creates needed fragment by passed class name.