How to access an options menu item from outside the menu - java

How can an options menu item be accessed from an object outside of the menu itself? I'm trying to set an alpha value for one of the options menu items, but it's not working for some reason. The commented lines are what I tried.
I've seen the following code used before, but it's not clear on where and how it should be used:
Drawable drawable = item.getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setAlpha(1);
}
Activity class
public class WebviewActivity extends AppCompatActivity {
private static final String TAG = WebviewActivity.class.getSimpleName();
WebView myWebView;
ProgressBar myProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_webview);
}
#Override
protected void onStart() {
super.onStart();
setContentView(R.layout.fragment_webview);
String url = getIntent().getStringExtra("url");
myWebView = findViewById(R.id.web_view);
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl(url);
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
myProgressBar.setProgress(newProgress);
}
});
}
private class WebViewClient extends android.webkit.WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request){
String url=request.getUrl().toString();
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
}
public void onBtnBackPressed() {
if (myWebView.canGoBack()){
myWebView.goBack();
} else {
onBackPressed();
}
}
public void onBtnForwardPressed() {
if (myWebView.canGoForward()){
myWebView.goForward();
} else {
// menu.getItem(R.id.action_webbrowser_forward).setEnabled(false);
// menu.getItem(R.id.action_webbrowser_forward).mutate();
// menu.getItem(R.id.action_webbrowser_forward).setAlpha(1);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.web_browser, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
else if (item.getItemId() == R.id.action_webbrowser_back) {
onBtnBackPressed();
} else if (item.getItemId() == R.id.action_webbrowser_forward) {
onBtnForwardPressed();
}
return super.onOptionsItemSelected(item);
}
}

Define in your activity class this variable:
MenuItem action_webbrowser_forward;
In onCreateOptionsMenu() after the inflation of the menu, write this:
action_webbrowser_forward = menu.findItem(R.id.action_webbrowser_forward);
then you can use it anywhere in your class:
action_webbrowser_forward.setEnabled(false);
but mutate is used for drawables and not menu items, so get the icon of the item by action_webbrowser_forward.getIcon() and apply mutate to it.

Try passing MenuItem reference on your onBtnForwardPressed function parameters :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
else if (item.getItemId() == R.id.action_webbrowser_back) {
onBtnBackPressed();
} else if (item.getItemId() == R.id.action_webbrowser_forward) {
onBtnForwardPressed(item);
}
return super.onOptionsItemSelected(item);
}
And :
public void onBtnForwardPressed(MenuItem menuItem) {
if (myWebView.canGoForward()){
myWebView.goForward();
} else {
menuItem.setEnabled(false);
menuItem.getIcon().setAlpha(50);
}
}
Hope this helps

Okay I spend couple of hour to get this solution.apparently you can get menuitem from your toolbar. So in my case.
var menuItem = toolbar.menu;
Now to get specfic item from menu item
favIcon = menuItem.findItem(R.id.favourite);
Note: favIcon is MenuItem declare global
Now if you can do whatever you want to do for this icon
eg. to make it invisible
favIcon?.isVisible=false

Related

How to programmatically hide menu on action bars in Android?

This is how I declare my menu on my action bars:
public void checkUserType() {
if (mPrefs.getUserType().equalsIgnoreCase("mahasiswa")) {
requestData(String.valueOf(mPrefs.getUserID()));
} else if (mPrefs.getUserType().equalsIgnoreCase("dosen")) {
requestData(String.valueOf(mPrefs.getSelectedUserId()));
getSupportActionBar().hide();
myMenu.findItem(R.id.exit).setVisible(false);
}
And I want to hide/remove the menu from the action bar using an if-else (not hiding whole action bar, just the menu). I have tried using "myMenu.findItem(R.id.exit).setVisible(false);" but it occurs error on a null object reference
This is my code:
public void checkUserType() {
if (mPrefs.getUserType().equalsIgnoreCase("mahasiswa")) {
requestData(String.valueOf(mPrefs.getUserID()));
} else if (mPrefs.getUserType().equalsIgnoreCase("dosen")) {
requestData(String.valueOf(mPrefs.getSelectedUserId()));
getSupportActionBar().hide();
myMenu.findItem(R.id.exit).setVisible(false);
}
This will hide a menu item by id:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate( R.menu.main_menu, menu );
// hide menu item
menu.findItem( R.id.menu_item_1 ).setVisible( false );
return true;
}
You can apply the same to:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if( item.getItemId() == R.id.menu_item_1 ) {
item.setVisible( false );
}
}
here just call invalidateOptionsMenu() and move your logic to onCreateOptionsMenu() and change visiblity there.
for example
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
.
.
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
invalidateOptionsMenu();
}
});
}
and in onCreateOptionsMenu()
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.activity_main_menu, menu);
menu.findItem(R.id.menu_item).setVisible(condition);
}

