This question already has answers here:
openSearch() in Android beginners app not defined
(3 answers)
Closed 9 years ago.
So I'm basically following this tutorial to learn the basics of programming, and at respond to action buttons they have this coding:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
but they dont talk about the case part at all, and now I don't understand what to do. I think (?) i need to create a method for the opensearch() and opensettings(), but what do i put in here, and what does the case part mean?
thanks for your help!
The switch | case structure is a conditional statement. The switch receives a variable that'll be compared to one or several values. I usually think of it as an elegant way of writing if statements.
Each case is a comparison to be made to the value stored in the variable provided to the switch. In this case, R.id.action_search and R.id.action_settings are both ID's (string or number. In this case I don't know which, since I haven't used the tutorial) that must be compared to the value of item.getItemId().
The default is the action that will be performed if none of the previous case statements are met.
So, depending on the value of item.getItemId(), possible actions are either the execution of openSearch() or openSettings() (both ending with return true). But, if neither condition is met, then no methods will be executed and the value returned will be super.onOptionsItemSelected(item)
So, if you cannot find, in that tutorial, the code for those two methods, then it's most likely an abstraction thrown at you to illustrate what actions would take place if conditions in the code were met.
Its just a template by Google to show you/world about how you can handle clicks on Menu Items (Action Bar) in android.
If we talk about this particular case, then in this case they are handling the click for two menu items 1. Search 2.Settings.
To accomplish the above task they have used switch (you can also use if and else statements) to verify which item has been clicked.
switch (item.getItemId()) { // Here they are checking the Id of item been clicked
case R.id.action_search: // Here they are examining if search item is clicked
//openSearch(); // if above case satisfies, then they gonna invoke the openSearch() method.
Toast.makeText(getApplicationContext(), "Pit Bull", Toast.LENGTH_LONG).show();
return true;
case R.id.action_settings: // Here they are examining if action item is clicked
//openSettings(); // if above case satisfies, then they have invoked the openSettings() method.
Toast.makeText(getApplicationContext(), "Eminem", Toast.LENGTH_LONG).show();
return true;
You can do whatever you want to do inside these cases by replacing your own logic
e.g : You can show here a Toast Like this
Toast.makeText(getApplicationContext(), "Pit Bull", Toast.LENGTH_LONG).show();
Its good that you want to learn programming, but its necessary that you should have basic knowledge of java first otherwise it will be quite hard to understand/learn the Android.
Best of luck..
Put whatever other code you want, those are sample methods, in place of methods you can log something to logcat, as Log.w("Test", "search button clicked");
basically the case part contains the action to be performed on click of button, like you may start a new activity, print something, set a log, whatever code you want on click, you can put it in the case of that particular button.
Related
I have several objects in an activity and I would like to check their id before I perform any actions on them. However I'm not sure how to go about it, I tried :
if (v.getId().contains("empty")){
but that gives an error and then I tried
if (v.getId() == "[attr^=empty]"){
and that is also wrong. To be honest I am aware that both of these don't use proper assignments and so on but I'm really lost on how to check whether an id contains a certain substring.... I would appreciate it if someone could help
PS: v is a View object
v.getId() returns an integer. In order to check id before doing something, I'd recommend something like:
switch (v.getId()){
case R.id.ViewElement1:
//do something here
break;
case R.id.ViewElement2:
//do something here
break;
case R.id.ViewElement3:
//do something here
break;
}
What this code does is that it gets the Id of your View then compares it through a switch-case block. If the id taken from v.getId(), the code in the case block executes. The break; is important, otherwise, the code in the cases below the one executed will also run. You can also do this for an if-else if that fits your style more.
If you want to fetch the id as a string, you can try:
String ResourceIdAsString = v.getResources().getResourceName(v.getId());
and then you can do your if contains operations on the String object.
I am not entirely sure what you are trying to achieve. So there's some overview of how id works.
First you have to id all of your views in xml like:
<TextView
android:height="wrap_content"
android:weight="match_parent"
android:id="#+/myTextView" />
Then in your JAVA code use a switch case like:
switch(view.getId()){
case R.id.myTextView1:
break;
}
If you have some views that do same thing you can use them like:
switch(view.getId()){
case R.id.myTextView1:
case R.id.myTextView2:
case R.id.myTextView3:
case R.id.myTextView4:
perfomeSomeAction();
break;
}
I want to make some kinda dictionary,But not exactly a dictionary,
I have two text views, One for the word, The other one for the meaning.
I have two Buttons which they change an integer's number
And finally I have lots of if, For Example:
(if i==1){
txt1.setText("x");
txt2.setText("y");
}
(if i==2){
txt1.setText("n");
txt2.setText("m");
}
Q1: Its better with switch right?
Q2: Where should I put those Switch? In each Button's ClickListener ?
Q3: Can you suggest a better way to do that?
Switch is definitely a better option.
You can have a common API that will handle this logic like:
toggleText(int i){
switch(i){
case 1:
txt1.setText("x");
txt2.setText("y");
break;
case 2:
txt1.setText("n");
txt2.setText("m");
break;
}
}
Then u can call this API from ur button cick:
button.setOnClickListener(new View.OnClickListener{
#Override
onClick(){
toggleText(pass your value here)
}
});
Let me know if u need any help.
Switch is good option than if else
Make a function and put all switch conditions in it and call that function on button click
My android application targets the latest platform. I am new to the platform, and read bit conflicting information on actionbar. The way I was using it for navigation was.
menu.xml
<menu>
<item android:id="#+id/action_sort_size"
android:icon="#android:drawable/ic_menu_sort_by_size"
android:title="#string/action_barabc"
android:onClick="abc" />
<item android:id="#+id/action_sort_alpha"
....
In my activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void abc(MenuItem item) {
//...
}
this works, but the back/up navigation is not working correctly. could be unrelated, still like to confirm.
But, I also see implementation like here
where it switches on item.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuitem1:
Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT)
.show();
break;
case R.id.menuitem2:
....
}
Which is the better approach?
The better approach, in my opinion, is the switch approach. There aren't many reasons why, but I'll list them:
The code is centralized. You don't have x amount of methods that basically do the same thing. It keeps your code more readable; it is "cleaner". You also get a default statement using the switch, this can help if you mess up and forget to make a case specifically for an element in the layout.
If you really wanted to have a centralized method using xml, you would have onClick reference the same method and check the ids of the View parameter. Which is essentially the same asonOptionsItemSelected.
It is a part of the API. The Android engineers would not have made it a part of the API if they didn't want the developer to use it. Yes the XML is techinally API, but XML should be used more for layouts and visuals, not for logic.
Everyone uses it. All the tutorials I have seen and everyone's code uses this method. It is now more of a convention.
It's largely personal, but if it looks like it's a convention, and everyone uses it, I'd adhere to it. Especially if you're working as part of a team. Different coding styles for such arbritrary things should be avoided.
And concerning your back/up navigation, it shouldn't make a difference which way you do it, since you have to implement the same code to get that navigation type.
I cant found the topic, perhaps someone can teach me some about android effectivity when the topis is about onclicklistener for buttons.
Lets say I got 10 buttons on a page (just an example now)
What's the best thing to do?
A switch that switch id for the buttons?
A onClickListener for each button?
What method is the faster one, and why?
Is there any different at all?
Best practice is to go with 1st option: A switch that switch id for the butttons.
As per my experience, i would suggest you to assign android:onClick attribute with same value, say for example: android:onClick="btnClicker"
And now you have to implement the same method inside the activity class as:
public void btnClicker(View v)
{
switch(v.getId())
{
case R.id.btn1:
break;
case R.id.btn2:
break;
case R.id.btn3:
break;
}
}
About 2nd option:
I don't prefer it because it increase number of code lines because just think you are having 10 buttons and you assign separate click listener for each buttons. And now compare it with the above 1st option, you will realize it.
So i would suggest you to go with 1st option i have suggested with example above, main reason is it decrease number of code lines and better readability of code.
Why there is better readability in 1st option i have suggested above?
Because you know you just have to check this particular function only for the code for every buttons, because everything is here inside a function.
I would be surprised if there is any significant difference. I would go with #2 because I think it leads to clearer code.
I think answer 1 is effectivity.
because create object will slow down the app.
and the RAM limit in mobile phone should be considered.
I am new to Android application Development.
How can I identify the mouseover action for a list box? On mouse over of a particular cell I want to highlight that cell or change the background color.
Please help me regarding this.
There isn't a concept of MouseOver in Android, at least one that I know of - user interaction is done through hardware/virtual keyboard and touchscreen.
ListView automatically highlights the current selection, so when you use the up and down DPad keys, you may get the effect you want.
I know this is old but my queries kept returning to this original post so I wanted to share it here.
For what it is worth, implementing the state_hovered in your selector will NOT work for list views on mouse over events.
You can achieve this event using custom array adapter.
*This assumes you know how to create your own selector and ArrayAdapter. If not, you can find those in other Stack Overflow posts.
Create your own array adapter.
Implement View.OnHoverListener in the adapter
Override the 'onHover'method:
#Override
public boolean onHover(View arg0, MotionEvent arg1) {
int ev = arg1.getActionMasked();
switch (ev) {
case MotionEvent.ACTION_HOVER_ENTER:
arg0.setHovered(true);
arg0.setSelected(true);
return true;
case MotionEvent.ACTION_HOVER_EXIT:
arg0.setHovered(false);
arg0.setSelected(false);
return true;
}
return false;
}