My code was working few hours ago but not anymore, I can't see what is the reason.
Here is my listener where I change fragment after a click :
CustomMarkRow.java
public void onClick(DialogInterface dialogInterface, int i){
Bundle bundle = new Bundle();
bundle.putInt("id", CustomMarkRow.this.mark.getId());
FragmentManager fragmentManager = CustomMarkRow.this.fragmentManager;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); activity.getActionBar().setSelectedNavigationItem(CustomMarkRow.this.positionTab);
EditMarkFragment fragment = new EditMarkFragment();
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.fragmentContainer, fragment,"2");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
At this moment, fragment.getArguments() contains what I put inside :
{android.os.Bundle#3644} "Bundle[{id=1}]"
In my second file :
EditMarkFragment.java
public class EditMarkFragment extends Fragment {
public View view;
public EditMarkFragment(){
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.view = inflater.inflate(getResources().getIdentifier("edit_mark", "layout",container.getContext().getPackageName()), container, false);
if(this.getArguments()==null){ // always null
...
}
return this.view
}
getArguments() always return null here, What is bad in this sample ?
* edit *
Here is my launcher class :
public class Launcher extends Activity implements ActionBar.TabListener {
private HomeFragment frag1 = new HomeFragment();
private EditMarkFragment frag2 = new EditMarkFragment();
private MarkListFragment frag3 = new MarkListFragment();
private EditCategoryFragment frag4 = new EditCategoryFragment();
private CategoryListFragment frag5 = new CategoryListFragment();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.launcher);
//Configuration de la barre d'onglet
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = getActionBar().newTab().setTabListener(this).setTag("1").setText("Home"); //.setIcon(R.drawable.homew);
getActionBar().addTab(tab1);
ActionBar.Tab tab2 = getActionBar().newTab().setTabListener(this).setTag("2").setText("New Mark"); //.setIcon(R.drawable.addw);
getActionBar().addTab(tab2);
ActionBar.Tab tab3 = getActionBar().newTab().setTabListener(this).setTag("3").setText("My Marks"); //.setIcon(R.drawable.listw);
getActionBar().addTab(tab3);
ActionBar.Tab tab4 = getActionBar().newTab().setTabListener(this).setTag("4").setText("New Category"); //.setIcon(R.drawable.categoryw);
getActionBar().addTab(tab4);
ActionBar.Tab tab5 = getActionBar().newTab().setTabListener(this).setTag("5").setText("Categories"); //.setIcon(R.drawable.categoryw);
getActionBar().addTab(tab5);
}
#Override
public void onTabSelected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if(tab.getTag().equals("1")){
ft.replace(R.id.fragmentContainer, frag1);
}
else if(tab.getTag().equals("2")){
ft.replace(R.id.fragmentContainer, frag2);
}
else if(tab.getTag().equals("3")){
ft.replace(R.id.fragmentContainer, frag3);
}
else if(tab.getTag().equals("4")){
ft.replace(R.id.fragmentContainer, frag4);
}
else if(tab.getTag().equals("5")){
ft.replace(R.id.fragmentContainer, frag5);
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
if(tab.getTag().equals("1")){
ft.remove(frag1);
}
else if(tab.getTag().equals("2")){
ft.remove(frag2);
}
else if(tab.getTag().equals("3")){
ft.remove(frag3);
} else if(tab.getTag().equals("4")){
ft.remove(frag4);
}
else if(tab.getTag().equals("5")){
ft.remove(frag5);
}
}
#Override
public void onTabReselected(ActionBar.Tab tab, android.app.FragmentTransaction ft) {
}
}
While your onClick() code is creating an arguments Bundle, your onCreate() is not. If that edition of your fragment calls getArguments(), the method will return null.
1-Update your EditMark fragment with as follows:-
public class EditMarkFragment extends Fragment {
public static View view;
public static EditMarkFragment newInstance(int id) {
EditMarkFragment fragment = new EditMarkFragment();
Bundle bundle = new Bundle();
bundle.putInt("id", id);
fragment.setArguments(bundle);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
this.view = inflater.inflate(getResources().getIdentifier("edit_mark", "layout",container.getContext().getPackageName()), container, false);
int id=getArguments.getInt("id");
return this.view}
2- Inside CustomMarkRow update your code as :-
public void onClick(DialogInterface dialogInterface, int i){
FragmentManager fragmentManager = CustomMarkRow.this.fragmentManager;
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); activity.getActionBar().setSelectedNavigationItem(CustomMarkRow.this.positionTab);
EditMarkFragment fragment = EditMarkFragment.newInstance(CustomMarkRow.this.mark.getId()) ;
fragmentTransaction.replace(R.id.fragmentContainer, fragment,"2");
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
Try this,hope this will hep you.
Related
i have one activity which contains spinner control in appbar. in homeActivity i'm using fragment which have default fragment as parentoptionfragment, from that fragment there are 3 option to change the fragments, if i have choosen one fragment from parentoption fragment and i want to change spinner value then the fragment should be updated without adding to backstack means if i press back button then it should call parent optionfragment, but when i'm trying to do so i'm getting error.
public void GetChildData(String token) {
ParentOptionsFragment fragment =new ParentOptionsFragment();
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
tv_childClassname.setText(classNameArr[position]);
tv_childSchoolName.setText(schoolNameArr[position]);
Fragment f = getSupportFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof ChildMapFragment){
Toast.makeText(HomeActivity.this, "refreshing childmapfragment", Toast.LENGTH_SHORT).show();
ChildMapFragment fragment = new ChildMapFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStackImmediate (fragment.getClass().getName(), 0);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}else if(f instanceof ParentOptionsFragment){
Toast.makeText(HomeActivity.this, "spinner changed from ParentOptionsFragment", Toast.LENGTH_SHORT).show();
}
}
parentoptionfragment.java
public class ParentOptionsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_parent_options, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ImageView img1=(ImageView)view.findViewById(R.id.imageView);
ImageView img2=(ImageView)view.findViewById(R.id.imageView2);
ImageView img3=(ImageView)view.findViewById(R.id.img_transport);
img3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ChildMapFragment fragment = new ChildMapFragment();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
/*final ViewTreeObserver vto = img1.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
int x;
img1.getViewTreeObserver().removeOnPreDrawListener(this);
x = img1.getMeasuredWidth();
img1.setLayoutParams(new LinearLayout.LayoutParams(x,x));
return true;
}
});*/
}
}
childfragment.java
public class ChildFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_child_map, container, false);
}
}
homeActivity ---> defaultfragment-- parentoptionfragment
parentoptiofragment---> childfragment
using spinner update childfragment without backstack
onbackpress of childfragment --> parentoptionfragment
replace
Toast.makeText(HomeActivity.this, "refreshing childmapfragment", Toast.LENGTH_SHORT).show();
ChildMapFragment fragment = new ChildMapFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStackImmediate (fragment.getClass().getName(), 0);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
with :
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.popBackStack()
update :
on your child fragment add a method : update() and call it :
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fragment = fragmentManager.findFragmentById(R.id.fragment_container)
if(fragment isInstanceOf ChildMapFragment ){
((ChildMapFragment )fragment).update() //call your update method here
}
FragmentManager fragmentManager = getSupportFragmentManager();
// String f_name=fragment.getClass().getName();
if (!fragmentManager.popBackStackImmediate(tag, 0)) {
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, fragment, tag);
ft.addToBackStack(tag);
ft.commit();
}
to Refresh fragment implement back stack in activity like this
#Override
public void onBackStackChanged() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment fr = fragmentManager.findFragmentById(R.id.content_frame);
if (fr != null) {
fr.onResume();
}
}
here pass different tag base on different fragment
I have a navigation drawer with menu HOME, SETTING, ABOUT US etc on a fragment. And only HOME has a swipe tab. On the start of the app, Home is opened, but after that whenever i click home again it shows error saying Home Fragment is not attached to Activity.
my code is as follows
Drawer.java
which is mainAciticity
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
myDrawerLayout.closeDrawer(drawerBody);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment;
switch (position){
case 0:
fragment = new Home();
fragmentTransaction.replace(R.id.main_content, fragment);
break;
case 1:
fragment = new Settings();
fragmentTransaction.replace(R.id.main_content, fragment);
break;
case 2:
fragment = new Aboutus();
fragmentTransaction.replace(R.id.main_content, fragment);
break;
case 3:
fragment = new Help_and_Feedback();
fragmentTransaction.replace(R.id.main_content, fragment);
break;
case 4:
fragment = new Fill_up_form();
fragmentTransaction.replace(R.id.main_content, fragment);
break;
}
setTitle(position);
fragmentTransaction.commit();
}
Home.java
public class Home extends Fragment implements ActionBar.TabListener {
ViewPager myViewPager;
ActionBar myActionBar;
MyFragmentPagerAdapter myFragmentPagerAdapter;
String[] selectedTabImage;
String[] unselectedTabImage;
String[] BloodGroups;
public Home() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.home, container, false);
//Initialization
myViewPager = (ViewPager) v.findViewById(R.id.viewpager);
myFragmentPagerAdapter = new MyFragmentPagerAdapter(getActivity().getSupportFragmentManager());
//viewpager work
myViewPager.setAdapter(myFragmentPagerAdapter);
myViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int i, float v, int i2) {
}
#Override
public void onPageSelected(int i) {
myActionBar.setSelectedNavigationItem(i);
}
#Override
public void onPageScrollStateChanged(int i) {
}
});
myActionBar =((ActionBarActivity)getActivity()).getSupportActionBar();
myActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//get the array of images for tab
selectedTabImage = getResources().getStringArray(R.array.tab_selected);
unselectedTabImage = getResources().getStringArray(R.array.tab_unselected);
BloodGroups = getResources().getStringArray(R.array.blood_groups);
//Add Tabs
for (int i = 0; i < myFragmentPagerAdapter.getCount(); i++) {
String name = selectedTabImage[i];
int tabId = getResources().getIdentifier(name,"drawable", getActivity().getPackageName());
myActionBar.addTab(myActionBar.newTab().setIcon(tabId).setTabListener(this));
}
return v;
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
int pos = tab.getPosition();
myViewPager.setCurrentItem(pos);
String name = selectedTabImage[pos];
int tabId = getResources().getIdentifier(name,"drawable", getActivity().getPackageName());
tab.setIcon(tabId);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
String name = selectedTabImage[tab.getPosition()];
int tabId = getResources().getIdentifier(name,"drawable", getActivity().getPackageName());
tab.setIcon(tabId);
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new DonarList();
Bundle args = new Bundle();
args.putInt("bloodGroupPosition", position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return 8;
}
}
#Override
public void onStop() {
super.onStop();
myActionBar.setNavigationMode(0);
}
}
the error stacktrace
05-29 14:44:31.961 12034-12034/com.example.p6.bloodies E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Fragment Home{4120fd50} not attached to Activity
at android.support.v4.app.Fragment.getResources(Fragment.java:619)
at com.example.p6.bloodies.Home.onTabSelected(Home.java:114)
at android.support.v7.internal.app.WindowDecorActionBar.selectTab(WindowDecorActionBar.java:634)
at android.support.v7.internal.app.WindowDecorActionBar.setSelectedNavigationItem(WindowDecorActionBar.java:414)
at android.support.v7.internal.app.WindowDecorActionBar.setNavigationMode(WindowDecorActionBar.java:1297)
at com.example.p6.bloodies.Home.onCreateView(Home.java:72)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:454)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:817)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
at dalvik.system.NativeStart.main(Native Method)
The code in line 72
myActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
The code in line 114
int tabId = getActivity().getResources().getIdentifier(name,"drawable", getActivity().getPackageName());
Not really clear and Cannot see your full activity code but Possibly your activity is still doing some (background) process or something when the code for the fragment runs. try moving the code to onActivityCreated() in the fragment life cycle which by then the fragment has been attached to the activity. Also good to check if fragment is already added in your code like.
if(!isAdded()) {
return;
}
Remove current fragment by this method may solve your issue
public void removeFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.remove(fragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
transaction.commit();
}
I have created 10 tabs programmatically and want to change number of buttons that are placed in fragment when a tab is clicked by user.
My 'MainActivity' code:
public class MainActivity extends Activity {
int numberOfButtons=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentA fragmentA = new FragmentA();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.mainLayout,fragmentA,"fragA");
transaction.commit();
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
for (int i=0;i<10;i++)
{
ActionBar.Tab tab = actionBar.newTab().setText("Tab"+i).setTabListener(new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
numberOfButtons = 10;
sendNumber(numberOfButtons);
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
}
});
actionBar.addTab(tab);
}
}
This is my fragment code:
public class FragmentA extends Fragment implements View.OnClickListener{
Button btn;
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
int numberOfButtons= getArguments().getInt("someInt",0);
LinearLayout view = new LinearLayout(getActivity());
// Inflate the layout for this fragment
view.setOrientation(LinearLayout.VERTICAL);
view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
for (int i = 0;i<numberOfButtons;i++)
{
btn = new Button(getActivity());
view.addView(new Button(getActivity()));
}
myView = view;
return myView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onClick(View v) {
}
}
I am calling the numbeOfButtons method inside the MainActivity and want to send number of buttons to Fragment when a tab is clicked. However the application throws error after line fA.numberOfBtns(numberOfButtons); is called. The error is reflect.InvocationTargetException.
How can I change the number of buttons in Fragment when a tab is clicked?
You may want to use newInstance technique to pass parameters during Fragment initialization. Here is a small example taken from here:
public static MyFragment newInstance(int someInt) {
MyFragment myFragment = new MyFragment();
Bundle args = new Bundle();
args.putInt("someInt", someInt);
myFragment.setArguments(args);
return myFragment;
}
And later you can access this parameter:
getArguments().getInt("someInt", 0);
I am creating a tab application, using fragments.
I have successfully created tabs, but now I need to create an object when a specific fragment is selected. e.g. When I select SettingsTab I need to call a function that is defined in Test class. and similarly destroy
// SettingsTab
package com.example.sensorspositioningn;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SettingsTab extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.settingstab, container, false);
}
}
Here is the code in mainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appContext = getApplicationContext();
//ActionBar
ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab Tab1= actionbar.newTab().setText("Tab1");
ActionBar.Tab Tab2= actionbar.newTab().setText("Tab2");
ActionBar.Tab Tab3= actionbar.newTab().setText("Tab3");
ActionBar.Tab SettingsTab = actionbar.newTab().setText("Settings");
Fragment Tab1F= new Tab1();
Fragment Tab2F= new Tab2();
Fragment Tab3F= new Tab3();
Fragment mSettingsFragment = new SettingsTab();
Tab1.setTabListener(new MyTabsListener(Tab1F));
Tab1.setTabListener(new MyTabsListener(Tab2F));
Tab1.setTabListener(new MyTabsListener(Tab3F));
SettingsTab.setTabListener(new MyTabsListener(mSettingsFragment));
actionbar.addTab(Tab1);
actionbar.addTab(Tab2);
actionbar.addTab(Tab3);
actionbar.addTab(SettingsTab);
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getSelectedNavigationIndex());
}
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
In your ActionBar.TabListener you can do this - (I'm assuming that you need the object to be in the Activity)
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
if(fragment instanceof SettingsTab) {
// Create your object, call your function
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
if(fragment instanceof SettingsTab) {
// Destroy your object
}
}
}
Try this
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
if(fragment instanceof SettingsTab){
doSettingsMethod();
}
if(fragment instanceof Tab1){
doOtherMethod1();
}
if(fragment instanceof Tab2){
doOtherMethod2();
}
if(fragment instanceof Tab3){
doOtherMethod3();
}
}
Also you may change TabListener class in this way. As for me it's a better design.
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
private final Runnable onSelect;
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
this.onSelect = null;
}
public MyTabsListener(Fragment fragment, Runnable onSelect) {
this.fragment = fragment;
this.onSelect = onSelect;
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(MainActivity.appContext, "Reselected!", Toast.LENGTH_LONG).show();
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
ft.replace(R.id.fragment_container, fragment);
if(onSelect != null){
fragment.getActivity().runOnUiThread(onSelect);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}
The only official source I found to this was on the developer site:
http://developer.android.com/training/implementing-navigation/lateral.html
They simply put arguments for each created fragment, and read the arguments when the fragments get selected.
By default if you select a tab it will be highlighted. If you want to select Explicitly means use the given commented code under onTabSelected(TabLayout.Tab tab) with your specified tab index position. This code will explains about change fragment on tab selected position using viewpager.
public class GalleryFragment extends Fragment implements TabLayout.OnTabSelectedListener
{
private ViewPager viewPager;public ViewPagerAdapter adapter;private TabLayout tabLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gallery, container, false);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
adapter = new ViewPagerAdapter(getChildFragmentManager());
adapter.addFragment(new PaymentCardFragment(), "PAYMENT CARDS");
adapter.addFragment(new LoyaltyCardFragment(), "LOYALTY CARDS");
viewPager.setAdapter(adapter);
tabLayout = (TabLayout) rootView.findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
tabLayout.setOnTabSelectedListener(this);
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
//This will be called 2nd when you select a tab or swipe using viewpager
final int position = tab.getPosition();
Log.i("card", "Tablayout pos: " + position);
//TabLayout.Tab tabdata=tabLayout.getTabAt(position);
//tabdata.select();
tabLayout.post(new Runnable() {
#Override
public void run() {
if (position == 0) {
PaymentCardFragment paymentCardFragment = getPaymentCardFragment();
if (paymentCardFragment != null) {
VerticalViewpager vp = paymentCardFragment.mypager;
if(vp!=null)
{
//vp.setCurrentItem(position,true);
vp.setCurrentItem(vp.getAdapter().getCount()-1,true);
}
}
}
if (position == 1) {
LoyaltyCardFragment loyaltyCardFragment = getLoyaltyCardFragment();
if (loyaltyCardFragment != null) {
VerticalViewpager vp = loyaltyCardFragment.mypager;
if(vp!=null)
{
vp.setCurrentItem(position);
}
}
}
}
});
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
//This will be called 1st when you select a tab or swipe using viewpager
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
//This will be called only when you select the already selected tab(Ex: selecting 3rd tab again and again)
}
private PaymentCardFragment getLoyaltyCardFragment() {
Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());
if(f instanceof PaymentCardFragment)
{
return (PaymentCardFragment) f;
}
return null;
}
private LoyaltyCardFragment getPaymentCardFragment() {
Fragment f = adapter.mFragmentList.get(viewPager.getCurrentItem());
if(f instanceof LoyaltyCardFragment)
{
return (LoyaltyCardFragment) f;
}
return null;
}
class ViewPagerAdapter extends FragmentPagerAdapter {
public List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
}
}
I am creating a five tabs that contains one fragment each.
I am using ListView in the first tab and in the ListView OnItemClickListener I want to replace from the first Tab Fragment to second tab Fragment.
How can I do that by using Fragment and TabHost?
I extends Fragment for main class and all fragment classes. I am not extends FragmentActivity. So how can I change the tab from one fragment to another fragment?
MainClass:
public class TabsFragment extends Fragment implements OnTabChangeListener {
private View mRoot;
public TabHost mTabHost;
private int mCurrentTab;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRoot = inflater.inflate(R.layout.tabs_fragment, null);
mTabHost = (TabHost) mRoot.findViewById(android.R.id.tabhost);
setupTabs();
return mRoot;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
mTabHost.setOnTabChangedListener(this);
mTabHost.setCurrentTab(mCurrentTab);
// manually start loading stuff in the first tab
updateTab("1");
}
private void setupTabs() {
mTabHost.setup(); // important!
mTabHost.addTab(newTab("1", R.drawable.fragment1, R.id.fragment1));
mTabHost.addTab(newTab("2", R.drawable.fragment2, R.id.fragment2));
mTabHost.addTab(newTab("3", R.drawable.fragment3, R.id.fragment3));
mTabHost.addTab(newTab("4", R.drawable.fragment4, R.id.fragment4));
mTabHost.addTab(newTab("5", R.drawable.fragment5, R.id.fragment5));
}
private TabSpec newTab(String tag, int labelId, int tabContentId) {
Log.d(TAG, "buildTab(): tag=" + tag);
View indicator = LayoutInflater.from(getActivity()).inflate(
R.layout.tab,
(ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
((ImageView) indicator.findViewById(R.id.imageView1)).setImageResource(labelId);
TabSpec tabSpec = mTabHost.newTabSpec(tag);
tabSpec.setIndicator(indicator);
tabSpec.setContent(tabContentId);
return tabSpec;
}
#Override
public void onTabChanged(String tabId) {
updateTab(tabId);
mCurrentTab = Integer.valueOf(tabId) - 1;
}
private void updateTab(String tabId) {
FragmentManager fm = getFragmentManager();
if (fm.findFragmentByTag(tabId) == null) {
if (tabId.equals("1"))
fm.beginTransaction().replace(R.id.fragment1, new Fragment1(), tabId).commit();
else if (tabId.equals("2"))
fm.beginTransaction().replace(R.id.fragment2, new Fragment2(), tabId).commit();
else if (tabId.equals("3"))
fm.beginTransaction().replace(R.id.fragment3, new Fragment3(), tabId).commit();
else if (tabId.equals("4"))
fm.beginTransaction().replace(R.id.fragment4, new Fragment4(), tabId).commit();
else if (tabId.equals("5"))
fm.beginTransaction().replace(R.id.fragment5, new Fragment5(), tabId).commit();
}
}
}
Fragment1:
public class Fragment1 extends Fragment implements OnItemClickListener {
ListView listView;
View theView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
theView = inflater.inflate(R.layout.fragment1, container, false);
listView = (ListView)theView.findViewById(R.id.list);
listView.setOnItemClickListener(this);
return theView;
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
// How can I switch from 1st tab to 2nd tab here???
// Below code is not worked for me.
Fragment2 newFragment = new Fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.map, newFragment);
transaction.commit();
}
}
Fragment2:
public class Fragment2 extends SupportMapFragment {
private LatLng mPosFija = new LatLng(37.878901,-4.779396);
GoogleMap mapView;
public Fragment2() {
super();
}
public static Fragment2 newInstance(LatLng posicion) {
Fragment2 frag = new Fragment2();
frag.mPosFija = posicion;
return frag;
}
#Override
public void onResume() {
super.onResume();
initMap();
}
#Override
public void onCreate(Bundle arg0) {
super.onCreate(arg0);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = super.onCreateView(inflater, container, savedInstanceState);
view = inflater.inflate(R.layout.fragment2, container, false);
view.setId(getId());
SupportMapFragment fm = (SupportMapFragment) getActivity().getSupportFragmentManager().findFragmentById(R.id.mapview);
mapView = fm.getMap();
initMap();
return view;
}
private void initMap() {
UiSettings settings = mapView.getUiSettings();
settings.setAllGesturesEnabled(true);
settings.setMyLocationButtonEnabled(true);
mapView.addMarker(new MarkerOptions().position(mPosFija).icon(BitmapDescriptorFactory.fromResource(R.drawable.icon)));
}
}
Check out my post. This contains all you need with basic.
Dynamically changing the fragments inside a fragment tab host?
NextFragment nextFrag = new NextFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.addToBackStack("next");
//container_framelayout: FrameLayout of Fragment to be replaced
transaction.replace(R.id.container_framelayout, nextFrag);
transaction.commit();