How to go back to the previous fragment properly? - android

I'm trying to handle the back button in a fragment. I want it to go back to the fragment it came from, but the #Override I've doesn't override from its superclass, but I don't why. Futhermore the method onBackPressed() is never used. I think it's weird as it works in my activities.
public class RateFrag extends Fragment implements View.OnClickListener {
private RatingBar ratingBar;
private Button rateknap;
private Forslag forslag;
#Override
public View onCreateView(LayoutInflater i, ViewGroup container, Bundle savedInstanceState) {
View rod = i.inflate(R.layout.activity_rate, container, false);
setHasOptionsMenu(true);
forslag = ((AnnonceDisplay) this.getActivity()).getForslag();
getActivity().setTitle(forslag.getTitle());
ratingBar = (RatingBar) rod.findViewById(R.id.ratingBar);
rateknap = (Button) rod.findViewById(R.id.rateknap);
rateknap.setOnClickListener(this);
return rod;
}
#Override
public void onClick(View v) {
if (v == rateknap) {
AlertDialog alert = new AlertDialog.Builder(getActivity())
.setMessage("Vil du give " + ratingBar.getRating() + " stjerner?")
.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
launchintent();
}
}
)
.setNegativeButton("Nej", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}
).show();
}
}
private void launchintent() {
FragmentManager fm = getFragmentManager();
Fragment f = fm.findFragmentById(R.id.fragment);
if(fm.getBackStackEntryCount() > 0){
fm.popBackStack();
} else{
getActivity().finish();
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_main, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Forside) {
Intent intent = new Intent(this.getActivity(), Forside.class);
startActivity(intent);
}
else if (id == R.id.Logud){
Intent intent = new Intent(this.getActivity(), LogInd.class);
startActivity(intent);
}
return true;
}
#Override //Method does not override method from its superclass
public void onBackPressed() { //Method onBackPressed is never used
if (getFragmentManager().getBackStackEntryCount() == 0) {
getActivity().finish();
} else {
getFragmentManager().popBackStack();
}
return;
}
}
Before anyone says it's a possible duplicate, I've searched here on Stackoverflow and Google. I actually got this Override from here, so please tell me what is wrong, and how I fix it.
Thanks :)

Override the onBackPress on your Activity like this
#Override
public void onBackPressed() {
int count = getFragmentManager().getBackStackEntryCount();
if (count == 0) {
super.onBackPressed();
} else {
getFragmentManager().popBackStack();
}
}

Related

How to restore fragment states while using bottom navigation view in android?

