Hide Android Fragment - android

Working With Android Framgent,I having Three fragments layout i want to hide fragment on the basis of flag.When First fragment is visible want disable second fragment
Am successfully able to hide tab headings of tab layout but not able to remove Page.How to achive it.?
I have searched alot but didn't find as i accepted.
public class Sample extends AppCompatActivity implements Commands.FragmentDataListener_Commands_epg{
Bundle dataBundle;
TabLayout tabLayout;
String flag;
private Sample.SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_customer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent intent=getIntent();
flag = intent.getStringExtra("flag");
mSectionsPagerAdapter = new Sample.SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
if(flag.equals("1")) {
tabLayout.removeTabAt(0);
}
else if(flag.equals("2"))
{
tabLayout.removeTabAt(1);
}
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onFragmentDataUpdated(Bundle dataBundle)
{
this.dataBundle=dataBundle;
}
#Override
public void onStart() {
super.onStart();
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
//first page
case 1:
//second page
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "First";
case 1:
return "second";
}
return null;
}
}}
Thank you in advance.

Since you get the flag in intent, you don't need tabLayout. Just init and the fragment to your view.
Some code like below:
Fragment fragmentInput = new FragmentAddVehicle();
FragmentManager getSupportFragmentManager.beginTransaction().add(R.id.ll_root_container, fragmentInput).commit();

Related

Tabs in Android disappears. Code was working before but now it stopped working

I have used Tab Control and RecyclerView together in Android. The way it functions is I have SearchBar in the toolbar. When the user enters the search query in the search bar. Upon hitting the search button, tab's Fragments are supposed to be loaded with data. Issues are as follows.
1) Tabs icon disappear
2) When debugging through the code found (Since I am using ViewPager with Tab Layout to implement Tabs in android) that getItem method of PagerAdapter class is called twice every time getItem is triggered.
I am stuck and don't know what to do. Not much help online as well.
1) Tab initialization Code:-
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout = (TabLayout)findViewById(R.id.tablayout);
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.craigslist_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.kijiji_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.letgo_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.varagesale_new1));
tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.facebook_new1));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
drawerLayout = findViewById(R.id.drawer_layout);
}
#Override
public boolean onQueryTextSubmit(String query) {
//loadRecyclerViewData(query);
Bundle bundle = new Bundle();
bundle.putString("searchText", query);
final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter(getSupportFragmentManager(), tabLayout.getTabCount(), bundle);
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return true;
}
2) PagerAdapter:-
public class PageAdapter extends FragmentStatePagerAdapter {
int mNoofTabs;
Bundle bundle;
public PageAdapter(FragmentManager fragmentManager, int NumberOfTabs, Bundle bundle)
{
super(fragmentManager);
this.mNoofTabs = NumberOfTabs;
this.bundle = bundle;
}
#Override
public Fragment getItem(int i) {
switch(i)
{
case 0 :
CraigslistFragment tab1 = new CraigslistFragment();
tab1.setArguments(bundle);
return tab1;
case 1:
KijijiFragment tab2 = new KijijiFragment();
tab2.setArguments(bundle);
return tab2;
case 2:
letgoFragment tab3 = new letgoFragment();
tab3.setArguments(bundle);
return tab3;
case 3:
VaragesaleFragment tab4 = new VaragesaleFragment();
tab4.setArguments(bundle);
return tab4;
case 4:
FacebookFragment tab5 = new FacebookFragment();
tab5.setArguments(bundle);
return tab5;
default:
return null;
}
}
#Override
public int getCount() {
return mNoofTabs;
}
}

How to re create the fragment in viewpager

