Android, trigger Activity on menu action - android

I'm new to android and I'm trying to figure out if there is a best practice in menu handling.
Well, here is the thing:
I have created a menu.xml file (within res/menu), Main.java handle the menu action with a switch case.
I'm wondering what is the best way to run appropriate task when an action is performed on a menu item:
Use an intent and trigger the corresponding activity
define everything (which could be a lot of code) within the case corresponding to this menu item.

...
startActivity(new Intent(getApplicationContext(),MyOtherActivity.class));
return;
it doesn't have to be more complicated than that.

Related

How to show "up" / "back" button in Xamarin.Forms?

I am trying to work out how to show the "up" arrow in Xamarin.Forms without a pushing a page onto the stack. I.E. I just want to perform an action when the back button is pressed. I am completely stuck on this so any help would be appreciated.
I have tried creating a custom renderer which handles a view property called DisplayHomeAsBack. Which in the renderer calls the following:
FormsAppCompatActivity context = ((FormsAppCompatActivity)Forms.Context);
Android.Support.V7.App.ActionBar actionBar = context.SupportActionBar;
if (actionBar != null)
{
actionBar.SetDisplayHomeAsUpEnabled(element.DisplayHomeAsBack);
}
Unfortunately it seems this does absolutely nothing, even though all online tutorials and stackoverflow question for android suggest this method.
The plan is that I can then use the "OnBackButtonPressed" override in MasterDetailPage, which should allow me to perform this action. Unfortunately displaying the back button has been the larger hurdle so far!
Any idea of a better way to do this or how I can get the current mechanism to work?
EDIT
I have created a project and uploaded it to this question on the Xamarin support forums, if it helps.
http://forums.xamarin.com/discussion/comment/186330#Comment_186330
Sorry to keep you waiting so long!
Warning that I did not actually run this code and changed it from my own so I would be surprised if it worked perfectly without some changes.
So below should add a back button where there was not one before (so like when there is not really a page to go back to) and then we will add a custom action to perform when it gets pressed.
I would suggest you push a new page onto the stack without using animation so it is transparent to the user and also makes all of this much simpler, but if you absolutely do not want to do that, the below method should work.
MainActivity:
//Use this to subscribe to the event which will create the back button
public override bool OnCreateOptionsMenu(IMenu menu) {
if(menu != null && App.AppMasterPage != null) { //You will need this to make sure you are on your MasterDetailPage, just store a global reference to it in the App class or where ever
Xamarin.Forms.MessagingCenter.Unsubscribe<string>(this, "CreateBackButton");
Xamarin.Forms.MessagingCenter.Subscribe<string>(this, "CreateBackButton", stringWeWillNotUse => { //Use this to subscribe to the event that creates the back button, then when you want the back button to show you just run Xamarin.Forms.MessagingCenter.Send<string>(this, "CreateBackButton")
ActionBar.DisplayOptions = ActionBarDisplayOptions.ShowTitle | ActionBarDisplayOptions.ShowHome | ActionBarDisplayOptions.UseLogo | ActionBarDisplayOptions.HomeAsUp; //You may need to play with these options to get it working but the important one is 'HomeAsUp' which should add the back button
});
} else {
Xamarin.Forms.MessagingCenter.Unsubscribe<string>(this, "CreateBackButton");
}
return base.OnCreateOptionsMenu(menu);
}
Now the next step is do do a custom action when it is pressed. I think you can either override OnBackPressed() or OnOptionsItemSelected() in MainActivity or maybe you can override the MasterDetailPage method. I am not sure.
Which ever one works for you, inside of that override, I would simply check to see if you are on your App.AppMasterPage like we did above, and if so, send a MessagingCenter message which your App.AppMasterPage has already subscribed to in order for it to handle the custom action.
If you get stuck let me know!
I know it sounds like a bit of a hack, but the best "solution" I have found so far is to add a page behind the current page (behind the root) so it is not visible. Then when the user presses the back button, handle it by removing that page.

Empty action bar in "MainActivity2" Android Studio

I have created with Android Studio 1.4 a Blank Activity where I can set menu's items to diplay.
My problem is that when I create a new activity "MainActivity2" I see the Action Bar with its colours but I'm not able to "connect" a menu with its elements. By default "onOptionsItemSelected" and "onCreateOptionsMenu" are not created automatically in this new activity.
Thanks
First activity,
MainActivity2
I found the solution. I saw some tutorials in Internet saying that to change activity I have to use "setContentView(R.layout.activity_main2)". By the way using this the application will override only the design and will never be executed the "onCreateOptionsMenu" where menu items are going to be added. The correct action to execute on the button listener is " startActivity(new Intent(MainActivity.this, Main2Activity.class)) ", so that the code can be executed.

One class for each layout (new page)?