I am trying to do restoring the fragment view state values(text view,..etc) when back from second fragment in android bottom navigation view.
MyActivity.java
public class LandingPage extends AppCompatActivity implements ProductFragment.AddToCart {
Fragment fragment;
TextView txtCart;
Button btnCart;
ItemData itemData;
ArrayList<ItemData> itemDataList;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
fragment = new ProductFragment();
loadFragment(fragment);
return true;
case R.id.nav_profile:
fragment = new ReportsFragment();
loadFragment(fragment);
return true;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_landing_page);
txtCart = findViewById(R.id.txt_cart);
btnCart = findViewById(R.id.btn_cartImg);
itemDataList = new ArrayList<>();
BottomNavigationView bottomNavigationView = findViewById(R.id.navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
loadFragment(new ProductFragment());
}
private void loadFragment(Fragment fragment) {
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, fragment);
transaction.commit();
}
}
ProductFragment.java
public class ProductFragment extends Fragment {
private OnFragmentInteractionListener mListener;
Button btnCart1,btnCart2,btnCart3;
AddToCart addToCart;
TextView txtItem1Des,txtItem1Price,txtItem2Des,txtItem2Price,txtItem3Des,txtItem3Price;
Button btnCart1Inc,btnCart1Dec,btnCart2Inc,btnCart2Dec,btnCart3Inc,btnCart3Dec;
TextView cart1txt,cart2txt,cart3txt;
String itemDes,itemPrice,itemImg,itemCount;
int quantity1,quantity2,quantity3;
public ProductFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_product, container, false);
btnCart1 = view.findViewById(R.id.cart1);
txtItem1Des = view.findViewById(R.id.cart1_desc);
txtItem1Price = view.findViewById(R.id.cart1_price);
btnCart1Inc = view.findViewById(R.id.cart1Inc);
btnCart1Dec = view.findViewById(R.id.cart1Dec);
cart1txt = view.findViewById(R.id.cart1txt);
btnCart2 = view.findViewById(R.id.cart2);
txtItem2Des = view.findViewById(R.id.cart2_desc);
txtItem2Price = view.findViewById(R.id.cart2_price);
btnCart2Inc = view.findViewById(R.id.cart2Inc);
btnCart2Dec = view.findViewById(R.id.cart2Dec);
cart2txt = view.findViewById(R.id.cart2txt);
btnCart3 = view.findViewById(R.id.cart3);
txtItem3Des = view.findViewById(R.id.cart3_desc);
txtItem3Price = view.findViewById(R.id.cart3_price);
btnCart3Inc = view.findViewById(R.id.cart3Inc);
btnCart3Dec = view.findViewById(R.id.cart3Dec);
cart3txt = view.findViewById(R.id.cart3txt);
quantity1 = Integer.parseInt(cart1txt.getText().toString());
quantity2 = Integer.parseInt(cart2txt.getText().toString());
quantity3 = Integer.parseInt(cart3txt.getText().toString());
buttonInitialization();
addingToCart();
return view;
}
private void addingToCart() {
btnCart1Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity1 <= 1){
btnCart1.setVisibility(View.VISIBLE);
btnCart1Dec.setVisibility(View.INVISIBLE);
btnCart1Inc.setVisibility(View.INVISIBLE);
cart1txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(1);
}else {
quantity1 = quantity1-1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
}
});
btnCart1Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity1 = quantity1+1;
cart1txt.setText(String.valueOf(quantity1));
addToCart.itemCount(cart1txt.getText().toString(),"1");
}
});
btnCart2Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity2 <= 1){
btnCart2.setVisibility(View.VISIBLE);
btnCart2Dec.setVisibility(View.INVISIBLE);
btnCart2Inc.setVisibility(View.INVISIBLE);
cart2txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(2);
}else {
quantity2 = quantity2-1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
}
});
btnCart2Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity2 = quantity2+1;
cart2txt.setText(String.valueOf(quantity2));
addToCart.itemCount(cart2txt.getText().toString(),"2");
}
});
btnCart3Dec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quantity3 <= 1){
btnCart3.setVisibility(View.VISIBLE);
btnCart3Dec.setVisibility(View.INVISIBLE);
btnCart3Inc.setVisibility(View.INVISIBLE);
cart3txt.setVisibility(View.INVISIBLE);
addToCart.removeItemFromCart(3);
}else {
quantity3 = quantity3-1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
}
});
btnCart3Inc.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
quantity3 = quantity3+1;
cart3txt.setText(String.valueOf(quantity3));
addToCart.itemCount(cart3txt.getText().toString(),"3");
}
});
}
private void buttonInitialization() {
btnCart1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem1Price.getText().toString().trim();
itemDes = txtItem1Des.getText().toString().trim();
itemCount = cart1txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"1");
btnCart1.setVisibility(View.INVISIBLE);
btnCart1Dec.setVisibility(View.VISIBLE);
btnCart1Inc.setVisibility(View.VISIBLE);
cart1txt.setVisibility(View.VISIBLE);
}
});
btnCart2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem2Price.getText().toString().trim();
itemDes = txtItem2Des.getText().toString().trim();
itemCount = cart2txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"2");
btnCart2.setVisibility(View.INVISIBLE);
btnCart2Dec.setVisibility(View.VISIBLE);
btnCart2Inc.setVisibility(View.VISIBLE);
cart2txt.setVisibility(View.VISIBLE);
}
});
btnCart3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
itemImg = "";
itemPrice = txtItem3Price.getText().toString().trim();
itemDes = txtItem3Des.getText().toString().trim();
itemCount = cart3txt.getText().toString().trim();
addToCart.cartCount("",itemPrice,itemDes,itemCount,"3");
btnCart3.setVisibility(View.INVISIBLE);
btnCart3Dec.setVisibility(View.VISIBLE);
btnCart3Inc.setVisibility(View.VISIBLE);
cart3txt.setVisibility(View.VISIBLE);
}
});
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
addToCart = (AddToCart) context;
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
public interface AddToCart{
void cartCount(String item_img,String item_price,String item_desc,String item_count,String item_pos);
void removeItemFromCart(int removeItem);
void itemCount(String itemCount,String position);
}
}
Here in ProductFragment iam going to add values to text view. When i was coming from ReportFragment the view values are going to be cleared in ProductFragment.
I would consider doing that in two steps:
save fragment instance instead of re-creating a new one every time
private ProductFragment productFragment;
private ReportsFragment reportsFragment;
private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_home:
if(productFragment == null)
productFragment = new ProductFragment();
loadFragment(productFragment);
break;
case R.id.nav_profile:
if(reportsFragment == null)
reportsFragment = new ReportsFragment();
loadFragment(reportsFragment);
break;
case R.id.nav_logout:
LogOut();
return true;
}
return true;
}
};
referring to this question/answer, you should implement in your fragment both void onSaveInstanceState(final Bundle outState) and void onActivityCreated(Bundle savedInstanceState)
In that way you will surely keep the instance of your fragment instead of creating a new one every time (new MyFragment() will always re-create it). In addition, saving your views state in onSaveInstanceState and restoring it in your onActivityCreate, will allow you to keep your views/values.
I wrote that by hand without a compiler, so it might not be perfect.
let me know if you need further information.
Good luck
I am using this solution and it works for me.
You should see my detailed answer to a similar question. I hope it will solve your problem.