Splash Screen for Android Webview

I have a WebView app and would like to add a splash screen to show either while loading the page, or for a set amount of time. I have tried some other solutions but could not find one that worked. If necessary to know, my splash image is splash.png, located in the drawable folder.
Here is my MainActivity.java
public class MainActivity extends Activity {
private GoogleApiClient client;
#Override
public void onBackPressed()
{
WebView webView = (WebView) findViewById(R.id.webView);
if(webView.canGoBack()){
webView.goBack();
}
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Tap Twice To Exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView view = (WebView) this.findViewById(R.id.webView);
view.getSettings().setJavaScriptEnabled(true);
view.setWebViewClient(new MyBrowser());
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
if(isNetworkStatusAvialable (getApplicationContext())) {
view.loadUrl("file:///android_asset/index.html");
} else {
view.loadUrl("file:///android_asset/error.html");
}
}
public static boolean isNetworkStatusAvialable (Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null)
{
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if(netInfos != null)
if(netInfos.isConnected())
return true;
}
return false;
}
#Override
public void onStart() {
super.onStart();
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"MLINKS",
Uri.parse("http://host/path"),
Uri.parse("android-app://PACKAGE-NAME/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"MLINKS",
Uri.parse("http://host/path"),
Uri.parse("android-app://PACKAGE-NAME/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
private class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
}
Thank you for any help!
EDIT:
Define a Progress Dialog:
private ProgressDialog pd;
Then inside your:
view.setWebViewClient(new MyBrowser() {
Insert this:
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
}
I did something like this at one time. IIRC, it went like this:
First, I created a special ImageView subclass that overrode onTouchEvent() and threw away all the events.
Then for my layout, I had my ImageView subclass overlay the WebView then made it hidden, like this (for example):
<FrameLayout
...
>
<WebView
...
/>
<com.example.TouchHandlerImageView
....
android:src="R.drawable.splash"
android:visibility="gone"
/>
....
</FrameLayout>
Then my code went like this:
Show the splash imageview. (The onTouchEvent() would keep touch events from going through to the WebView underneath)
Start the page loading (In my case, I also had to run some javascript to set up the page)
In WebViewClient onPageFinshed(), hide the splash imageview, displaying the WebView with page fully loaded.
at first thing make a background and show it im main screen till the data is being ready.
use AsyncTask Class because it has 3 methods which them
1- onPreExecute() //don't do anything here
2- doInBackgroundProcess()// fetch your data here
3- onPostExecute()//get back the original background

how to get dictionary meaning from direct to web android

this is my main activity code.
this is kind of jumble solver Program.
Jumble helper is create to solve unjumble word.
When you enter any Unordered word it will gives correct dictionary word.
currently when I tap on any word it text converted in to voice (TTS API) instead of I want to open dictionary meaning.
now I want to add dictionary meaning from web dictionary..
how can I add word meaning??
note that I will currently call data from unix word dic.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edt_char = (EditText) findViewById(R.id.editText);
wordListView = (ListView) findViewById(R.id.word_listview);
wordListView.setOnItemClickListener(this);
tts = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i != TextToSpeech.ERROR) {
tts.setLanguage(Locale.ENGLISH);
}
}
});
copyDBFileOnlyOnce();
}
public void viewOnClick(View button) {
switch (button.getId()) {
case R.id.btnGet:
String word = edt_char.getText().toString();
if (!"".equalsIgnoreCase(word) && ResourceUtil.supportedWordFormat(word)) {
new DataDictionaryTask(this, wordListView).execute(AlphabetToPrime.calcPrimeProduct(word.toLowerCase()));
} else {
((View)(wordListView.getParent())).setVisibility(View.GONE);
Toast.makeText(getApplicationContext(), "Please enter a-z characters only", Toast.LENGTH_LONG).show();
}
hideSoftKeyboard(this);
break;
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_main);
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String spk = (String)parent.getItemAtPosition(position);
Log.d("Selected text:", spk);
tts.speak(spk, TextToSpeech.QUEUE_FLUSH, null);
}
private void copyDBFileOnlyOnce()
{
prefs = getSharedPreferences("jumblehelper_pref", MODE_PRIVATE);
if (prefs.getBoolean("firstrun", true)) {
new AssetLoader(this).execute("jumblehelper.db3");
prefs.edit().putBoolean("firstrun", false).commit();
}
}
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}

