I am trying to create a button on the action bar that will activate a method that is in the same activity.
Below is my menu xml:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".AddContactActivityOCR">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/undo"
android:orderInCategory="100"
android:title="UNDO"
app:showAsAction="always"/>
</menu>
Below are my relevant codes in the activity:
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.menu_add_contact_undo, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.undo:
onRewrite();
return true;
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onRewrite(View v){
listName.setText(recognizedText);
listOwner.setText(recognizedText);
companyName.setText(recognizedText);
companyAddress.setText(recognizedText);
companyNumber.setText(recognizedText);
mCurrentLang = mFromLang;
validator(recognizedText);
}
I am trying to start "onRewrite()" when I click the "UNDO" button on my action bar.
However it shows the error below:
I tried using "android:onClick="onRewrite" on a normal button and it is able to start this method. Why is it not starting "onRewrite" in this case?
why its show error?
you have create method with parameter View like onRewrite(View v) and you are trying to call it without parameter that's why its show you that message.
remove parameter from method. like below
public void onRewrite(){ .... // your code}
I tried using "android:onClick="onRewrite" on a normal button and it
is able to start this method.
why its working?
want to use method to work in both case. create two method with same name & use same code inside that.
public void onRewrite(){ .... // your code}
public void onRewrite(View v){ .... // your code}
another solution is create button click in activity and remove android:onClick="onRewrite from layout.xml, call onRewrite() from click event as well as from onOptionsItemSelected
Change your Activity code
Error Because you calling method On onRewrite() without Parameter
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.menu_add_contact_undo, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.undo:
onRewrite();
return true;
case android.R.id.home:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onRewrite(){
listName.setText(recognizedText);
listOwner.setText(recognizedText);
companyName.setText(recognizedText);
companyAddress.setText(recognizedText);
companyNumber.setText(recognizedText);
mCurrentLang = mFromLang;
validator(recognizedText);
}
Hope this will helps you
Related
I'm building an app which has menu item in toolbar, i have created submenu for one menu i.e whose id is 'cloud'. I would like to implement onclick on each submenu when click will open different activity.
Here is the menu.xml file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_refresh"
app:showAsAction="ifRoom"
android:title="Refresh"
android:icon="#drawable/ic_loop_black_24dp"></item>
<item
android:id="#+id/notes"
app:showAsAction="ifRoom"
android:title="Refresh"
android:icon="#drawable/ic_event_note_black_24dp"></item>
<item
android:id="#+id/cloud"
app:showAsAction="ifRoom"
android:title="Refresh"
android:icon="#drawable/ic_cloud_upload_blackt_24dp">
<menu>
<group
android:checkableBehavior="single">
<item android:id="#+id/imageee"
android:title="Image Upload"
android:orderInCategory="100"
app:showAsAction="ifRoom" />
<item android:id="#+id/pdfff"
android:title="Pdf Upload"
android:orderInCategory="100"
app:showAsAction="never"/>
</group>
</menu>
</item>
</menu>
Here is the Mainactivity file
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
mymenu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.action_refresh:
Intent intent = new Intent(MainActivity.this, UpdateService.class);
startService(intent);
}
return true;
case R.id.notes:{
Intent activity_weather = new Intent(this,Physics.class);
startActivity(activity_weather);
}
return true;
case R.id.cloud:{
}
return true;
}
return super.onOptionsItemSelected(item);
}
I looked for answer and tried on my own but I have no idea how to achieve this.
Any help is appreciated.
Thank you in advance.
I have a solution for you:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
// TODO:
toast("refresh");
return true;
case R.id.notes:
// TODO:
toast("notes");
return true;
case R.id.imageee:
// TODO: Start your image upload
toast("imageee");
return true;
case R.id.pdfff:
// TODO: Start your PDF upload
toast("pdfff");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void toast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
I write toast method to show a toast when users click on an item on menu or sub menu. Please remove //TODO: line and add your code for each case there.
I don't think you want to have
android:checkableBehavior="single"
set on your submenu. This behaviour is only useful if you just want to capture the choice (or choices) in the menu item, but not if you actually want to react (ie: do something) when the user selects a submenu item.
Based on your question, it sounds like you want to launch another Activity when the user selects one of these submenu items. To do that just add those menu items to the switch statement in onOptionsItemSelected():
case R.id.imageee:
Intent imageIntent = new Intent(this, Upload.class);
startActivity(imageIntent);
return true;
case R.id.pdfff:
Intent pdfIntent = new Intent(this, Pdf.class);
startActivity(pdfIntent);
return true;
Another interesting solution could be:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent();
switch (item.getItemId()) {
case R.id.action_refresh:
intent.setClass(this, UpdateService.class);
break;
case R.id.notes:
intent.setClass(this, Physics.class);
break;
case R.id.cloud:
intent = null;
break
case R.id.imageee:
// TODO set intent class
break;
case R.id.pdfff:
// TODO set intent class
break;
}
// If the selected item is the one that opens the submenu does not try to start the
// activity avoiding throwing null pointer exception and consequently opens the submenu
if (!(intent == null))
startActivity(intent);
return super.onOptionsItemSelected(item);
}
That way you avoid having to have multiple times, in all cases the same call to the method.
startActivity()
Saving lines of code. It is even more advantageous if you decide to add more items to the menu.
I have a refresh icon on my menu which when clicked will refresh the contents of the Activity. But the problem is that the refresh icon is still clickable while it is refreshing which I do not want. Here is my menu.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="#+id/action_refresh"
android:orderInCategory="100"
android:icon="#mipmap/ic_refresh"
android:enabled="true"
android:title="#string/action_settings"
app:showAsAction="always"/>
And here is where I handle the click event for the icon
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
// getData() fetches the data and updates the display
getData();
return true;
}
return super.onOptionsItemSelected(item);
}
Also, is there a way to maybe dim the icon so that the user knows that they have already clicked the icon?
When you click the icon, use the isEnabled() method of your Menuitem to check if it is currently enabled. If it is, then disable it until the data is loaded. Once the data loads successfully, then you can enable it again. Example:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(item.isEnabled()) {
// "Dim" the icon like you said. You can use other alpha values if you like.
item.getIcon().setAlpha(130);
// Disable the menu icon
item.setEnabled(false);
}
getData();
return true;
}
return super.onOptionsItemSelected(item);
}
Now, you said that you have a getData() method which updates the display after it fetches the data. Once the data is fetched, check if the Menuitem is disabled. If it is disabled, then enable it again. Example:
if(item != null && item.isEnabled() == false) {
// "Undim" the icon
item.getIcon().setAlpha(255);
// Enable it again
item.setEnabled(true);
}
You can use setEnabled(true) method to enable/disable menu item
You could create a second menu.xml, that is used after the refresh button is clicked. To force a menu redraw call invalidateOptionsMenu();
In this second menu.xml, the refresh button could be disabled, or switched to a diffrent one, indicating the user, that the refresh is on going.
Easiest way to fix this is to hold on to the menu item in your activity.
private MenuItem mRefreshItem;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater infl = new MenuInflater(this);
infl.inflate(R.menu.menu, menu);
mRefreshItem = menu.findItem(R.id.action_refresh);
return super.onCreateOptionsMenu(menu);
}
/** Call this when you begin or end loading */
private void setRefreshEnabled(boolean enabled) {
mRefreshItem.setEnabled(enabled);
}
I'm trying to add a second button to my action bar. I have one drawable that opens a new activity. I want to add a second on in onOptionsItemSelected. Here is my code.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.new_account:
Intent intent = new Intent(getActivity(), AddAccountActivity.class);
this.startActivity(intent);
break;
switch (item.getItemId()) {
case R.id.action_settings:
Intent myIntent = new Intent(getActivity(), SettingsActivity.class);
this.startActivity(myIntent);
break;
}
return super.onOptionsItemSelected(item);
}
}
I get an error asking in the last closing bracket saying, "Missing return statement." I am new to android development so I'm guessing it is something simple. Thanks.
Edit: Here is my main.xml in my menu folder
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.myapplication2.app.MainActivity" >
<item android:id="#+id/new_account"
android:icon="#drawable/ic_action_new"
android:showAsAction="always"/>
<item android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
android:showAsAction="always" />
I haven't changed any lines of the settingsActivity.class. I just created a new activity with the "settings" mode.
If you want add menuItem, you must add item in xml.
Project-res-menu has a xml files.
There is already has a 1 item.
Try add new Item and set attribute, I think you show a two menu.
You are getting "Missing return statement" because you don't have a return statement in switch-case.
For ex:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.settings:
setSettings();
return true;
case R.id.second:
setColor();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
Hello I having a problem trying to get eclipse to recognized my menu icon. I want to have the icon appear in the action bar and when clicked, I want to display a toast.The problem is that my save icon is not being recognized in eclipse. Here is my code :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.profilemenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch(item.getItemId()) {
case android.R.id.home:
finish();
case android.R.id.save:
save cannot be resolved or is not a field
}
return false;
}
The menu :
<?xml version="1.0" encoding="UTF-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/save" android:showAsAction="ifRoom"
android:title="#string/save_str" android:icon="#drawable/content_save" />
</menu>
You're using the incorrect identifier within the switch statement, you should use just R.id.Save, like so:
switch(item.getItemId()) {
case R.id.home:
finish();
case R.id.save:
Toast.makeText(getContext(), "Toast message", Toast.LENGTH_SHORT).show();
}
Using the android identifier means you are trying to find a resource built into the android sdk which doesn't exist.
I want to customize the activity back button in action bar, not in hard key back button. I have overriden the onBackPressed() method. It works with my emulator back button, but not with action bar back button.
I want it to happen with action bar. How can I do this?
Here is my code:
#Override
public void onBackPressed() {
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
return;
}
I have used this toast whether back pressed is working or not but the actual implementation changes like to move back to previous activity. But this is not working with the button present on top of action bar (besides title of the activity).
Please any one could specify me the problem.
I think you want to override the click operation of home button. You can override this functionality like this in your activity.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Toast.makeText(getApplicationContext(),"Back button clicked", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
If you want ActionBar back button behave same way as hardware back button:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
onBackPressed();
return true;
}
return false;
}
Two things to keep in mind that the user can either press back button or press the actionbar home button.
So, if you want to redirect him to the same destination then you can do this.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
#Override
public void onBackPressed() {
super.onBackPressed();
Intent intent = new Intent(CurrentActivity.this, NextActivity.class);
startActivity(intent);
finish();
}
This will take the user to the intent pressing either key or the action bar button.
Sorry mine is a late answer, but for anyone else arriving at this page with the same question, I had tried the above:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
...
if (item.getItemId() == android.R.id.home) {
....
}
....
}
but this failed to catch the "Back" button press.
Eventually I found a method that worked for me on https://stackoverflow.com/a/37185334/3697478 which is to override the "onSupportNavigateUp()" as I am using the actionbar from the "AppCompatActivity" support library. (There is an equivalent "onNavigateUp()" for the newer actionbar/toolbar library.)
#Override
public boolean onSupportNavigateUp(){
finish();
return true;
}
and I removed the "android:parentActivityName=".MainActivity" section from the manifest file.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
(1) Add Parent activity for your child activity (AndroidManifest.xml)
<activity
android:name=".ParentActivity" />
(2) override the onSupportNavigateUp method inside the child activity
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
I have achieved this, by using simply two steps,
Step 1: Go to AndroidManifest.xml and in the add the parameter in tag - android:parentActivityName=".home.HomeActivity"
example :
<activity
android:name=".home.ActivityDetail"
android:parentActivityName=".home.HomeActivity"
android:screenOrientation="portrait" />
Step 2: in ActivityDetail add your action for previous page/activity
example :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
If you want to return to the previous instance of an Activity by pressing of ActionBar home button, without recreating it, you can override getParentActivityIntent method to use the one from the back stack:
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public Intent getParentActivityIntent() {
return super.getParentActivityIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
EDIT:
Also you can achieve the same result by
setting the launchMode of your parent activity to singleTop.
So setandroid:launchMode="singleTop" to parent activity in your manifest.
Or you can use flag FLAG_ACTIVITY_CLEAR_TOP with the UP intent.
reference: Providing Up Navigation
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == android.R.id.home) {
onBackPressed();
return true;
}
//noinspection SimplifiableIfStatement
if (id == R.id.signIn) {
return true;
}
return super.onOptionsItemSelected(item);
}
///////////////////
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
There are several ways how to set up back button in bar:
1) method .setDisplayHomeAsUpEnabled(true); will do it, and then you can simply override android.R.id.home
2) adding <meta-data android:name="android.support.PARENT_ACTIVITY" android:value="my.package.parrent" /> in Android Manifest, but in this case you can not override android.R.id.home in OnOptionsMenuSelected.
.. for those who wonder why it doesn't work for them...