How to open link in a fragment with webview when a specific item is clicked from listview fragment

I have an Android app with a navigation drawer with menu items.This menu contains entry to multiple fragments. One of the fragments has a listview in it with names of websites. My aim is that whenever a name of website is clicked from that list the link associated with the listview item saved in stringarray in strings.xml file is opened in new fragment with webview which opens the site.
So far I have implemented this code for the fragment with listview
class AtlasListFragment extends android.support.v4.app.ListFragment implements AdapterView.OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.atlas_list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tut_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}}
And the code which launches the fragment from navigation drawer is below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.Fragment fragment = null;
if (id == R.id.home) {
fragment = frag;
else if (id == R.id.settings) {
fragment=new Settings();
} else if (id == R.id.about_us) {
fragment=new AboutUc();
}
else if(id == R.id.atlas){
fragment = new AtlasListFragment();
}
else{
}
if (fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.fragmentview,fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
By this mehod you can open a webview in where you want use WebView layout and use this method in your activity
public void openWebView(String url){
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Hope it works for you
First of all you will need broadcast so you can send your clicked
URL from adapter to your fragment, and in your main fragment when you
receive the url you can use intent or webview
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.hossam";
private static final String UPDATE_LOCATION_METHOD = "updateLocation";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
String url_adapter = arg1.getStringExtra("url_adapter");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url_adapter));
startActivity(i);
break;
default:
break;
}
}
}
}
i hope this helped

Converting Activity to a fragment gives onCreateOptionsMenu error

