Dynamically change Options Menu Items in Android
We moved. Please visit this link for this post.
Sometimes need to change, add, delete options menu items dynamically after some event or after some situation in application flow.
We all know onCreateOptionsMenu method which helps to create options menu for activity. But in this situation it doesn’t help.
For this situation I use public boolean onPrepareOptionsMenu(Menu menu).
I will show short example which you can copy t your IDE and check my words.
Only one note for this method: don’t forget to clear menu items (menu.clear();) on every method start.
Example:
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* Class which shows how to change dynamically options menu items
*
* @author FaYna Soft Labs
*/
public class Main extends Activity {
private Button clickBtn;
private boolean isChangedStat = false;
private static final int MENUITEM = Menu.FIRST;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
clickBtn = (Button) findViewById(R.id.click);
clickBtn.setText("Click me");
clickBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(isChangedStat) {
isChangedStat = false;
} else {
isChangedStat = true;
}
}
});
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
menu.clear();
if(isChangedStat) {
menu.add(0, MENUITEM, 0, "True");
} else {
menu.add(0, MENUITEM, 0, "False");
}
return super.onPrepareOptionsMenu(menu);
}
}
In this example I change after button click text in options menu item. It is very simple example. You can modify it for your problem. For example add, delete options menu items.
Why I recommended to clear menu? If you will not clear menu then after every click you will have plus one menu item.
Try to comment and you will see what I mean.
Hope this article was useful for you.
hey … nice tutorial … helped me in my project …. i want to open up options menu by clicking upon my own created button … is it possible ? if so, please help me out … thanks in advance
Hi.
I didn’t try this. I need to investigate. But at this time please visit this link with some solution for you (http://www.anddev.org/viewtopic.php?p=1850)
hey thanks for your reply … is it possible to open up a context menu without having to click a view?
Hi.
Unfortunately no. You need always call method registerForContextMenu(View view). This type of menu is showing only after pressing on some View.
hey … you are really helpful … i want to display a list which has exactly the same view as a context menu has …. is there a way to do this ? please help me out …
Sure. It is possible. I don’t have tutorial for this yet, but I made it from this link http://developer.android.com/guide/topics/ui/dialogs.html#AddingAList
I will create post for this, as soon as I will have time for this.
Don’t forget that I moved The Developer’s Info to http://thedevelopersinfo.com.
thank u so much … this is exactly what i was looking for …
You are welcome.
I am glad that I can help you.
i am facing one problem … i need to get a button like one in android phone’s home screen that slides up to show the menu items, when clicked and when clicked again slides down. i was wondering if you can help me out.
I can’t provide detailed steps.
I think you should implement own view component with button and listview. It is not hard, but you should find good tutorial about how to use animation and listview.
Maybe details you will find on community forums like http://www.anddev.org/.
Thanks for your help.
do you know how to record incoming and outgoing calls on android device?
What do you mean?
You want to record voice or call length or what?
i want to record the whole conversation. i have been exploring on google and i have come to know that its not possible. Is it right? What if we use MediaRecorder class somehow to get this done? There is a solution for every problem but i am not mature enough to find a solution for this problem. I hope you can figure it out …
Hmm.
I think you can try to do this.
G1 had limitation for recording – the caller voice is not recorded.
But I found in android 2.1 api (http://developer.android.com/reference/android/media/MediaRecorder.AudioSource.html) VOICE_CALL constant which should help you.
Read how to handle audio http://developer.android.com/guide/topics/media/index.html#capture
Also you need to read these 2 posts about how to handle incomming calls
http://www.anddev.org/call_handling-t996.html
http://www.anddev.org/recognize_incoming_phonecalls-t133.html
In my point of view you can implement this task.
For me it is very interesting and personally I will try to investigate this on next weekend.
Thanks Oleg … i am already working on this VOICE_CALL constant.
I will let you know if i appear on a conclusion.
Ok. Thanks. I will be waiting.
hey Oleg …. I am using this code but could not find any audio recorded nor do i get any exception. I have added the in manifest.xml file.
public class AudioRecord extends Activity {
private final static String TAG = AudioRecord.class.getSimpleName();
private MediaRecorder recorder;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
recorder = new MediaRecorder();
button = (Button)findViewById(R.id.button);
button.setText(“start”);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
buttonClicked();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
private void buttonClicked() throws IOException {
if (button.getText().equals(“start”)) {
try {
recorder = new MediaRecorder();
String path = “/sdcard/test.3gpp”;
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(path);
try{
recorder.prepare();}
catch(IOException e){
e.printStackTrace();
}
try{
recorder.start();
}
catch(Exception e){
e.printStackTrace();
}
Toast.makeText(this, “start”, Toast.LENGTH_LONG).show();
button.setText(“stop”);
} catch (Exception e) {
Log.w(TAG, e);
}
} else {
try {
try{
recorder.stop();
}
catch (Exception e){e.printStackTrace();}
recorder.release(); // Now the object cannot be reuse
button.setEnabled(false);
Toast.makeText(this, “stop”, Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.w(TAG, e);
}
}
}
}
I created 2 posts about how to capture audio in Android.
Visit this link
http://thedevelopersinfo.com/category/android/android-how-to/android-multimedia/
Hope they will help you
hey OLEG … i am able to record only my voice during the conversation using MIC constant. VOICE_CALL constant doesnt work.
Hod did you test VOICE_CALL? I mean did you call from emulator/phone to emulator/phone?
i called from phone to phone
I found old post on google forum.
It depends of phone model.
Need to investigate…
Hey Oleg … now i am working on augmented reality … i am able to put a view on top of camera view … but there is a problem with my HTC magic. when we open camera programmatically, it is opened in landscap mode. i changed the orientation by using
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
but it also changes the orientation of my view that i am adding on top of camera view. Can you help me out?
As I understand you want that your view should start in landscape mode and camera in portrait.
Am I right?
no i want both views on portrait mode. By default camera view is landscape and my view is portrait. if i change the screen rientation to Portrait, camera view becomes portrait but now my view is rotated by 90 degree to landscape mode.
Try add this to AndroidManifest android:screenOrientation=”portrait” or android:screenOrientation=”behind”
<activity android:name=".Main" android:label="@string/app_name" android:screenOrientation=”portrait”>
Delete sendRequestedOrientation() method.
How it works in emulator? Maybe it is a feature of your HTC Magic.
I will be waiting the result from you.
Doesn’t make any difference. Camera view is still rotated.
Please read this thread.
already went through this thread …. no change
hey Oleg … im creating an alert dialog with list of multi choice items. when i click ok, how do i get the checked items?
See here. Pay attention at Adding checkboxes and radio buttons. There is an example which shows how to get selected item from radio button. You need to modify for checkboxes. I recommend to add items to the array list.
i went through this link … i thought the same way as you suggested. Problem arises when user unchecks the item. In this case, I have to remove the item from the list. Its not that difficult but i was wondering may be there is built in method to check for items selected. Thanks for you help.
Is it possible to implement a count down timer inside an alert dialog. I guess i have to implement onPrepareDialog().
My recommendation is to create own custom dialog.
Done !!!!
I created an alert dialog and started a new thread from onCreateDialog(int) method.
It is cool
Hey Oleg …. its me again …
i want to create a list view .
each row consists of two lines …. one for list item’s title, which is bold, and one for its description, which is shorter in size.
can u help me out? plzzz
Yes sure.
Where is your problem?
i dont know how to specify different formats for item’s title and description.
You need to use style attribute in item layout
Example:
<TextView android:id=”@+id/itemName” … style=”@style/MainMenuRowText” />
res->values->styles.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<resources>
<style name=”MainMenuRowText”>
<item name=”android:textSize”>22sp</item>
<item name=”android:textColor”>#FFF</item>
</style>
…
(your other style specific values here)
<resources>
Hey Oleg …. Looks like i couldnt explain my problem … The solution you suggested can be used to set a format for a row of a list. Right?
what if i am using two text views in a row? both should have different text sizes? how to do that? i am struck. ..
You create layout for your row. In this layout you need to create 2 TextView. For every TextView component you need specify own style, as I showed previously.
Oleggggggggg …. Done !!!!! Thanx for your help
You are welcome
i want to open options menu when i click on a button. i can do this by calling openOptionsMenu method in onClick method. Now i want to animate my button on top of options menu and when i click the button the menu should be closed. how to do that? options menu gets closed when i touch anywhere on the screen. i dont want that.
Hmmm.
Very interesting task. Unfortunately I haven’t found a way for creating modal options menu.
I think you can’t do this… Try to ask on the forums.
Hey Oleg … I created a FrameLayout. Added Camera View and a button in it. Now i can view a button on top of camera view. But the problem is i dont know how to change the location of the button? it always appears on top left corner while i want it to appear at bottom. I tried button.setGravity(Gravity.bottom), but it doesnt work. I also tried to set padding but
Try to modify button in layout by using
<Button android:id=… android:layout_gravity=”center” />
I am developing a game … i have to switch between activities … i want to display game time throughout the application … how to do that?
If you need to show this time only at game activity use Thread for showing.
When you need to switch to other activity then save this value.
Thanks Oleg … i want to do simple android projects to earn some money and also to enhance my learning in Android platform. Can you help me out? Where to find such simple projects?
In my point of view, you have to chose area where you want to work (multimedia, games, security, etc). After that you need to investigate applications which are there (sometimes I use androlib.com as application manager). And after that need to start to develop application which should resolve some type of problem.
All projects start as simple “Hello, Wolrd”, but a lot of them grow to the great applications.
I think you are working on the right way.
From beginner to professional one step.
I am interested in developing games. I want to know where to get pojects from? Who will hire me and pay me for my work? I am working in a software house but the salary they are paying me isnt good enough. Don yopu know where to get start?
You can create own games and distribute them on Android Market. Or you can search on the forums about new teams and new jobs.
I heard that the condition to distribute any application on Android Market is that it must be free.
Here you can list of countries.
You can sell in Android Market only demo.
Full version user can buy in other e-shops (Handango, SlideME,… etc).
Hey Oleg … its me again … is there a way to store something in my application, close the application, and when i start the application again it is still stored.
SharedPreferences, Files, Database
I think i have to use database or files. I ve got another problem.
In my application, i want the user to login his facebook account when he starts the application for the first time and then remembers his facebook id and other informations extracted from his facebook account even after the application gets closed.
1. How to connect to facebook?
2. How to extract users information(name, sex, age etc) from his account?
hope you can help me out.
Sorry for late response.
For this type of application you should use external library.
You need to visit their Wiki
Thanx Oleg …
Oleg … here is something i found to connect to facebook
http://code.google.com/p/fbconnect-android/
i dont know how to run the code. can u guide me?
I am using FBRoket to connect to facebook but i am facing problems. Do you have any experience with FBRocket?
Nope. I don’t have any experience with this library. You need to contact with developers. Also I found example on their site. Did you try it?
fbconnect( http://code.google.com/p/fbconnect-android/ ) is working. Now i need to understand the code so that i can make changes according to my requirement. Thanks for your response. You are really been so helpful for me. Its a great thing for a beginner to have someone to guide.
In my point of view you should stay with FBRoket. It is much easier for beginners. Also I sent feedback and received response very quickly it is also very important.
fbconnect’s author is Martin Adamek. This person also creates Android plugin for NetBeans.
Anyway, my recommendation is to select library where will be communication with dev team.
i also sent him feedback regarding my problem but he didnt respond. Now i know how to use fbconnect according to my requirement but i am having problem with FQL.
i wrote a query
select uid,name,username from user where uid == ” + session.getUid()
this query returns me uid and name correctly but it returns null value for username, while i was mainly interested in getting the username. I cant figure out the problem with my code. Can you?
Read here. This note explains which fields you can get.
cant i store the login email when user enters the email and password to connect to facebook?
Did you mean store locally on the phone?
Yes you can. Use for this database.
Hey Oleg …. its time to start exploring Google Maps ….
I have radius and center point(longitude/latitude)of a circle. I want to generate some long/lat pairs within the area of that circle. There is a limit on minimum distance between the points i generate. Then i have to plot those points on map.
Today i studies a lot about maps and now i am able to draw points on the map based on their long/lat info. What is left is how to generate the long/lat pairs?
Do i have to use Haversine formula to somehow get a long/lat pair from another long/lat pair and distance?
Here I can’t help you.
I don’t have any experience with Google Maps.
No problem Oleg … I think your saturday was off, but i was working on saturday too
. Anyhow, i solved the problem.
Yes, you are right, I was not at work.
I am glad that you solved the problem.
Hey Oleg!
I wrote a php code that generates a json object. Now i want to parse this object in my java code. I know how to do the parsing after i get json string. I am not getting any idea about how to get json string from a url. Help me out
Did you read these:
Android Series: Parsing JSON data with GSON and Android JSON HttpClient to send data to PHP server with HttpResponse?
I have a php file stored on my local server. This file returns a json array. In my java code, i entered this url to access that array.
http://localhost/game.php?task=game_type
it works fine on emulator but this web page doesnt get opened when i test it on real device. In past i did xml parsing. At that time, i wrote my ip address in place of local host in the url and it worked but now isnt. i cant figure out the problem.
It was so simple. I had to change firewall settigs. Turned it off and it worked. I am such an idiot
It’s normal in development. Sometimes you forget about specific things.
Hey Oleg … I am working on google maps. May application works fine on emulator but when i load it on real device, map doesnt show up. All i can see is grey tiles. On forums, i read that the maps api key i generated from debug store wont work on real device. They say that replace debug.keystore file with your own key store file but i dint read anywhere how to generate my own keystore file. Please help me out.
Hi.
Read this.
If you will have question then notify me.
I read that article. It says “use keytool” to generate api key. It doesnt tell how to use key tool
If you use Eclipse with ADT plugin you can use other solution.
On the project right mouse click -> Android Tools -> Export Signed Application Package… -> select project -> radio button “Create new keystore” -> all other steps.
After that you will have signed application. If you want to verify then you need to use jarsigner -verify YourApplication.apk command in console. If all is good then you will see output jar verified.
this link http://code.google.com/android/add-ons/google-apis/mapkey.html tells how to use keytoll but again, it requires my own key store file and i dont know how to generate it.
i followed the steps. I created mapapi.keystore file in “C:\key store\mapappi.keystore”. Also i created .apk file of my application. what to do now? where to get map api key from? i m stuck. my head aches
Next step is to get MD5 Fingerprint. In console type:
keytool -list -alias my -keystore my_new
Enter keystore password:
my, Apr 16, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): 91:35:1E:50:4D:FD:93:C4:2B:10:02:0D:F9:4B:58:B6
This is your MD5: 91:35:1E:50:4D:FD:93:C4:2B:10:02:0D:F9:4B:58:B6.
Next you should register for a Maps API Key. Visit this link.
After that you need to add the Map API Key to your application and enable MapView elements in application.
Thanks Oleg for giving me your precious time.
No problem. Did you receive working application?
Still i am getting gray tiles. no map
Did you create new apk after receiving Maps API key?
“After that you will have signed application. If you want to verify then you need to use jarsigner -verify YourApplication.apk command in console. If all is good then you will see output jar verified.”
how to do that. when i type the above command on console it gives jarsinger not recognized error
Add %JAVA_HOME%/bin to PATH variable
i entered the new API key in my code and compiled it again but still no map shows up.
“Add %JAVA_HOME%/bin to PATH variable” in environment variable?
Yes, you need to add to your environment variables new one which called JAVA_HOME
Read how to do this.
And after that add JAVA_HOME/bin to PATH variable.
Did you add this <uses-library android:name=”com.google.android.maps” /> to your application in AndroidManifest file?
yes
yes i have added all the permissions
Very strange…
I don’t understand where is the problem.
Read this Map’s startup guide.
I recommend to create new application step-by-step.
It works now … Thanks a lot …
It is very good news
Hey Oleg … I am working on augmented reality … i want to discuss something with you.
I have my device’s location and location of another point. What i want to do is, whenever i see that location in my camera, the location’s name should be displayed.
i can find the direction of compass in onSensorChanged() method. i can also find the other location’s direction with respect to me using mylocation.bearingto(otherLocation) method. When both directions are same, then i should display the name of the location. Am i going on right way?
In my point of view you are working on right way.
Ok … thaks .. let see what happens …
I get a drawable from the web. I want to draw it on the canvas, But i can draw only bitmap image on the canvas. Is there a way to convert the image from drawable to bitmap?
ok … its done ….
i want to show a list in alert dialog. The data to be displayed in the list comes from the web server database. It works fine. The problem arises when i change the data in the web server database. onCreateDialog() isnt called again and my alert dialog keeps displaying the old data. Do you know how to solve this problem?
An easy way is to use some Thread which will ping every min your web server data. There are others methods, but you need to find yours.
its done ….
I want to show a digital clock in my game. If i use DigitalClock class, its gives me system time, it doesnt start from zero second. If i implement my own clock by creating a thread and updating time after 1 sec, it gives in consistent results.
In an activity, i am running two threads. When i switch from that activity to another activity, do i have to stop the threads or they get stopped themselves.
In my application, i need to switch between two activities again and again(one activity calls the other one). Both activities have threads running.
I am calling mythread.stop() method before switching between activities. it works a couple of times, but if i switch more than 2 times i get force close message. Can you figure out the problem?
Try to use interrupt() method instead of using stop().
Ping me when you will have the result.
It doesn’t solve the problem. I used mythread.setState() and it worked. I am getting a strange error.
I created a thread that shows game time elapsed. Outside the thread i am plotting my position and my friends position on the map. My friend’s lat/long come from an online database. Time thread works fine until i start getting data from webserver database.
As soon as my application starts updating my location on web server and getting my friend’s location from database …. during this process time thread gets slow. why is it so? any task i am doing in a separate thread should not get affected by whatever is going on outside the thread.
When i am on the first screen of my application, if i press hardware back button, the application gets closed. What should i do to prevent this?
Read this post. It should help you.
Hey Oleg … again i need your help … how to prevent the screen lock when my application is running ….
I don’t understand your question. Do you want to prevent the screen lock when you start phone or when your application is running?
how to get long/lat of a location from zipcode.
It is hard to say if you can receive long/lat only from zip code. I think you need to add also additional parameters such country or so on.
Try to use web services like Yahoo! Maps Web Services or The Google Geocoding Web Service.
p.s. From this month I don’t support this resource. If you have questions please post them on The Developer’s Info.
i want to prevent the screen lock when my application is running. Do i have to do something in code?
I have not any ideas.
In my point of view you need to change phone’s settings.
i want to show progress dialog until my activity’s on draw method gets called.
In onCreate() i used progressDialog.show() to show the dialog and in onDraw() i used progressDialog.cancel() to stop the dialog. In onDraw() methos, i am adding overlays for me and my friends.
When the activity is started, progress dialog is shown, when it comes to onDraw() method, overlay pins are shown but progress Dialog never disappears.
How to do that?
I think you need to use Handler or AsyncTask for this operation. Use onDraw() inside Handler or AsyncTask.
Why is it so that anything done in a thread slows down the overall process being performed in the activity. Am i doing something wrong?
Wrong?! I don’t think so. But need to analyze code. Try to debug your code, maybe it helps you to find bottleneck.
I am using sliding drawer in my application to provide users with options menu. when i click on the handle, it goes all the way up to the top of the screen. I want it to go upwards only till all the options are visible. How to do that?
Hey Oleg!
I have completed my first project, a real time game. In this game the players can purchase cheats from Android market. I am giving the Alpha release tomorrow, every thing is working except i dont know when users want to purchase cheats, which link to direct them? Is there a dummy account on Android market which i can use? how to charge them for the cheats? i am not getting any idea … Help me out …
Do i need to create a dummy account on Android market for testing? if so, how?
Hi. You know I think you need to contact Android Market’s administrators, because I don’t have any idea in this implementation.
Also I want to congratulate you with your first application.
Thanks Oleg. It was you who drove me through difficulties.
Is it possible to purchase something from android market within the application? There must be a sandbox for testing such applications. Is there one?
There is several application like theme changer which allows to download application’s themes. But how do they do this I don’t know. Try to read Android Market’s help, maybe there you will find answer.
right.
I have started working on my next application. This is relatively smaller but , right now, i have no idea how to proceed. I have to download images from Flickr. I am googling but what i can find is how to upload images to Flickr. Do you know how to download?
i found this link for a project that downloads images from flickr
http://code.google.com/p/background-flickr/
but i am not able to find any file that contains the complete source code
Try to use this library it should help. Also visit their dev page.