I have a viewpager with 5 tabs , each tab is fragment showing different data to user , each fragment have recycleview inside itself , and i need to re insert updated data into the recyclerview when user change the tab, and I need to update the view
Every time I swipe to a tab, a new instance of the fragment in that tab needs to load so that data will be updated.
I have tried:
1- I used FragmentStatePagerAdapter (nothing happens)
2- I Override getItemPosition method to return PagerAdapter.POSITION_NONE; (nothing happens)
3- setOffscreenPageLimit(0) (Nothing happens)
4- refresh function inside each fragment to be called onTabSelected
(gives nullPointerException)
How can i recreate fragment from scratch each time user change the tab
i really need to know.
I have been struggling with this problem for a week with no progress. I appreciate any help, be it a hint, a comment, a suggestion.
Let me know what code should I post, Thanks.
Edit:
my codes:
MainActivity:
public class Sefaresh_activity3 extends AppCompatActivity implements Serializable, Sefaresh3_interface {
Context context;
Toolbar mtoolbar;
private List<Food> food_list = new ArrayList<>();
MyPagerAdapter adapter;
Custom_TabLayout mTabLayout;
ViewPager mpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sefaresh_activity3);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
}
context = this;
sqlHelper = new SqlHelper(this);
setupTabs();
private void setupTabs() {
mtoolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(mtoolbar);
SpannableString s = new SpannableString(getTitle());
s.setSpan(new TypefaceSpan(this, "IRAN Sans Bold.ttf"), 0, s.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
setTitle(s);
try {
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} catch (Exception e) {
L.m("something is wrong in toolbar section");
}
adapter = new MyPagerAdapter(getSupportFragmentManager());
mTabLayout = (Custom_TabLayout) findViewById(R.id.tab_layout);
mpager = (ViewPager) findViewById(R.id.viewpager);
mpager.setAdapter(adapter);
mTabLayout.setTabsFromPagerAdapter(adapter);
mTabLayout.setupWithViewPager(mpager);
mpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
L.m("tab selected" + tab.getPosition());
mpager.setCurrentItem(tab.getPosition());
// Sefaresh3_fragment all_fragment = (Sefaresh3_fragment) adapter.getFragment_all();
// sefaresh3_fragment.onRefresh();
// Sefaresh3_fragment sefaresh3_fragment = (Sefaresh3_fragment) adapter.fragment_all;
// adapter.notifyDataSetChanged();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
class MyPagerAdapter extends FragmentStatePagerAdapter {
// public ArrayList<Fragment> fragmentArrayList = new ArrayList<>();
Fragment fragment_all;
Fragment fragment_pizza;
Fragment fragment_sandwich;
Fragment fragment_salad;
Fragment fragment_coca;
public Fragment getFragment_coca() {
return fragment_coca;
}
public Fragment getFragment_all() {
return fragment_all;
}
public Fragment getFragment_pizza() {
return fragment_pizza;
}
public Fragment getFragment_sandwich() {
return fragment_sandwich;
}
public Fragment getFragment_salad() {
return fragment_salad;
}
String[] tabs = {
"products",
"new products",
"featured",
"star",
"star2"
};
#Override
public int getItemPosition(Object object) {
return PagerAdapter.POSITION_NONE;
}
public MyPagerAdapter(FragmentManager fm) {
super(fm);
tabs = getResources().getStringArray(R.array.sefaresh3_tabs);
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public Fragment getItem(int num) {
Fragment fragment = null;
orders = new Orders();
orders.setOrders(all_orders);
switch (num) {
case 0:
// fragment_all = Sefaresh3_fragment.newInstance("all", "");
// return new Sefaresh3_fragment().newInstance("all","");
return Sefaresh3_fragment.newInstance("all","");
case 1:
fragment_pizza = Sefaresh3_fragment.newInstance("pizza", "");
return fragment_pizza;
case 2:
fragment_sandwich = Sefaresh3_fragment.newInstance("sandwich", "");
return fragment_sandwich;
case 3:
fragment_salad = Sefaresh3_fragment.newInstance("salad", "");
return fragment_salad;
case 4:
fragment_coca = Sefaresh3_fragment.newInstance("coca", "");
return fragment_coca;
default:
return fragment;
}
}
#Override
public CharSequence getPageTitle(int position) {
return tabs[position];
}
#Override
public int getCount() {
return 5;
}
}
thanks for everybody suggestions , after one week struggling with this problem I found the solution.
I tried several methods but finally I just found the solution.
I used Broadcast receiver to tell the fragment update the list , and every time I need to update the fragments to update the data list , I call the broadcaster. its awesome and it works well
If anyone had the same problem I will be happy to help him :) thanks.

How to add back button on action bar with more fragments

know anyone how can I add one back button one my action bar?Here it's my acplication and I want to add it before INFO button.
I've try to add that code for action bar but it don't works:
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
Here it's my activity:
public class TrailActivity extends FragmentActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
Intent intent;
Trail trail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
intent = getIntent();
setContentView(R.layout.trail_fracment_main);
trail = intent.getParcelableExtra("trail");
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setHomeButtonEnabled(true);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, tell the ViewPager to switch to the corresponding page.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
InfoFragments infoFragments = new InfoFragments();
infoFragments.setTrail(trail);
Fragment fragment = infoFragments;
return fragment;
} else if (position == 1) {
return new MapFragments();
} else {
return new WondersFragments();
}
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
}
EDITED:
In the left part it's how should be looks my action bar with back button and in the right part it's the actually my application right now. So.. How can I make it to looks like the aplication from left part?
If anyone know please show me how I can do it.
Thx :D
Implement OnBackStackChangedListener and add this code to your Fragment Activity.
#Override
public void onCreate(Bundle savedInstanceState) {
//Listen for changes in the back stack
getSupportFragmentManager().addOnBackStackChangedListener(this);
//Handle when activity is recreated like on orientation Change
shouldDisplayHomeUp();
}
#Override
public void onBackStackChanged() {
shouldDisplayHomeUp();
}
public void shouldDisplayHomeUp(){
//Enable Up button only if there are entries in the back stack
boolean canback = getSupportFragmentManager().getBackStackEntryCount()>0;
getSupportActionBar().setDisplayHomeAsUpEnabled(canback);
}
#Override
public boolean onSupportNavigateUp() {
//This method is called when the up button is pressed. Just the pop back stack.
getSupportFragmentManager().popBackStack();
return true;
}
If you are looking for Back Arrow beside the ActionBar tabs.Using Sherlock you can do it.Try this
https://stackoverflow.com/a/12703960/2365507