I was converting my UserListing Activity to a fragment when i received this error in myOnCreateOptionsMenu.
This is my Fragment Activity.
public class UserListingActivity extends Fragment implements LogoutContract.View {
private Toolbar mToolbar;
private TabLayout mTabLayoutUserListing;
private ViewPager mViewPagerUserListing;
private LogoutPresenter mLogoutPresenter;
public static void startActivity(Context context) {
Intent intent = new Intent(context, UserListingActivity.class);
context.startActivity(intent);
}
public static void startActivity(Context context, int flags) {
Intent intent = new Intent(context, UserListingActivity.class);
intent.setFlags(flags);
context.startActivity(intent);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
bindViews();
init();
setHasOptionsMenu(true);
return super.onCreateView(inflater, container, savedInstanceState);
}
// #Override
// protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_user_listing);
// bindViews();
// init();
// }
private void bindViews() {
mToolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
mTabLayoutUserListing = (TabLayout) getActivity().findViewById(R.id.tab_layout_user_listing);
mViewPagerUserListing = (ViewPager) getActivity().findViewById(R.id.view_pager_user_listing);
}
private void init() {
// set the toolbar
setSupportActionBar(mToolbar);
// set the view pager adapter
UserListingPagerAdapter userListingPagerAdapter = new UserListingPagerAdapter(getFragmentManager());
mViewPagerUserListing.setAdapter(userListingPagerAdapter);
// attach tab layout with view pager
mTabLayoutUserListing.setupWithViewPager(mViewPagerUserListing);
mLogoutPresenter = new LogoutPresenter(this);
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getActivity().getMenuInflater().inflate(R.menu.menu_user_listing, menu);
// return super.onCreateOptionsMenu(menu);
// }
#Override
public boolean onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
getActivity().getMenuInflater().inflate(R.menu.menu_user_listing, menu);
return super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
logout();
break;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
new AlertDialog.Builder(this)
.setTitle(R.string.logout)
.setMessage(R.string.are_you_sure)
.setPositiveButton(R.string.logout, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
mLogoutPresenter.logout();
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
#Override
public void onLogoutSuccess(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
LoginActivity.startIntent(this,
Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
}
#Override
public void onLogoutFailure(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(this, MainActivity.class));
}
}
What has to be changed to solve this and what more has to be changed to covert it into a Fragment. I am beginner so detailed help would be appreciated.
Thanks
Method signature in fragment should be as below
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
The problem is with the return type of the method, make it void and error will be gone as the super-type returns void.

Android Application - Get last fragment for each activity if already loaded

I actually have an aplication with multiple activitys (on for each icon of my toolbar), also I would like to have the possibility to show the last fragment of these activitys from the stack if the user already open it before.
As you can see in my BaseActivity class below (which I extend for all my activitys), I already add fragments to the stack.
This is my class :
public class BaseActivity extends AppCompatActivity {
private final String TAG = "BaseActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_base);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public void setImageLoaderConfig(Context context) {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true)
.resetViewBeforeLoading(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.defaultDisplayImageOptions(defaultOptions)
.build();
ImageLoader.getInstance().init(config);
}
public void initToolBar() {
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.toolbar_layout);
Toolbar toolbar = (Toolbar) linearLayout.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (toolbar != null) {
initToolbarOnClickListener();
}
}
private void initToolbarOnClickListener() {
(findViewById(R.id.toolbar_relativelayout_news)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ArticlesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_toilettes)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ToilettesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_practice)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(PratiquesActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_diary)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(AgendaActivity.class);
}
});
(findViewById(R.id.toolbar_relativelayout_forum)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showActivity(ForumActivity.class);
}
});
}
public void updateToolbarIcons(Integer position) {
ImageView imageViewIcon;
Integer[] activeDrawableIds = {R.drawable.menu_actu_hover_320, R.drawable.menu_toilette_hover_320,
R.drawable.menu_pratiques_hover_320, R.drawable.menu_agenda_hover_320, R.drawable.menu_forum_hover_320};
Integer[] inactiveDrawableIds = {R.drawable.menu_actu_160, R.drawable.menu_toilette_320,
R.drawable.menu_pratiques_320, R.drawable.menu_agenda_320, R.drawable.menu_forum_320};
Integer[] imageviewIds = {R.id.toolbar_imageview_news, R.id.toolbar_imageview_bathroom,
R.id.toolbar_imageview_practice, R.id.toolbar_imageview_diary, R.id.toolbar_imageview_forum};
for (int i = 0; i < imageviewIds.length; i++) {
Log.d(TAG, i + " " + imageviewIds[i]);
imageViewIcon = (ImageView) findViewById(imageviewIds[i]);
if (i == position) {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), activeDrawableIds[i]));
} else {
imageViewIcon.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), inactiveDrawableIds[i]));
}
}
if (AfamiciApp.isConnected()) {
ImageView imageViewUser = (ImageView) findViewById(R.id.toolbar_imageview_user);
imageViewUser.setVisibility(View.VISIBLE);
}
}
public void showActivity(Class activityClass) {
Intent intent = new Intent(this, activityClass);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
public void initIsConnected() {
if (AfamiciApp.getMail() != null && AfamiciApp.getPassword() != null) {
AfamiciApp.setIsConnected(true);
}
}
public void showConnexionFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
args.putInt("containerId", layoutId);
ConnexionFragment connexionFragment = new ConnexionFragment();
connexionFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, connexionFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCommentaireFragment(Integer layoutId, Integer id, Boolean isFromConnection) {
if (isFromConnection) {
getSupportFragmentManager().popBackStack();
}
Bundle args = new Bundle();
args.putInt("id", id);
CommentaireFragment commentaireFragment = new CommentaireFragment();
commentaireFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, commentaireFragment, null)
.addToBackStack(null)
.commit();
}
public void showCreationCompteFragment(Integer layoutId, Integer id) {
Bundle args = new Bundle();
args.putInt("id", id);
CreationCompteFragment creationCompteFragment = new CreationCompteFragment();
creationCompteFragment.setArguments(args);
getSupportFragmentManager()
.beginTransaction()
.replace(layoutId, creationCompteFragment, null)
.addToBackStack(null)
.commit();
}
}
Thanks in advance for your replys :)
You can get current fragment(last one added) in the FrameLayout using:
Fragment fragment = getSupportFragmentManager().findFragmentById(layoutId); //layoutId is id of FrameLayout

