Change Fragment Layout (RTL , LTR) on runtime when changing language - android

i am using a Drawer Navigation activity to handle fragments , and i have an options menu to change Locale like this :
public class DrawerNavigationActivity extends AppCompatActivity implements NavigationView
.OnNavigationItemSelectedListener, AgendaMainFragment.OnFragmentInteractionListener,
MediaMainFragment.OnFragmentInteractionListener, VideosFragment
.OnFragmentInteractionListener, PhotosFragment.OnFragmentInteractionListener,
ThemesMainFragment.OnFragmentInteractionListener, AdresseMainFragment
.OnFragmentInteractionListener, InfoMainFragment.OnFragmentInteractionListener,
NewsMainFragment.OnFragmentInteractionListener, BlockMainFragment
.OnFragmentInteractionListener, DemosMainFragment.OnFragmentInteractionListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_navigation);
setTitle(R.string.app_name);
//########################################################### set initial fragment
Bundle b = getIntent().getExtras();
Fragment fragment = null;
if(b.getInt("link") == 1) {
fragment = new AgendaMainFragment();
}else if(b.getInt("link") == 2){
fragment = new MediaMainFragment();
}else if(b.getInt("link") == 3){
fragment = new ThemesMainFragment();
}else if(b.getInt("link") == 4){
fragment = new AdresseMainFragment();
}else if(b.getInt("link") == 5){
fragment = new InfoMainFragment();
}else if(b.getInt("link") == 6){
fragment = new NewsMainFragment();
}else if(b.getInt("link") == 7){
fragment = new BlockMainFragment();
}else if(b.getInt("link") == 8){
fragment = new DemosMainFragment();
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frag_drawer_container, fragment);
ft.commit();
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.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#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.drawer_navigation, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
switch (id) {
case R.id.fr:
LocaleHelper.setLocale(getBaseContext(), "fr");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.ar:
LocaleHelper.setLocale(getBaseContext(), "ar");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.en:
LocaleHelper.setLocale(getBaseContext(), "en");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
case R.id.es:
LocaleHelper.setLocale(getBaseContext(), "es");
LocaleHelper.updateGlobalConfig(getBaseContext());
ft.detach(getVisibleFragment()).attach(getVisibleFragment()).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
public Fragment getVisibleFragment(){
FragmentManager fragmentManager = DrawerNavigationActivity.this.getSupportFragmentManager();
List<Fragment> fragments = fragmentManager.getFragments();
if(fragments != null){
for(Fragment fragment : fragments){
if(fragment != null && fragment.isVisible())
return fragment;
}
}
return null;
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
Fragment fragment = null;
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
super.onBackPressed();
return true;
} else if(id == R.id.nav_agenda) {
fragment = new AgendaMainFragment();
} else if (id == R.id.nav_gallery) {
fragment = new MediaMainFragment();
} else if (id == R.id.nav_themes) {
fragment = new ThemesMainFragment();
} else if (id == R.id.nav_adresse) {
fragment = new AdresseMainFragment();
}else if (id == R.id.nav_info) {
fragment = new InfoMainFragment();
}else if (id == R.id.nav_news) {
fragment = new NewsMainFragment();
}else if (id == R.id.nav_blocs) {
fragment = new BlockMainFragment();
}else if (id == R.id.nav_demo_animation) {
fragment = new DemosMainFragment();
}else{
return true;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.frag_drawer_container,fragment);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onAgendaFragmentInteraction(Uri uri) {
}
#Override
public void onMediaFragmentInteraction(Uri uri) {
}
#Override
public void onFragmentInteraction(Uri uri) {
}
#Override
public void onFragmentPhotoInteraction(Uri uri) {
}
for my fragments i change the bar action title like this :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_news_main, container, false);
LocaleHelper.updateGlobalConfig(getContext());
getActivity().setTitle(getResources().getString(R.string.fgmt_titre_news));
return view;
}
it's working fin except for an RTL language , when i choose and RTL locale it change the title and the content but keeps the layout orientation LTR , so if i close the application and reopen again it changes the oriontation to RTL but keeps it even for LTR fragments:
by orientation i mean the action bar and the drawer navigation.
Fragment with local Fr :
Change Local to AR (RTL)
close the App and reopen it and navigate to RTL fragment
navigate to another LTR fragment (it keeps RTL Layout Orientation)
what am i doing wrong and what is the best and clean way to achieve it ?

Related

How to implement setDrawerLockMode or disable navigation drawer

