How to set selected tab job in on create [duplicate] - android

This question already has answers here:
ViewPager set current page programmatically
(3 answers)
Closed 4 years ago.
I have 3 tabs containing difference Fragments as:
Product and Services
Business Directory
Job
Bellow is my TabFragement Adapter The code is worked correctly but only 1 thing I want is:
=> I want to set Job Fragment as default in onCreate
This is my adapter.
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3 ;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new Product_Service();
case 1 : return new Business_Dir();
case 2 : return new Job();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Product & Srevices";
case 1 :
return "Business Directory";
case 2 :
return "Job";
}
return null;
}
}
}

You can use the fragment position index to show particular fragment as default using setCurrentItem method ofViewPager docs. Do this after setting adapter on viewpager
viewPager.setCurrentItem(2, false); // job fragment index is 2
false here mean , the transition to fragment 3 will be done instantly and if you pass true then chosen fragment will be displayed using scrolling effects ( you can use true when you want to give a little tour to user for first time)

Related

App freezes forever when Fragment get's displayed

Since I implemented a BottomAppBar my App isn't responding when a certain Fragment should get displayed even though I haven't changed anything. There isn't an error message either and all other Fragments which are getting displayed when another item in the BottomNavigationBar is clicked work fine.
Fragment:
public class StatisticsFragment extends Fragment {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private BankAccountsStatisticsFragment bankAccountsStatisticsFragment = new BankAccountsStatisticsFragment();
private BillsStatisticsFragment billsStatisticsFragment = new BillsStatisticsFragment();
private CategoriesStatisticsFragment categoriesStatisticsFragment = new CategoriesStatisticsFragment();
private GoalsStatisticsFragment goalsStatisticsFragment = new GoalsStatisticsFragment();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View inflatedView = inflater.inflate(R.layout.fragment_statistics, container, false);
mTabLayout = (TabLayout) inflatedView.findViewById(R.id.tl_statistics);
mViewPager = (ViewPager) inflatedView.findViewById(R.id.vp_statistics);
mViewPager.setAdapter(new Adapter(getChildFragmentManager()));
mTabLayout.setupWithViewPager(mViewPager);
return inflatedView;
}
private class Adapter extends FragmentPagerAdapter {
private static final int TABS = 4;
public Adapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0: return bankAccountsStatisticsFragment;
case 1: return billsStatisticsFragment;
case 2: return categoriesStatisticsFragment;
case 3: return goalsStatisticsFragment;
default: throw new IllegalStateException("Couldn't find a fragment for position " + position);
}
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0: return getString(R.string.tab_bank_accounts);
case 1: return getString(R.string.tab_bills);
case 2: return getString(R.string.tab_categories);
default: return getString(R.string.tab_goals);
}
}
#Override
public int getCount() {
return TABS;
}
}
}
LOGCAT
LOGCAT
Inflating a Layout and creating a Fragment transition (like the "FragmentManager....replace().commit()") are done in the MainThread where the UserInterface is rendered, so the UserInterface will freeze in these moments.
I think you have to pre-load the "bad" Fragment and just HIDE it instead of Destroy it...in this way the next time you want to create it is already ready.

How to create one fragment at a time using viewpager