Exit App on Back Button Press not working

I would like my application to quit if the user presses back at a certain activity. The following is the code for that activity.
public class MainActivity extends FragmentActivity implements DenkoListFragment.ListSelectListener {
private SlidingMenu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayView(0);
menu = new SlidingMenu(this);
menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
menu.setShadowWidthRes(R.dimen.shadow_width);
menu.setShadowDrawable(R.drawable.shadow);
menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
menu.setFadeDegree(0.35f);
menu.attachToActivity(this, SlidingMenu.SLIDING_CONTENT);
menu.setMenu(R.layout.menu_frame);
menu.setSelected(true);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.menu_frame, new DenkoListFragment())
.commit();
}
private void displayView(int position) {
Fragment fragment = null;
switch (position) {
case 0:
fragment = new MainViewFragment();
break;
case 1:
fragment = new StationViewFragment();
break;
case 2:
fragment = new MapViewFragment();
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
} else {
}
}
#Override
public void select(int index) {
displayView(index);
menu.showContent();
}
#Override
public void onBackPressed() {
if (menu.isMenuShowing()) {
menu.showContent();
} else {
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
System.exit(0);
}
}).setNegativeButton("No", null).show();
}
}
}
It takes the app two back presses (and two confirmations) to exit. What explains this behaviour and is there any way to resolve this?
Remove below snippet from onBackPress() Method. It will handle by SlideMenu only.
if (menu.isMenuShowing()) {
menu.showContent();
}
Code from SlidingFragmentActivity call onBackPress:
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
boolean b = mHelper.onKeyUp(keyCode, event);
if (b) return b;
return super.onKeyUp(keyCode, event);
}
mHelper.onKeyUp(keyCode, event) will call a Method of SlidingActivityHelper:
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && mSlidingMenu.isMenuShowing()) {
showContent(); //Close the SlidingMenu and show the content view.
return true;
}
return false;
}
super.onBackPressed(); will do what ever you want,just include super.onBackPressed(); instead of System.exit(0);,because it will call the onBackpressed method of Activity.So,onDestroy method get call properly.
new AlertDialog.Builder(this).setIcon(android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
super.onBackPressed();
}
}).setNegativeButton("No", null).show();

Categories

Resources