Can I add protected void onResume() to Fragment class to launch something when the UI restored in Android?

In AppCompatActivity , I can add the code protected void onResume() to launch some function when UI is shown or restored.
Now I created a Tabbed Activity, I add the code protected void onResume() to PlaceholderFragmentOld class , and I hope the system do someting when the UI cleanup_delete_fragment_old is shown, but the system crash and return the following error.
android.support.v4.app.SuperNotCalledException: Fragment PlaceholderFragmentOld{40e55078 #0 id=0x7f0f0070 android:switcher:2131689584:0} did not call through to super.onResume()
PlaceholderFragmentOld.java
public class PlaceholderFragmentOld extends Fragment {
private AdView adView;
private SMSRange mSmsRange;
private View mView;
private Context mContext;
private Spinner spinnerRanger;
private CheckBox chIsWriteLog;
public PlaceholderFragmentOld() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.cleanup_delete_fragment_old, container, false);
mView=rootView;
mContext=rootView.getContext();
return rootView;
}
#Override
protected void onResume() {
DoSometing();
}
}
CleanupDelete.java
public class CleanupDelete extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cleanup_delete);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch(position){
case 0:
fragment = new PlaceholderFragmentOld();
break;
case 1:
fragment = new PlaceholderFragmentReduce();
break;
case 2:
fragment = new PlaceholderFragmentTrim();
break;
case 3:
fragment = new PlaceholderFragmentPerson();
break;
default:
throw new IllegalArgumentException("Invalid section number");
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.Tab_Old);
case 1:
return getString(R.string.Tab_Reduce);
case 2:
return getString(R.string.Tab_Trim);
case 3:
return getString(R.string.Tab_Person);
}
return null;
}
}
}
Yes, you can add onResume() to a Fragment.
The error your getting states:
SuperNotCalledException: PlaceholderFragmentOld did not call through to super.onResume()
You need to call super.onResume() as the first line in your onResume() method, otherwise the system will complain. Something like this would work
protected void onResume(){
super.onResume();
doSomething();
}

view pager with fragments having listview updating multiple times

I am trying to implement 3 fragments within View pager. All of the fragments has their own list view. Whenever i am swiping back to the first fragment the list view is updating itself getting duplicate values. here is the main activity implementing the view pager. Please suggest.
public class MainActivity extends FragmentActivity {
/** Called when the activity is first created. */
static AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
SearchView mSearchView;
MenuItem menuSearch;
Boolean flag = false;
String pid;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setupActionBar();
getActionBar().setTitle("All Patients");
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager, attaching the adapter and setting up a listener for when the
// user swipes between sections.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new OnPageChangeListener()
{
public void onPageSelected(int position)
{
//mAppSectionsPagerAdapter.getItemPosition(getFragmentManager().findFragmentById(position));
//getActionBar().setTitle(mAppSectionsPagerAdapter.getPageTitle(position));
if(position==0){
getActionBar().setTitle("All Patients");
//flag = true;
//menuSearch.setVisible(true);
invalidateOptionsMenu();
}
if(position==1){
getActionBar().setTitle("All Doctors");
//flag=false;
//menuSearch.setVisible(false);
invalidateOptionsMenu();
}
else
getActionBar().setTitle("All Nurses");
invalidateOptionsMenu();
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
}
public void onPageScrollStateChanged(int state)
{
if (state == ViewPager.SCROLL_STATE_DRAGGING)
{
}
if (state == ViewPager.SCROLL_STATE_IDLE)
{
}
}
});
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to one of the primary
* sections of the app.
*/
public static class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new AllPatient();
case 1:
//Intent intent = new Intent(MainActivity.this,abc.class);
return new AllDoctors();
case 2:
return new AllNurses();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Try this:
mViewPager.setOffscreenPageLimit(3);

Categories

Resources