I am using two fragments inside viewpager. In the second fragment, I play a video from url using exoplayer. My problem is that when the activity is launch, the video is loaded automatically because all fragments are automatically created by viewpager. How to create one frament at a time so that the second fragment can play the video only if it is visible to the user (by swipping or tapping the tab).
The viewpager adapter
class ViewPagerAdapter extends FragmentStatePagerAdapter {
Bundle bundle;
public ViewPagerAdapter(FragmentManager manager, Bundle bundle) {
super(manager);
this.bundle = bundle;
}
#Override
public Fragment getItem(int position) {
Log.d("getItem", position + "");
switch (position) {
case 0:
IngredientListFragment ingredientListFragment = new IngredientListFragment();
ingredientListFragment.setArguments(bundle);
return ingredientListFragment;
case 1:
StepsListFragment stepsListFragment = new StepsListFragment();
stepsListFragment.setArguments(bundle);
return stepsListFragment;
default:
IngredientListFragment ing = new IngredientListFragment();
ing.setArguments(bundle);
return ing;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Ingredients";
case 1:
return "Steps";
default:
return "Ingredients";
}
}
}
Inside the activity
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager(), bundle);
viewPager.setAdapter(adapter);
tabLayout.setupWithViewPager(viewPager);
Please Help.
you do not need to create fragment one at a time:
use this code in second fragment to run exoplayer when user open that fragment:
private boolean _hasLoadedOnce = false; // your boolean field
#Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
if (isFragmentVisible_ && !_hasLoadedOnce) {
// move exoplayer code here so this code run only when user select this fragment
_hasLoadedOnce = true;
}
}
}
One more thing, you have to put this line after creating viewpager:
in your case after
tabLayout.setupWithViewPager(viewPager);
viewPager.setOffscreenPageLimit(1);

Tab Slider Android Studio not working

I set up a tab slider in my activity calling 3 separate fragments depending on the fragment selected. The problem is that when the first tab is selected, "Science" is shown - which was set on the onCreateView() method of the first fragment. However, WITHOUT clicking on the other tabs, "Technology" and "Sports" are then shown.
To my knowledge, the way I implemented it the last two should only show once the corresponding tab is selected.
This is my Page adapter class
public class PagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 3; //Represents the number of tabs
private String tabTitles[] = new String[]{"Technology", "Science", "Sports"}; //Tab values defined in an array
private Context context;
public PagerAdapter(FragmentManager fm, Context context)
{
super(fm);
this.context = context;
}
#Override
public int getCount()
{
return PAGE_COUNT;
}
//determines the fragment depending on the selected tab
#Override
public Fragment getItem(int position)
{
if(position==0)
return TechnologyFragment.newInstance(position+1);
else if(position==1)
return ScienceFragment.newInstance(position+1);
else if(position==2)
return SportsFragment.newInstance(position+1);
else
return null;
}
//displays the title for each tab
#Override
public CharSequence getPageTitle(int position)
{
// Generate title based on item position
return tabTitles[position];
}
}
This is the news class - where the view pager and tab layout are set up
public class News extends AppCompatActivity {
//Here the viewPager is connected to the PagerAdapter class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_news);
//This component will be used to page between the various fragments created.
final ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new PagerAdapter(getSupportFragmentManager(), News.this));
//the tabLayout is given the viewPager to connect to the pager with the tabs
TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs);
tabLayout.setupWithViewPager(viewPager);
//the following was used so the tabs fill up the width of the screen being responsive for all devices and orientations
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
tabLayout.setTabMode(TabLayout.MODE_FIXED);
}
}
And these are the fragment classes - (the other two are identical but have a different message represented using the Toast)
public class ScienceFragment extends Fragment {
//other methods
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_science_fragment, container, false);
toShow=getAll();
GridView gridView = (GridView)view.findViewById(R.id.gridview);
gridView.setAdapter(new ImageAdapter(getContext(),toShow));
Toast.makeText(getContext(), "Science", Toast.LENGTH_SHORT).show();
return view;
}
}
Any help is appreciated

Fragment ActionBar Item will not show

I have a tabbed fragment, with drawer and I am attempting to force the ActionBar button to appear. At present, it is pushed to the overflow menu...
How can I configure the item to always appear in the action bar?
Fragment:
public class EventsTabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 3;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout, null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
setHasOptionsMenu(true);
return x;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.events_menu, menu);
}
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
/**
* Return fragment with respect to Position .
*/
#Override
public Fragment getItem(int position) {
// Need to build
// Order/first appearing will be specific to time of day, ie. if in morning, then breakfast/brunch, if midday then lunch, late then dinner
switch (position) {
case 0:
return new BreakfastFragment(); // ChatActivity();
case 1:
return new BreakfastFragment();
case 2:
return new UpdatesFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
/**
* This method returns the title of the tab according to the position.
*/
#Override
public CharSequence getPageTitle(int position) {
// Order/first appearing will be specific to time of day, ie. if in morning, then breakfast/brunch, if midday then lunch, late then dinner
switch (position) {
case 0:
return "Upcoming";
case 1:
return "Invited";
case 2:
return "Past";
}
return null;
}
}
}
Menu:
<item
android:id="#+id/action_filter"
android:title="test"
android:icon="#drawable/inbox"
mytest:showAsAction="always" />
Where are you inflating your Toolbar?
private Toolbar toolbar; // add this as a global declaration (outside of oncreate)
//inside onCreateView
toolbar = (Toolbar) findViewById(R.id.toolbar_name_in_xml);
toolbar.inflateMenu(R.menu.YourMenuNameInXML);
Does this make any difference? After I stopped using setSupportActionBar() I had to inflate the menu from a Toolbar object like in the code above for it to work.