I have a navigation drawer activity with fragments within it by using a fragment container. I have three fragments within it and I need one of it named locate_login to not contain my navigation drawer.
MainActivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); //nav drawer
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Set the fragment initially
locate_login fragment = new locate_login();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
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);
}
public void onSelectFragment(View v){ //ignore this
Fragment newFragment;
if(v == findViewById(R.id.trigger)){
newFragment = new locate_after();
}
else{
newFragment = new locate_before();
}
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is my locate_login fragment
public class locate_login extends Fragment{
public locate_login () {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.locate_login, container, false);
// Inflate the layout for this fragment
return rootView;
}
}
I will highly appreciate it if the answer will be detailed since I'm a beginner on Android Studio.
Create a class for some constant parameter. Declare some constant variable like:
Let say StringConstant.java :
public static final int LOCK_DRAWER = 1;
public static final int SHOW_DRAWER = 2;
When navigating from the drawer, use an Intent object as:
If you want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.SHOW_DRAWER);
OR
If you do not want to show the drawer, use:
intent.putExtra("SHOW_DRAWER", StringConstant.LOCK_DRAWER);
Retrieve intent from your fragment class, you say locate_login.
int status = getActivity.getIntent().getIntExtra("SHOW_DRAWER", 0);
Check status:
if (status == String.Constant.LOCK_DRAWER){
lockDrawer();
}
public void lockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
To unlock the drawer:
public void unlockDrawer() {
drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}

How to implement onBackPress from fragment in navigation drawer to MainActivity

I want to implement onBackPress to my fragment but i don't know how. When i go to another fragment (in this case, my fragment is the one from my ActivityHome and i'm using standard NavigationDrawer from android stuudio).
Here is my code for ActivityHome
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
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);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
FragmentHome fragment = new FragmentHome();
fragmentTransaction.add(R.id.containerID, fragment);
fragmentTransaction.commit();
}
#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.activity_home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
Toast.makeText(getApplicationContext(),
"Akun anda telah dikeluarkan!", Toast.LENGTH_LONG).show();
Intent logout = new Intent(ActivityHome.this, ActivityMain.class);
startActivity(logout);
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if(id == R.id.nav_home){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, FragmentHome.newInstance()).commit();
}else if (id == R.id.nav_profile){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, Profile.newInstance()).commit();
}
else if (id == R.id.nav_history){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, History.newInstance()).commit();
}
else if (id == R.id.nav_about_us){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, AboutUs.newInstance()).commit();
}
else if (id == R.id.nav_ganti_kata_sandi){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, GantiKataSandi.newInstance()).commit();
}
else if (id == R.id.nav_share){
ActivityHome.this.getSupportFragmentManager().beginTransaction().replace(R.id.containerID, Share.newInstance()).commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
I hope u guys can help me with my problem.
I have webview in fragment, I used this code to detect backpress code in mainactivity OnbackPressed():
Fragment webview = getSupportFragmentManager().findFragmentByTag("BLOG");
if (webview instanceof BlogFragment) {
boolean goback = ((BlogFragment) webview).canGoBack();
if (!goback) {
} else {
((BlogFragment) webview).goBack();
}
}
Make sure you start fragment like:
getSupportFragmentManager()
.beginTransaction()
.addToBackStack(null)
.replace(R.id.frame_content, new BlogFragment(), "BLOG")
.commit();
To open fragment from activity.
Fragment fragment = Fragment.newInstance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(R.anim.fragment_slide_left_enter,
R.anim.fragment_slide_left_exit, R.anim.fragment_slide_right_enter,
R.anim.fragment_slide_right_exit);
addFragmentToActivity(fragmentTransaction, Fragment, R.id
.content_frame);
public void addFragmentToActivity(#NonNull FragmentTransaction transaction,
#NonNull Fragment fragment, int frameId) {
transaction.addToBackStack(fragment.getClass().getName());
transaction.add(frameId, fragment, fragment.getClass().getName());
transaction.commit();
}
That's how I add fragment from HomeActivity and For back Call override method OnBackPressed in HomeActivity.
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
getSupportFragmentManager().popBackStackImmediate();
}
You can get event when back button pressed from any fragment in Activity's onBackPressed() method.
Suppose you've pressed back from HomeFragment then you can get onBackPressed in Activity like following :
#Override
public void onBackPressed() {
HomeFragment fragment = (Fragment)findFragmentById(// fragment id);
if(fragment!=null && fragment.isVisible()){
// Here you can code for Home Fragment's onBackPress()
}
super.onBackPressed();
}

Other Fragment is viewed above the current fragment changes on rotation with android studio navigation drawer template

Thank you for spending time on my qeustion. In my app I am using android studio navigation drawer template.
But the problem is that, when I rotate the phone, the previous fragment's layout is shown above the current fragment.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Fragment fragment = null;
Class fragmentClass = null;
/* if (savedInstanceState == null){
try{
fragment = (Fragment) fragmentClass.newInstance();
}catch (Exception e){
e.printStackTrace();
}
}*/
fragment = new Login();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
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);
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment =null ;
Class fragmentClas = null;
if (id == R.id.nav_camera) {
// Handle the camera action
fragment = new Attendance();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_gallery) {
fragment = new AddStudent();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
/* FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();*/
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
When you rotate the device, the activity saves its current state and keeps the current fragment then it's destroyed and recreated i.e. onCreate() is called again. You had one fragment before it's destroyed and now it added another in the new call to onCreate() that's why you have 2 fragments. To fix this you should check first if the savedInstanceState parameter in onCreate() is null i.e. it's the first creation of activity not just being restarted due to rotation change or anything, then decide to add the fragment or not instead of adding to whenever the activity calls onCreate()
if(savedInstanceState == null) {
// Add the fragment because it's normal creation
fragment = new Login();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.fragment, fragment);
fragmentTransaction.commit();
}

