I don't can change the fragment when i click in navigation item. It happens only in my FragmentTwo. The commit results an error and the app is close. Please, someone can help me? Where is the error?
MAIN CODE
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inicio_admin);
// Implementação do navigation view
DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
toggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
navigationView.setNavigationItemSelectedListener(this);
if(savedInstanceState == null) {
FragmentOne frag1 = new FragmentOne();
FragmentTwo frag2 = new FragmentTwo();
FragmentTransaction ft = fm.beginTransaction();
ft.add(R.id.layoutFundo, frag1, "frag1");
ft.commit();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(toggle.onOptionsItemSelected(item))
return true;
return super.onOptionsItemSelected(item);
}
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentOne frag1 = new FragmentOne();
FragmentTwo frag2 = new FragmentTwo();
FragmentTransaction ft = fm.beginTransaction();
if (item.getItemId() == R.id.nav_menu_1) {
ft.replace(R.id.layoutFundo, frag1, "frag1");
ft.addToBackStack("pilha");
showMessage("IF", "Entrou no if");
Toast.makeText(InicioAdmin.this, "Novo", Toast.LENGTH_SHORT).show();
} else if (item.getItemId() == R.id.nav_menu_2) {
ft.replace(R.id.layoutFundo, frag2, "frag2");
ft.addToBackStack("pilha");
showMessage("ELSEIF", "Entrou no Elseif");
Toast.makeText(InicioAdmin.this, "Outro", Toast.LENGTH_SHORT).show();
} else {
ft.replace(R.id.layoutFundo, frag1, "frag1");
ft.addToBackStack("pilha");
showMessage("ELSE", "Entrou no else");
}
ft.commit();
/* switch (item.getItemId()) {
case R.id.nav_menu_1:
break;
case R.id.nav_menu_2:
break;
default:
break;
}*/
DrawerLayout dl = (DrawerLayout) findViewById(R.id.drawerLayout);
if (dl.isDrawerOpen(GravityCompat.START))
dl.closeDrawer(GravityCompat.START);
return false;
}
// Método showMessage
public void showMessage (String title, String message)
{
AlertDialog.Builder builder=new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
FRAGMENT ONE CODE
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_one, null);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText("Fragmento 1");
return (view);
}
FRAGMENT TWO CODE
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
/*
View view = inflater.inflate(R.layout.fragment_two, null);
TextView tv = (TextView) view.findViewById(R.id.textView1);
tv.setText("Fragmento 2");
*/
return (null);
}
The two classes extends Fragment
I think you are returning null in fragment that's why you are getting error. please add view in fragment and run this. hope it will help.
Related
I have a fragment MyProfile (consists info about a logged user) which I want to be used by fragments Team (consists info about all team members). When I use MyProfile for Team fragment, I need up button. I read documentation guide, tried all from up navigation inside fragment and stopped on this example. The problem is instead of going back to the previous fragment in my case it just opens the options menu.
MainActivity
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
int id = item.getItemId();
if (id == R.id.nav_team) {
fragmentTransaction.replace(R.id.container, new TeamFragment())
.addToBackStack(null)
.commit();
}
TeamFragment
public class TeamFragment extends Fragment {
private String LOG_TAG = getClass().getSimpleName();
private ListView teamList;
private android.support.v4.app.FragmentManager fragmentManager;
public TeamFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).setActionBarTitle("Team");
View rootView = inflater.inflate(R.layout.fragment_announcement, container, false);
final SwipeRefreshLayout swipeToUpdate = rootView.findViewById(R.id.swiperefresh);
teamList = rootView.findViewById(R.id.announcements_list);
getTeamFromAPI(Contract.TEAM);
teamList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageView avatar = view.findViewById(R.id.team_img);
TextView fullname = view.findViewById(R.id.team_fullname);
TextView jobtitle = view.findViewById(R.id.team_jobtitle);
TextView email = view.findViewById(R.id.team_email);
avatar.buildDrawingCache();
Bitmap bitmap = avatar.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bAvatar = baos.toByteArray();
//when team member i replace here current fragment with profile fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = ProfileFragment.newInstance(String.valueOf(fullname.getText()),
String.valueOf(jobtitle.getText()),
String.valueOf(email.getText()), bAvatar);
fragmentTransaction.replace(R.id.container, fragment, "MEMBER_PROFILE")
.addToBackStack(null)
.commit();
}
});
return rootView;
}
private void getTeamFromAPI(String url) {
//fetch team members from database
}
}
Place where I try return back to TeamFragment
ProfileFragment
public class ProfileFragment extends Fragment{
private String LOG_TAG = getClass().getSimpleName();
private String mFullname;
private String mTitle;
private String mEmail;
private byte[] mAvatar;
private android.support.v4.app.FragmentManager fragmentManager;
private ActionBar actionBar;
private View rootView;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String name, String title, String email, byte[] avatar) {
Bundle bundle = new Bundle();
bundle.putString("fullname", name);
bundle.putString("title", title);
bundle.putString("email",email);
bundle.putByteArray("avatar", avatar);
ProfileFragment fragment = new ProfileFragment();
fragment.setArguments(bundle);
return fragment;
}
private void readBundle(Bundle bundle) {
if (bundle != null) {
this.mFullname = bundle.getString("fullname");
this.mTitle = bundle.getString("title");
this.mEmail = bundle.getString("email");
this.mAvatar = bundle.getByteArray("avatar");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
// Sets "up navigation" for both phone/tablet configurations
actionBar = ((MainActivity)getActivity()).getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_announcement, container, false);
ListView listView = rootView.findViewById(R.id.announcements_list);
SwipeRefreshLayout swipe = rootView.findViewById(R.id.swiperefresh);
swipe.setEnabled(false);
readBundle(getArguments());
ArrayList<ProfileObject> list = new ArrayList<>();
list.add(new ProfileObject(mFullname, mTitle,mEmail,mAvatar));
ProfileAdapter adapter = new ProfileAdapter(getContext(), list);
listView.setAdapter(adapter);
return rootView;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.e(LOG_TAG+"/onOptionsItemSelected","Pressed: "+item.getItemId());
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProfileFragment member_profile = (ProfileFragment)fragmentManager.findFragmentByTag("MEMBER_PROFILE");
fragmentTransaction.remove(member_profile).commit();
fragmentManager.popBackStack();
actionBar.setDisplayHomeAsUpEnabled(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
But as I already said it only the opens options menu. Did I make a somewhere conceptual mistake?
UPDATE: Problem inside onOptionsItemSelected. If add
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.e(LOG_TAG+"/onOptionsItemSelected","Pressed: "+item.getItemId());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
and click on back arrow nothing will be in Logcat.
As per your code you have handled onOptionsItemSelected() for R.id.home but I see you are using ActionBar back button which is provided by Android UI itself
actionBar = ((MainActivity)getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
In this case Home Button is referenced as android.R.id.home and NOT R.id.home
This is the reason you are not getting any update in Logcat too (as you mentioned in comments).
Update your switch case as below and replace R.id.home with android.R.id.home
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: // <- Update this
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProfileFragment member_profile = (ProfileFragment)fragmentManager.findFragmentByTag("MEMBER_PROFILE");
fragmentTransaction.remove(member_profile).commit();
fragmentManager.popBackStack();
actionBar.setDisplayHomeAsUpEnabled(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
The Main Activity having bottom navigation and contains 5 fragments in it. Each fragments having multiple fragment inside. how to handle the onbackpressed in it.
Homepage.java
public class Homepage extends AppCompatActivity {
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
= new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.home:
selectedFragment = Fragment_home.newInstance();
break;
case R.id.eventsfeed:
selectedFragment = Fragment_eventsfeed.newInstance();
break;
case R.id.events:
selectedFragment = Fragment_events.newInstance();
break;
case R.id.messages:
selectedFragment = Fragment_messages.newInstance();
break;
case R.id.settings:
selectedFragment = Fragment_settings.newInstance();
break;
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.content, selectedFragment);
transaction.commit();
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.homepage);
Fragment fragmentnewview = new Fragment_home();
FragmentManager frMan = getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
BottomNavigationViewHelper.disableShiftMode(navigation);
}}
Fragment_home.java
public class Fragment_home extends Fragment {
public static Fragment_home newInstance(){
Fragment_home fragment=new Fragment_home();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.fragment_home, container, false);
CardView card=(CardView)view.findViewById(R.id.next_page_home_card);
card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Event_details();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
Inside that Fragment_home.java i have a card view when it clicked it goes to next fragment Event_Details.java
Event_Details.java
public class Event_details extends Fragment {
Button add_comments;
ImageButton back;
public static Event_details newInstance(){
Event_details fragment=new Event_details();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.event_details, container, false);
add_comments=(Button)view.findViewById(R.id.add_comment);
back=(ImageButton)view.findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Fragment_home();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
add_comments.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Comments();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
i have a button in Event_Details.java when clicked that it calls another fragment Comments.java
Comments.java
public class Comments extends Fragment {
ImageButton back;
public static Comments newInstance(){
Comments fragment=new Comments();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view=inflater.inflate(R.layout.add_your_comments, container, false);
back=(ImageButton)view.findViewById(R.id.back);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.setVisibility(View.GONE);
Fragment fragmentnewview = new Event_details();
FragmentManager frMan = getActivity().getSupportFragmentManager();
FragmentTransaction frTr = frMan.beginTransaction();
frTr.add(R.id.content,fragmentnewview);
frTr.commit();
}
});
return view;
}
}
back.setOnClickListener is the image button to go back but i can't implement in the hardware back button.
You need to #Override your activity onBackPressed() method !!!
There are many good information and answers about your question ! if you want to become good programmer you need good research skills!!! :))
Try to research and solve the problem yourself . Write some code, and after all of it if you still can't resolve your problem i'll give you code for copy and paste :)
When you load a fragment, use addToBackStack(null) on the FragmentTransaction. If you do that, the back button will reverse the transaction.
#Override onBackPressed()
method as #L.Petrosyan told,
insideonBackPressed()get the current position of your viewpager usingviewPager.getCurrentItem();
it will return you anint` value. use that value to manage your code.
i have used navigation drawable from android studio 2.2.3 with fragments as frag1,frag2
I want to send selected spinner values to all fragments,
i have managed to send first selected spinner item to all fragments using bundle but when i select the second item from spinner item list
nothing work,here is my codes
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
String data1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//add this line to display menu1 when the activity is loaded
displaySelectedScreen(R.id.nav_menu1);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
ArrayList<String> list = new ArrayList<String>();
list.add("Top News");
list.add("Politics");
list.add("Business");
list.add("Sports");
list.add("Movies");
MenuItem item = menu.findItem(R.id.spinner);
Spinner spinner = (Spinner) MenuItemCompat.getActionView(item);
spinner.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, list));
data1=spinner.getSelectedItem().toString();
Toast.makeText(MainActivity.this, spinner.getSelectedItem().toString(),Toast.LENGTH_LONG).show();
return true;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
displaySelectedScreen(item.getItemId());
return true;
}
private void displaySelectedScreen(int itemId) {
//creating fragment object
Fragment fragment = null;
switch (itemId) {
case R.id.nav_menu1:
fragment = new frag1();
break;
case R.id.nav_menu2:
fragment = new frag2();
Bundle data2 = new Bundle();
data2.putString("data", data1);
fragment.setArguments(data2);
break;
case R.id.nav_menu3:
fragment = new frag3();
Bundle data = new Bundle();
data.putString("data", data1);
fragment.setArguments(data);
break;
}
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
}
}
public class frag2 extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu_3, container, false);
TextView text = (TextView) view.findViewById(R.id.textView3);
String getArgument = getArguments().getString("data");
text.setText(getArgument);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getActivity().setTitle("Menu 1");
}
}
So where and how can i modify or my codes so that
1.i can send the selected spinner item to all fragments ?
2.i can retain the state of selected spinner value when navigate between fragments ?
Use onItemSelected listener and perform operation you want to perform there
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Here
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
i need to start a fragment from another fragment.
i have my MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff) ;
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new TabFragment()).commit();
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
//Selecao dos menus
if (menuItem.getItemId() == R.id.nav_reservas) {
FragmentTransaction fragmentTransaction = mFragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.containerView, new Reservas()).commit();
} else if (menuItem.getItemId() == R.id.nav_hotel) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
} else if (menuItem.getItemId() == R.id.nav_check) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new CheckIn()).commit();
} else if (menuItem.getItemId() == R.id.nav_loc) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Endereco()).commit();
} else if (menuItem.getItemId() == R.id.nav_avalie) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Avalie()).commit();
} else if (menuItem.getItemId() == R.id.nav_info) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new Informacoes()).commit();
} else if (menuItem.getItemId() == R.id.nav_guia) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new GuiaDaCidade()).commit();
}
return false;
}
}
);
and i start the GuiaDaCidade extends fragment.
public class GuiaDaCidade extends Fragment {
View rootView;
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.guia_da_cidade, null);
View botaoPasseios = (View) rootView.findViewById(R.id.btpasseios);
View botaoAgenda = (View) rootView.findViewById(R.id.btagenda);
botaoPasseios.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
I need that when the button is clicked start the Passeios extends Fragment
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.guia_passeios, null);
expListView = (ExpandableListView) rootView.findViewById(R.id.listaexp);
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
expandeAll();
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
mudaTela(groupPosition, childPosition);
return false;
}
});
return rootView;
}
I already tried everything possible but no way is working.
before you start another fragment, if you want to keep your current fragment into backstack so that it is available when user presses back button, add it to back stack using fragment manager. Then just use the same line: fragmentTransaction.replace(containerView,new Fragment(), TAG).commit();
GuiaDaCidade
botaoPasseios.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Passeios fragment = new Passeios();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.your_guiadacidade_layoutID, fragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
As mentioned in my previous question I had some problem with showing Fragments inside a ViewPager after opening another Fragment from one of the Fragments inside the ViewPager.
I somehow managed to resolve the problem by using add() in the FragmentTransaction. Unfortunately this creates another problem:
I am using the ActionBar in my app. When I am selecting the same menu item twice I encounter the same problem as before, it doesn't show any Fragments inside the ViewPager.
Home Activity Code(where action bar on click events are call)
public class HomePageActivity extends SherlockFragmentActivity implements ICallback {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private SherlockActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mChampionsMenuItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.Theme_Sherlock);
setContentView(R.layout.activity_home_page);
mTitle = mDrawerTitle = getTitle();
mChampionsMenuItems = getResources().getStringArray(R.array.champions_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerList.setAdapter(new ArrayAdapter<String>(this, R.layout.drawer_list_item, mChampionsMenuItems));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.color.navy_blue));
getSupportActionBar().setDisplayShowTitleEnabled(false);
mDrawerToggle = new SherlockActionBarDrawerToggle(this, mDrawerLayout, R.drawable.menu_icon, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
onFragmentChange(new HomeActivityFragment(), true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
default: return super.onOptionsItemSelected(item);
}
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
switch (position) {
case 0:
onFragmentChange(new Fragment1(), false);
break;
case 1:
onFragmentChange(new Fragment2(), false);
break;
case 2:
onFragmentChange(new MyPointFragment3(), false);
break;
case 3:
// onFragmentChange(new HomeActivityFragment(), true);
break;
case 4:
onFragmentChange(new QueriesFragment(), false);
break;
case 5:
onFragmentChange(new GalleryFragment(), false);
break;
default:
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onFragmentChange(Fragment fragment, boolean flag) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.content_frame, fragment, fragment.getClass().getName());
transaction.commit();
}
}
This is the Fragment which contains the ViewPager:
public class Fragment1 extends Fragment implements OnClickListener {
ICallback callback;
private LinearLayout headerContainer;
private ImageView headerLogo;
private TextView headerName;
private Button menuBarButton;
MyAdapter adapter;
ViewPager pager;
ActionBar actionBar;
private Button progOverview, progStr, bonusPoint;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof ICallback) {
this.callback = (ICallback) activity;
}
actionBar = activity.getActionBar();
actionBar.show();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = setUpView(inflater, container);
return rootView;
}
private View setUpView(LayoutInflater inflater, ViewGroup container) {
View rootView = inflater.inflate(R.layout.fragment_about_champions_club, container, false);
headerContainer = (LinearLayout) rootView.findViewById(R.id.second_top_header);
headerContainer.setBackgroundColor(getResources().getColor(R.color.prog_str_blue));
headerLogo = (ImageView) rootView.findViewById(R.id.header_logo);
headerLogo.setBackgroundResource(R.drawable.about_champions_ticon);
headerName = (TextView) rootView.findViewById(R.id.header_name);
headerName.setText(R.string.about_champ_title);
adapter = new MyAdapter(getFragmentManager());
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
}
}
}
}
This is one of the Fragments inside the ViewPager:
public class ProgramOverViewFragment extends Fragment {
ICallback callback;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof ICallback) {
this.callback = (ICallback) activity;
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_program_overview, container, false);
TextView termsAndCond = (TextView) rootView.findViewById(R.id.terms_and_condition_button);
termsAndCond.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
fragment.setRetainInstance(true);
transaction.addToBackStack(null);
transaction.commit();
}
});
return rootView;
}
}
My FragmentStatePagerAdapter:
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int index) {
switch (index) {
case 0: return new ProgramOverViewFragment();
case 1: return new ProgramStructureFragment();
case 2: return new BonusPointFragment();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Thanks for your help!
What do you want to do exactly? Are you trying to replace a Fragment inside the ViewPager? Or are you trying to replace a Fragment inside a Fragment inside the ViewPager? Or are you trying to do something different altogether? I can only give you an accurate solution if you explain what you are trying to do in detail. Anyway here is what I am guessing might be wrong:
I think your problem is that you use the wrong FragmentManager. There are multiple different FragmentManagers, but essentially there are two cases:
You want to add/replace/remove a Fragment from an Activity
You want to add/replace/remove a Fragment from another Fragment
As long as I don't see your layout files I can't be sure which of those two options fits your situation.
Solution if you want to replace a Fragment inside of another Fragment
If you want to perform a FragmentTransaction on a Fragment inside of another Fragment, then you need to use the child FragmentManager! You can use the child FragmentManager inside a Fragment like this:
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
fragment.setRetainInstance(true);
transaction.addToBackStack(null);
transaction.commit();
As you can see you just need to use getChildFragmentManager() instead of getSupportFragmentManager()
As I already said, without any further information about your situation I cannot give you a more accurate answer. So please try to explain what you want to do as best as you can to me and I'm confident we can solve this.
Finally i found what i did wrong in my code :
i'm using this below code for setting adapter for view Pager inside a fragment :
adapter = new MyAdapter(getFragmentManager());
pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(adapter);
and by replacing getFragmentManager() to getChildFragmentManager() we resolve this problem. As per my understanding i'm using view pager inside a fragment that's why i have to use getChildFragment manager to store transitions of my viewPager.
Might this help someone and this question is still open for better solutions.