Change Fragment with ViewPager

I am using PagerSlidingTab Library for ViewPager. And I want to change Fragment while scrolling of tabs. It is working fine. Check out my code.
I am using AsynTask() on each Fragment.
When the App opens with the MainActivity, First Fragment is attached to the activity, But It shows two AsynTask() dialog message, one from First and another from Second Fragment. And When I scroll to second tab, It shows dialog message of Third Fragment.
So, If I scroll from left to right in tabs, the Fragment right to the current fragment is displayed and if i scroll from right to left, the Fragment left to the current Fragment is displayed.
Please help me to solve the problem.
My Code:
public class PageSlidingTabStripFragment extends Fragment {
public static final String TAG = PageSlidingTabStripFragment.class
.getSimpleName();
public static PageSlidingTabStripFragment newInstance() {
return new PageSlidingTabStripFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.pager, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) view
.findViewById(R.id.tabs);
ViewPager pager = (ViewPager) view.findViewById(R.id.pager);
MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager());
pager.setAdapter(adapter);
tabs.setViewPager(pager);
}
public class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
private final String[] TITLES = { "Instant Opportunity", "Events",
"Experts" };
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new InstantOpportunity();
case 1:
return new Events();
case 2:
return new Experts();
default:
break;
}
return null;
}
}
}
Explanation:
It turns out there is an easier implementation for scrollable tabs which doesn't involve another library. You can easily implement tabs into your app using normal Android code straight from the default SDK.
The Code
Main Class:
public class PageSlidingTabStripFragment extends Fragment {
//Variables
private ViewPager viewPager;
private PagerTitleStrip pagerTitleStrip;
public PageSlidingTabStripFragment() {
// Required empty public constructor
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Find your pager declared in XML
viewPager = (ViewPager) getView().findViewById(R.id.pager);
//Set the viewPager to a new adapter (see below)
viewPager.setAdapter(new MyAdapter(getFragmentManager()));
//If your doing scrollable tabs as opposed to fix tabs,
//you need to find a pagerTitleStrip that is declared in XML
//just like the pager
pagerTitleStrip = (PagerTitleStrip)
getView().findViewById(R.id.pager_title_strip);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.[your layout name here], container, false);
}
}
Adapter:
//Note: this can go below all of the previous code. Just make sure it's
//below the last curly bracket in your file!
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment fragment = null;
if (arg0 == 0) {
fragment = new InstantOpportunity();
}
if (arg0 == 1) {
fragment = new Events();
}
if (arg0 == 2) {
fragment = new Experts();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Instant Opportunity";
}
if (position == 1) {
return "Events";
}
if (position == 2) {
return "Experts";
}
return null;
}
}
Conclusion:
I hope this helps you understand another way to make scrollable tabs! I have examples on my Github Page about how to make each type (That being Fixed or Scrollable).
Links:
Fixed Tabs Example - Click Here
Scrollable Tabs Example - Click Here
Hope this helps!
Edit:
When asked what to import, make sure you select the V4 support fragments.
please use this example..its very easy.i already implement that.
reference link
hope its useful to you.its best example of pager-sliding-tabstrip.
Use
framelayout compulsory:
FrameLayout fl = new FrameLayout(getActivity());
fl.addView(urFragementView);
and then set your fragement view in this framelayout.

Categories

Resources