How to show a text from one fragment in another fragment?

I WAS WORKING BY THE EXAMPLE YOU JUST GAVE ME AS DUPLICATE, READ THE ENTIRE POST, TY
I'm making a simple app with sliding menu by using the template provided by android studio. And I have to use fragments to switch between items of the sliding menu.
What I wanna do? (check app design at the bottom)
When I click on button pass data it should set the text in the Fragment B to the text that I entered in a Fragment A but without going directly to the Fragment B. So when I press the button pass data then I wanna go to the sliding menu and select item that containts fragment B and then I wanna see the text from Fragment A. Thanks in advance.
public class MainActivity extends AppCompatActivity implements FragmentA.DataPassListener {
#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(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
displayFragmentA();
} else if (id == R.id.nav_gallery) {
displayFragmentB();
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
});
}
#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);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void passData(String data) {
FragmentB fragmentB = new FragmentB();
Bundle args = new Bundle();
args.putString("data", data);
fragmentB.setArguments(args);
//getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, fragmentB).commit();
//it works with the commented part but I dont wanna go directly to the fragment when I press pass data button
}
public void displayFragmentA() {
FragmentA frag = new FragmentA();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, frag);
fragmentTransaction.commit();
}
public void displayFragmentB() {
FragmentB frag = new FragmentB();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, frag);
fragmentTransaction.commit();
}
}
Fragment A code:
public class FragmentA extends Fragment {
DataPassListener mCallback;
public interface DataPassListener {
public void passData(String data);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Make sure that container activity implement the callback interface
try {
mCallback = (DataPassListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement DataPassListener");
}
}
public FragmentA() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_a, container, false);
final EditText input = (EditText) view.findViewById(R.id.etInputID);
Button passDataButton = (Button) view.findViewById(R.id.bPassDataID);
passDataButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.passData(input.getText().toString());
}
});
return view;
}
}
Fragment B code:
public class FragmentB extends Fragment {
TextView showReceivedData;
public FragmentB() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_fragment_b, container, false);
showReceivedData = (TextView) view.findViewById(R.id.showReceivedData);
Bundle args = getArguments();
if (args != null) {
showReceivedData.setText(args.getString("data"));
} else {
Toast.makeText(getActivity(), "didnt get the bundle from mainactivity", Toast.LENGTH_LONG).show();
}
return view;
}
}
Design of the app:
If these two fragments use same activity,
to set value to fragment :
getActivity().getIntent().putExtra("key", "value");
To get value from fragment :
getActivity().getIntent().getExtras().getString("key");

Blank page after selecting a default item and pressing back button NavigationView

I am selecting a default fragment in NavigationView when my activity starts up,
it works alright but the problem with it is that when I press the back button, I see a blank view.
My Activity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private final String TAG = "MainActivity";
NavigationView navigationView;
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
String about_blog = "http://example.com/page/json/urls/p-about";
String contri = "http://example.com/page/json/urls/contribute";
String privy = "http://example.com/page/json/urls/privacy-rules";
String contact = "http://example.com/page/json/urls/contact_us";
String advert = "http://example.com/page/json/urls/advertise-here";
String spons = "http://example.com/page/json/urls/sponsor-us";
Fragment fragment = null;
if (id == R.id.menu_home) {
fragment = new PostFragment();
}
if (id == R.id.about_blog) {
fragment = new PageFragment();
} else if (id == R.id.nav_contri) {
fragment = new PageFragment();
} else if (id == R.id.nav_contact) {
fragment = new PageFragment();
} else if (id == R.id.nav_privy) {
fragment = new PageFragment();
} else if (id == R.id.nav_advert) {
fragment = new PageFragment();
} else if (id == R.id.spons) {
fragment = new PageFragment();
} else if (id == R.id.app_about) {
//fragment = new abtFragment();
} else if (id == R.id.settings) {
//fragment = new SettingFragment;
}
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "Device rotated and onCreate called");
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) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
navigationView.setCheckedItem(R.id.menu_home);
navigationView.getMenu().performIdentifierAction(R.id.menu_home, 0);
}
To expatiate, when I launch the app, PostFragment is launched by default. When I click the back key, instead of the app closing, I meet a blank page.
Please, what am I doing wrong here and how do I correct it?
I have found the solution here. Just paste this
FragmentManager fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
#Override public void onBackStackChanged() { if (getSupportFragmentManager().getBackStackEntryCount() == 0) finish(); } });
In the hosting activity's onCreate.
What this does is to finish the activity if the current fragment is the last in the back stack.

Categories

Resources