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.
Related
I am trying to implement tab functionality in an Android browser. I tried to save the webpage in a cache, but I can't figure out how to save multiple of them and load them when the user switches tabs. How could I implement this?
I would like to save the current webpage in a cache when the user wants to add a new tab and open Main_activity, and then next time when the user switches tabs, the current webpage should get saved in a cache, and the intended webpage of the intended tab gets loaded in the webview. Now the issue is, I don't know how to handle multiple webpages in a cache, and select which one to load when.
My code consists of two activities, main_activity with some icons and webView_activity with a simple webview. I am using a custom dialog box with a ListView in it, so I will need to add new rows for new tabs and edit them when tabs are switched.
Here is my main_activity
public class MainActivity extends AppCompatActivity {
ImageView yt,google,gm,twitter;
SearchView g_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
g_search = (SearchView) findViewById(R.id.g_search);
g_search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
yt = (ImageView) findViewById(R.id.yt);
google = (ImageView) findViewById(R.id.google);
gm = (ImageView) findViewById(R.id.gm);
twitter = (ImageView) findViewById(R.id.twitter);
yt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.youtube.com");
startActivity(i);
}
});
google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.google.com");
startActivity(i);
}
});
gm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.gmail.com");
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.twitter.com");
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m1, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_new_tab){
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(MainActivity.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Here is my web_view activity
public class webview1 extends AppCompatActivity {
CustomWebView web1;
String search_q,shortcut;
FloatingActionButton fab;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview1);
web1 = (CustomWebView) findViewById(R.id.web1);
web1.setGestureDetector(new GestureDetector(new CustomGestureDetector()));
web1.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(final WebView view, int errorCode, String description,
final String failingUrl) {
fragmentManager.beginTransaction()
.replace(R.id.container, new blankState())
.commit();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
registerForContextMenu(web1);
// web1.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setBuiltInZoomControls(true);
web1.getSettings().setDisplayZoomControls(false);
web1.getSettings().setLoadWithOverviewMode(true);
web1.getSettings().setUseWideViewPort(true);
search_q=getIntent().getStringExtra("query");
shortcut=getIntent().getStringExtra("shortcut");
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_toolbar);
ImageView action_back = (ImageView) findViewById(R.id.action_back);
action_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setVisibility(GONE);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code for launching new tab here
}
});
web1.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress ){
frame_layout.setVisibility(View.VISIBLE);
progress_bar.setProgress(progress);
if(progress==100){
frame_layout.setVisibility(GONE);
srl.setRefreshing(false);
}
super.onProgressChanged(view, progress);
}
});
progress_bar.setProgress(0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_url){
ShowUrlDialog();
return true;
}
if(item.getItemId()==R.id.action_home){
Intent i = new Intent(webview1.this,MainActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_new_tab){
// code to launch new tab here
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(webview1.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(webview1.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m2, menu);
// Associate searchable configuration with the SearchView
return true;
}
#Override
public void onBackPressed() {
if (web1.canGoBack()) {
web1.goBack();
} else {
super.onBackPressed();
}
}
}
I'm trying to build with only fragments.
The App opens with a Activity blank that only has a ActionBar upon clicking the hamburger icon it opens a drawer that give you a menu option.
Upon clicking on one of the Menu Items it opens the First Fragment which has a Recycler/Card View. Upon clicking one of the Cards it opens a new fragment with more details of the selected cards.
Now the problem is the detail fragment shows home icon cause I enable setDisplayHomeAsUpEnabled(true) but when I click on the back arrow it does not do anything. The hardware back button does take me back to the previous (Recycler/Card View) fragment.
I also have setHasOptionsMenu(true) in the detail fragment.
I put log tags everywhere to see when the home button reacts but nothing.
Hope someone can give me a hand.
Activity:
public class AppStart extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
ActionBarDrawerToggle actionBarDrawerToggle;
final String TAG = "AppSart: onBackPressed";
final String TAG1 = "AppSart: resetActionBar";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_start);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public void onBackPressed() {
int stack = getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG,Integer.toString(stack));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
public void resetActionBar(boolean childAction)
{
Log.d(TAG1,Boolean.toString(childAction));
if (childAction) {
actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
}
}
Recycler Fragment:
public class ProductFragment extends Fragment {
final String TAG1 = "ProdFrag: onCreate";
final String TAG2 = "ProdFrag: onCreateView";
final String TAG3 = "ProdFrag: onResume";
final String TAG6 = "ProdFrag: ActionSetting";
final String TAG7 = "ProdFrag: home";
public ProductFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG1,Integer.toString(stack));
boolean canback = stack>0;
((AppStart)getActivity()).resetActionBar(canback);
}
#Override
public void onResume() {
super.onResume();
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG3,Integer.toString(stack));
boolean canback = stack>0;
((AppStart)getActivity()).resetActionBar(canback);
}
#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);
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG2,Integer.toString(stack));
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.toolbar_menu, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
switch (item.getItemId()) {
case R.id.action_settings:
Log.d(TAG6,Integer.toString(stack));
return true;
default:
break;
}
return false;
}
}
Detail Fragment:
public class ProductTabsFragment extends Fragment {
final String TAG1 = "TabFrag: onCreate";
final String TAG2 = "TabFrag: onResume";
final String TAG3 = "TabFrag: ActionSettings";
final String TAG4 = "TabFrag: home";
final String TAG5 = "TabFrag: onBckStkChng";
final String TAG6 = "TabFrag: onNavigateUp";
public ProductTabsFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG1,Integer.toString(stack));
boolean canback = stack>0;
((AppStart)getActivity()).resetActionBar(canback);
}
#Override
public void onResume() {
super.onResume();
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
Log.d(TAG2,Integer.toString(stack));
boolean canback = stack>0;
((AppStart)getActivity()).resetActionBar(canback);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_product_tabs, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.toolbar_menu, menu);
super.onCreateOptionsMenu(menu,inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int stack = getActivity().getSupportFragmentManager().getBackStackEntryCount();
switch (item.getItemId()) {
case R.id.action_settings:
Log.d(TAG3,Integer.toString(stack));
return true;
case android.R.id.home:
Log.d(TAG4,Integer.toString(stack));
//getActivity().onBackPressed();
return true;
default:
break;
}
return false;
}
}
Also this is the code in the recycler adapter for when a card is click to load the detail Fragment:
cvProduct.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
ProductTabsFragment productTabsFragment = new ProductTabsFragment();
AppCompatActivity activity = (AppCompatActivity) view.getContext();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container,productTabsFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
For those who might have this problem. Turns out that when ActionBarDrawerToggle is used setToolbarNavigationClickListener needs to be used for the backarrow.
The R.id.home in optionitemselected seems to be disabled. Hope this helps!
so what I did was remove from the onOptionsItemSelected(MenuItem item):
case android.R.id.home:
Log.d(TAG4,Integer.toString(stack));
return true;
and modified resetActionBar(boolean childAction) in the main Activity which is called in the oncreate of fragmentA and fragmentB.
public void resetActionBar(boolean childAction)
{
Log.d(TAG1,Boolean.toString(childAction));
if (childAction) {
actionBarDrawerToggle.setDrawerIndicatorEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Log.d(TAG4,"Clicked");
onBackPressed();
}
});
} else {
getSupportActionBar().setHomeButtonEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
actionBarDrawerToggle.setDrawerIndicatorEnabled(true);
}
}
I have a fragment that loads data everytime you click on it, I want its behavior to be in a way that if I clicked on it once and moved to another fragment when I go back to it, it does not reload the data and it does not show the "Loading spinner" anymore. How do I do that? This is my fragment code:
public ConsultantFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);//Make sure you have this line of code.
setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
View consultantView = inflater.inflate(R.layout.fragment_consultant, container, false);
//consultantList = new ArrayList<>();
//consultantLisView = (ListView) consultantView.findViewById(R.id.consultant_listview);
swipeRefreshLayout = (SwipeRefreshLayout) consultantView.findViewById(R.id.consultant_list_swipe_refresh);
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(false);
retrieveConsultantList();
consultantRecyclerView.setAdapter(consultantRecylerViewAdapter);
}
});
consultantRecyclerView = (RecyclerView) consultantView.findViewById(R.id.consultant_recyclerview);
setUpDialog();
FloatingActionButton createConsultantFab = (FloatingActionButton) consultantView.findViewById(R.id.add_consultant);
createConsultantFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent createConsultantIntent = new Intent(getContext(), CreateConsultantActivity.class);
startActivity(createConsultantIntent);
}
});
((AppCompatActivity) getActivity()).getSupportActionBar().setTitle(R.string.consultant_list_title);
retrieveConsultantList();
return consultantView;
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
searchMenuItem = menu.findItem(R.id.action_search);
searchView = (SearchView) searchMenuItem.getActionView();
searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
/// searchView.setSubmitButtonEnabled(true);
searchView.setOnQueryTextListener(this);
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
consultantRecylerViewAdapter.getFilter().filter(newText);
consultantRecylerViewAdapter.notifyDataSetChanged();
return false;
}
private void setUpConsultantRecyclerView(List<Consultant> consultantList) {
consultantRecylerViewAdapter = new ConsultantRecylerViewAdapter(getContext(), consultantList);
consultantRecyclerView.setAdapter(consultantRecylerViewAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
consultantRecyclerView.setLayoutManager(linearLayoutManager);
consultantRecyclerView.setItemAnimator(new DefaultItemAnimator());
}
public void setUpDialog() {
consultantListLoadingDialog = ProgressDialog.show(getContext(),
"Loading consultant",
"Please wait");
}
private void retrieveConsultantList() {
final StringRequest consultantStringRequest = new StringRequest(Request.Method.GET,
Constants.BASE_URL.concat(Constants.CONSULTANT_KEY_WORD),
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//eventList = new ArrayList<>();
JsonDataParser parseJSON = new JsonDataParser();
setUpConsultantRecyclerView(parseJSON.jsonArrayToConsultantList(response));
consultantListLoadingDialog.dismiss();
//consultantListAdapter.addAll();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
VolleyRequestQueue.getInstance(getContext()).addToRequestQueue(consultantStringRequest);
}
}
Remove your method which is getting results from the server from onCreateView. onCreateView called all time when you replace fragments. Instead do one time work in onCreate.
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
retrieveConsultantList();
}
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();
}
}
I am using options menu in message fragment where I can add friends from menu. I can navigate to this fragment from activity or fragment. When I launch this message fragment, menu is working fine. When I do navigate through other screen and come to message fragment menu disappears. After using/navigating in the application for 4-5 minutes, menu starts behaving randomly.
Strange behavior is, when I do launch message fragment from activity, menu always works well. This behaves randomly when I launch it from fragment.
Here is my code
public class MessagesFragment extends BaseFragment{
private static final String TAG = MessagesFragment.class.getSimpleName();
Context mContext;
View mView;
private ListView listBuddy;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
((InnerActivity)getActivity()).setActionbarTitle(getResources().getString(R.string.my_buddies));
View v = inflater.inflate(R.layout.fragment_messages, container, false);
listBuddy = (ListView) v.findViewById(R.id.listViewFindBuddy);
this.mView = v;
return v;
}
#Override
public void onDetach() {
// TODO Auto-generated method stub
super.onDetach();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onStart() {
// TODO Auto-generated method stub
super.onStart();
}
#Override
public void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
// TODO Auto-generated method stub
super.setUserVisibleHint(isVisibleToUser);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.messages, menu);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.action_add:
break;
}
return super.onOptionsItemSelected(item);
}
Activity
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
add the following code in your activity :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}