OptionMenu doesn't show anything in Sherlock Fragment - android

I am working in Sherlock Fragment and needed to add some options in the optionMenu. But unable to do this. Here is my code below. i have already added setHasOptionMenu(true) in onCreateView :So please have a look at this code,,, and tell me where i am wrong
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
super.onCreateOptionsMenu(menu, inflater);
progress = menu.add("Progress");// first option
progress.setIcon(android.R.id.progress);
progress.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
MenuItem add = menu.add("Refresh");// second option
add.setIcon(R.drawable.ic_menu_refresh);
add.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
MenuItem get = menu.add("Logout");// third option
get.setIcon(R.drawable.power);
get.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
get.setOnMenuItemClickListener(new OnMenuItemClickListener()
{
#Override
public boolean onMenuItemClick(MenuItem item)
{
userfunctions = new UserFunctions();
//AsyncTask
class AsyncLogout extends AsyncTask<Void, Void, String> {
protected String doInBackground(Void... params) {
json = userfunctions.logoutUser(userid);
try {
if (json.getString(KEY_SUCCESS) != "1") {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
p_error_msg = "successful";
}
} else {
p_error_msg = "error";
}
} catch (Exception e) {
e.printStackTrace();
}
return p_error_msg;
}
protected void onPostExecute(String result) {
try {
if (result.equals("successful")) {
Intent ii = new Intent(getActivity(),
HomeActivity.class);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("login", "0");
editor.remove("PREF_ACCESS_TOKEN_TWITTER");
editor.remove("PREF_ACCESS_TOKEN_SECRET_TWITTER");
editor.remove("PREF_ACCESS_TOKEN_FB");
editor.remove("PREF_ACCESS_TOKEN_SECRET_FB");
editor.commit();
startActivity(ii);
getActivity().finish();
} else {
}
} catch (Exception e) {
}
}
protected void onPreExecute() {
super.onPreExecute();
}
}
AsyncLogout as=new AsyncLogout();
as.execute();
return false;
}
});
add.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item)
{
Intent i = new Intent(getActivity(), MainActivity.class);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("login", "1");
editor.putInt("defaultSelector", 2);
editor.commit();
startActivity(i);
getActivity().finish();
return false;
}
});
}

Here is the proper way how to handle MenuItems from Fragment :
public class MyFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.menu_inner_cards, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()){
case R.id.action_sort:
// DO STUFF
break;
case R.id.action_anytag:
// DO STUFF
break;
}
return true;
}
}
My suggestion is, instead of creating the items in Java code, use a custom menu.xml only for your Fragment, inflate it and use onOptionsItemSelected() for handling click event on menu items.

Related

How can I implement tabs in an Android Browser?

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();
}
}
}

hide/show options menu when clicking buttons

I'm using some buttons in my fragments. When i checks those buttons then options menu should display. And when i uncheck it it should hide options menu. How should i do this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mLocation = getArguments().getString(Beco.EXTRA_LOCATION);
listMalls = temporaryModelCache.getDealData().getFacets().getArea();
listCategories = temporaryModelCache.getDealData().getFacets().getCategories();
listGender = temporaryModelCache.getDealData().getFacets().getAgeGroup();
try {
MainActivity activity = (MainActivity) getActivity();
if (activity != null) activity.hideBottomBar();
} catch (Exception ignored) {
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
return true;
}
return super.onOptionsItemSelected(item);
}
And this is the event that i need to hide/display options menu
private void checkSelected() {
if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) {
footerTab.setVisibility(View.VISIBLE);
} else {
footerTab.setVisibility(View.GONE);
}
}
When if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) i need to display actions menu and in the else part i need to hide options menu ! How can i achieve this?
call invalidateOptionsMenu() for hide and show option menu
Boolean Isreset= false;
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
if(!Isreset)
{
mResetButton.setVisibility(true);
}else{
mResetButton.setVisibility(false);
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
Isreset= true;
invalidateOptionsMenu();
return true;
}
return super.onOptionsItemSelected(item);
}
You can keep the instance of Menu object and later on use it to invalidate the options menu.
private Menu menu;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mLocation = getArguments().getString(Beco.EXTRA_LOCATION);
listMalls = temporaryModelCache.getDealData().getFacets().getArea();
listCategories = temporaryModelCache.getDealData().getFacets().getCategories();
listGender = temporaryModelCache.getDealData().getFacets().getAgeGroup();
try {
MainActivity activity = (MainActivity) getActivity();
if (activity != null) activity.hideBottomBar();
} catch (Exception ignored) {
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.forgot_password, menu);
mResetButton = menu.findItem(R.id.action_reset);
this.menu = menu;
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.action_reset:
Log.d(TAG, "onClick");
resetFilter();
return true;
}
return super.onOptionsItemSelected(item);
}
Using the menu object then toggle the options menu.
private void checkSelected() {
if (!mapMall.isEmpty() || !mapGender.isEmpty() || !mapCategory.isEmpty()) {
footerTab.setVisibility(View.VISIBLE);
menu.findItem(R.id.action_reset).setVisibility(View.VISIBLE);
} else {
footerTab.setVisibility(View.GONE);
menu.findItem(R.id.action_reset).setVisibility(View.GONE);
}
}