I wast just wondering if the standard practice is to create an activity/fragment class for each layout file (new page).
Example:
MainActivity.java
onCreate(){
setContentView(R.layout.**start_page**)
}
And than when the user clicks a button in the action bar (or some other button on the screen):
onOptionItemSelected() {
switch XX -> case XX: setContentView(R.layout.**next_page**)
}
So could i do the above instead of launching a new activity.java (that contains a new layout.xml) with an intent, or inflating the view with a fragment.java (that also contains a new layout.xml).
I can see that the up/back navigation wouldn't work with the above code, but is that the only reason why you basically have to create two files (.java & .xml) for each new page in your app.
Yes you could do it technically but beware that if you already create an instance of view lets say Button and you change the layout button will be null because button is not located in your View and also it will take time to render again the layout. So it is a best practice to start a new activity or just create a fragment.
You can do that, but every view will be on the given Activity, and the event handlers would be in the same class, which isn't really modular. It could get extremely bloated and you'll have a 2000 line superclass because it handles every single button click in arbitrary functions (or even worse, in a single onClick function).

Android OptionsMenu, add items on runtime

I've got an optionsmenu looking like this right now:
Lets say that if I click item 1, i want two new items added to the menu looking like this:
I'm having problems doing this at runtime(while it's open) since onCreateOptionsMenu is only called once and onPrepareOptionsMenu seems only to be called when the menubutton of the phone is clicked. I just want it to refresh with these new items added.
Thanks for any help!
When you select an option item it causes the system to close the options menu. This happens after onOptionsItemSelected() runs. I'm guessing what you need to have happen is for that entire process to complete then have the options menu programmatically opened again so onPrepareOptionsMenu() is called.
Try this:
In onOptionsItemSelected(), when the user selects your "add two more options" option, set a flag in your activity but don't do anything else.
Override onOptionsMenuClosed(). Check if the flag is set. If it is, then post to be executed by the UI thread on its next pass. It should do nothing but open the options menu again, e.g.
runOnUiThread(new Runnable() {
#Override
public void run() {
openOptionsMenu();
}
});
Override onPrepareOptionsMenu(). Check if the flag is set. If it is, then add your two additional menu items and un-set the flag. You'll need to do some additional work to prevent the "add more items" menu item from continuing to add new items every time its pressed, unless that's the behavior you're looking for.

Android Activities, Tabs, Back Button

I am writing my first Android app. It's a port of an iPhone app which has 3 tabs at the bottom, call these A, B and C. Tab A has 4 child activities (A1, A2, A3, A4) , tab B has 3 child activities and Tab C has 2 child activities.
For the Android app, I don't really want to show the iPhone style tab bar at the bottom. In fact I'd rather have no tab bar at all (so I can use more of the screen) and instead use the Menu button to swap between activities A, B and C.
I'm really struggling to choose the best method to implement this which will also need to handle the back button correctly.
I've read the Android developer notes on Activities and tried this out (using the intent flags to disable the 'slide left' effect) This works for switching between A1, B1, C1, but if you've navigated A1, A2, then C1 i don't know how to make the Back button go to A2 (it goes to A1)
I've also read about using Tabs and tried a test with this. However the back button is not handled and simply exits the app. I realise I can handle the Stack myself and override the Back button and that I'll need to use ActivityGroups. But I've not found any good examples of how to handle the back button in the ActivityGroup and also read that theres a bug in handling the back button if one of the Activities in the Group is a ListActivity, which I also intend to use.
Any help or pointers would be appreciated to help get me started.
If you use TabHost it's quite hard thing to handle and I wouldn't recommend that
If you use Context Menu than calling each activity normally (!not withing activity group) should put the Activity to the Activity Stack and make standard functioning of Back button available.
Alternatively you can imitate bottom menu just by a separate menu View which you include to all the layouts which will avoid TabHost limitation but will give the same look.
This is how I go about using the menu button. In your main activity have something like this:
First, make a new android xml file and set the type to menu (its one of the dropdowns in eclipse), then the menu.xml file will automatically be made in the right place.
Open up the layout, and add your 3 items (one for each page you want to switch to)
// Menu button pressed
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.page1:
startActivity(new Intent(this, page1Activity.class));
break;
case R.id.page2:
startActivity(new Intent(this, page2Activity.class));
break;
case R.id.page3:
startActivity(new Intent(this, page3Activity.class));
break;
}
return true;
Where page1Activity and the rest are the other classes.
Make sure that in your Id section of the layout you have #+id/page1, etc...
Just add those activities to your manifest and it should work. The back button works fine with this (though I havent tried with a listview. With a listview you should just have a finish(); when you select something to avoid multiple lists)
To switch subpages use something like this:
public void page1aPressed(View button) {
Intent nextPage = new Intent();
nextPage.setClassName("com.example",
"com.example.page1a");
startActivity(nextPage);
When you press back it just goes to the previous activity. Maybe I'm thinking of this wrong but it works for me.

Categories

Resources