One of webview reload page after change screen orientation

First code:
package com.fshare.zsee;
public class ZSEEActivity extends TabActivity {
private WebView webview ;
private WebView webviewtwo;
private TabHost mTabHost;
private WebSettings webviewtwoSettings;
private int error;
protected void onStart() {
super.onStart();
// The activity is about to become visible.
}
protected void onStop() {
super.onStop();
// The activity is about to become visible.
}
protected void onRestart() {
super.onRestart();
}
protected void onDestroy(){
super.onDestroy();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Activity activity = this;
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Zastępstwa").setContent(R.id.tab1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("Plan Lekcji").setContent(R.id.tab2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("O programie").setContent(R.id.tab3));
webview = (WebView) findViewById(R.id.webView1);
webviewtwo = (WebView) findViewById(R.id.webView2);
webviewtwoSettings = webviewtwo.getSettings();
if (savedInstanceState != null){
error = savedInstanceState.getInt("webtwoerror");
webview.restoreState(savedInstanceState.getBundle("stateone"));
webviewtwo.restoreState(savedInstanceState.getBundle("statetwo"));
if(error == 1){
webviewtwoSettings.setTextSize(TextSize.NORMAL);
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
mTabHost.setCurrentTab(savedInstanceState.getInt("CURRENT_TAB"));
}
else{
webviewtwoSettings.setTextSize(TextSize.LARGER);
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
//error = 0 ;
mTabHost.setCurrentTab(0);
}
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webview.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
}
});
webviewtwo.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
webviewtwoSettings.setTextSize(TextSize.NORMAL);
String summary = "<html><body><meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" ><center>Coś się zepsuło :(</center></body></html>";
webviewtwo.loadData(summary, "text/html","utf-8");
Toast.makeText(activity, "O nie! " + description, Toast.LENGTH_SHORT).show();
error = 1 ;
}
});
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
// put your stuff here or just block the back button for perticular activity
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
return super.onKeyDown(keyCode, event);
}
protected void onSaveInstanceState(Bundle outState) {
Bundle outStateone = new Bundle();
Bundle outStatetwo = new Bundle();
webview.saveState(outStateone);
webviewtwo.saveState(outStatetwo);
outState.putBundle("stateone", outStateone);
outState.putBundle("statetwo", outStatetwo);
outState.putInt("CURRENT_TAB", mTabHost.getCurrentTab());
outState.putInt("webtwoerror", error);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.item1:
final AlertDialog alertdialog= new AlertDialog.Builder(this).create();
alertdialog.setTitle("O Programie");
alertdialog.setMessage("Zmiany w 1.0.1: \n-Obsługa planu z dnia 17.10.2011\n-Drobne Poprawki");
alertdialog.setButton("Fajno", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
alertdialog.cancel();
}
});
alertdialog.show();
return true;
case R.id.item2:
finish();
case R.id.item3:
if(mTabHost.getCurrentTab() == 0){
webview.loadUrl("http://zsee.bytom.pl/ogloszenia.php");
}
else if(mTabHost.getCurrentTab() == 1)
{
error = 0 ;
webviewtwo.loadUrl("http://zsee.bytom.pl/plannew/index.html");
webviewtwoSettings.setTextSize(TextSize.LARGER);
}
default:
return super.onOptionsItemSelected(item);
}
}
}
And now very simple question. Why webviewtwo reload page after change orientation and webview (webView1) doesen't ? and how to prevent it? Now only webView1 doesen't reload page after change screen orientation.
Sierran
I am not sure why the first one doesn't change but adding this to my manifest inside of the activity tag worked for me
android:configChanges="orientation|keyboardHidden|keyboard"

Android: Broken menu button when text used

I have defined a standard onCreateOptionsMenu. The menu button works fine when my EditText box is empty. But when the EditText box has data in it, the menu button doesnt work. Any clue? Please help, i have no clue how to solve this. Thanks!
public class TipCalc extends Activity {
private EditText total;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
total = (EditText)findViewById(R.id.EditText01);
total.setOnKeyListener(mKeyListener);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
private OnKeyListener mKeyListener = new OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
if((v.getId() == R.id.EditText01
&& (total.getText().toString().length() > 0) {
calculate();
return true;
}
}
return false;
}
}
I dont know if that would be correct but create setOnClickListener rather than OnKeyListener
something like this
TextView total = (TextView) findViewById(R.id.EditText01);
total.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
//do some stuff
}
});

Categories

Resources