saving the edittext value to another activity on click of save actionbutton in android

how to save the text given to edit text, after clicking the save action button in action bar that should save to another activity.
my first activity Add.java
public class Add extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_add_action, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:save();
return true;
case R.id.cancel:cancelnavi();
return true;
}
return super.onOptionsItemSelected(item);
}
private void save() {
EditText titlename;
titlename=(EditText)findViewById(R.id.edittitle);
String title=titlename.getText().toString();
if (title.equalsIgnoreCase("")){
Toast.makeText(Add.this, "Script title should not be empty", Toast.LENGTH_LONG).show();
} else {
Intent i;
i=new Intent(getApplicationContext(), Scripts.class);
i.putExtra("n", titlename.getText().toString());
startActivityForResult(i, 0);
titlename.setText("");
}
}
}
It should be saved to scripts.java
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflate=getMenuInflater();
getMenuInflater().inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_edit:editscript();
break;
}
return true;
}
private void editscript() {
Intent editinIntent;
editinIntent=new Intent(Scripts.this, Edit.class);
startActivity(editinIntent);
}
}
Maybe this can help you.
public class Scripts extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scripts);
getActionBar().setDisplayShowHomeEnabled(false);
//Extract the data
String yourTitle = getIntent().getStringExtra("n");
}
}

Trouble making menuitem visible after asynctask

I have a Refresh button that I would like to make visible depending on the situation.
When the Refresh button is clicked I can make it invisible without a problem, however, I cannot make it visible again once the AsyncTask process finishes. I have trouble passing the MenuItem value back to the AsyncTask.
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.refresh_action_provider, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_refresh:
item.setVisible(false); //hide refresh button
setSupportProgressBarIndeterminateVisibility(true);
Toast.makeText(getApplicationContext(), "REFRESH CLiCKED", Toast.LENGTH_SHORT).show();
new DownloadNewsTask().execute();
return true;
}
return false;
}
You could pass your item in your task's constructor, store it and make it visible in onPostExecute method:
public class DownloadNewsTask extends AsyncTask<...> {
private final MenuItem item;
public DownloadNewsTask(MenuItem item) {
this.item = item;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
item.setVisible(true);
}
...
}
And then:
new DownloadNewsTask(item).execute();
You can also have the item be a member of your activity class and access it from your task if it is defined as an inner class of your activity:
public class TestActivity extends Activity {
protected MenuItem refreshItem;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getSupportMenuInflater().inflate(R.menu.refresh_action_provider, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_refresh:
this.refreshItem = item;
item.setVisible(false); // hide refresh button
setSupportProgressBarIndeterminateVisibility(true);
Toast.makeText(getApplicationContext(), "REFRESH CLiCKED", Toast.LENGTH_SHORT).show();
new DownloadNewsTask().execute();
return true;
}
return false;
}
public class DownloadNewsTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// your stuff...
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
refreshItem.setVisible(true);
}
}
}

Android Activity Group - second activity always shows first activity menu

I have one problem using ActivityGroup. I have two activities inside an ActivityGroup and both of them use a menu (overriding the onCreateOptionMenu and onOptionsItemSelected).
Both activity have different menus.
Well, the problem is that the second activity always show the first activity menu,
Any idea about this issue?
Below is my code
public class myActivityGroup extends ActivityGroup {
----
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id, intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
View view = window.getDecorView();
history.add(view);
setContentView(view);
}
}
public void back() {
if (history.size() > 0) {
int lastActivityIndex = history.size() - 1;
int lastIDIndex = mIdList.size() - 1;
String activityId = mIdList.get(lastIDIndex);
Log.d(TAG, "activityId:" + activityId);
history.remove(lastActivityIndex);
mIdList.remove(lastIDIndex);
setContentView(history.get(history.size() - 1));
} else {
finish();
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Activity current = getLocalActivityManager().getCurrentActivity();
return current.onPrepareOptionsMenu(menu);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
LocalActivityManager manager = getLocalActivityManager();
Activity current = manager.getCurrentActivity();
return current.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
LocalActivityManager manager = getLocalActivityManager();
Activity current = manager.getCurrentActivity();
return current.onOptionsItemSelected(item);
}
}
public class ChildActivity1 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//add menu here
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.settings_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle on menu item selected here
return true;
}
}
public class ChildActivity2 extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//add menu here
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.offer_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//handle on menu item selected here
return true;
}
}
When you add the activities, the "current" activity is that last one added. I suspect that if you interact with the other activity then activate the options menu it will work.
Try retrieving the activity you need using the String Id:
LocalActivityManager manager = getLocalActivityManager();
Activity a = manager.getActivity(id);
return a.onCreateOptionsMenu(menu);

Categories

Resources