View objects id - android

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;
}

Related

Android: Count number of cases in switch statement, know when last case

I am busy working on an app with multiple switch statement that each have a different number of cases.
switch(variable){
case: 0
//do something
case: 1
//do something
case: 3
//do something
I can iterate through the cases by using variable = variable +1. That works fine. My problem is being able to tell when the last case in the switch statement has been reached so that I can perform a different action.
How do I know when the count is at the last case? What is the code for that?
I appreciate your time.
You can use default case for your problem.
switch(variable){
case: 0
//do something
break;
case: 1
//do something
break;
case: 3
//do something
break;
default:
// Here you can run your different action
break;
}
You have to also define the max value for your variable so that when your variable value reaches to that max value it stops incrementing the variable value.
I think you are working inside a method or cycle
In that case you can restart the variable when it reaches the last value inside your switch
.
.
.
switch(variable){
case 0:
//do something
case 1:
//do something
case 2: //this is the last
.
.
.
//do something
.
.
.
variable = 0;
}//End of switch
.
.
.
[EDIT]
You can restart the variable in the last case of your switch.

Lots of if statements

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

What do the cases and methods mean ? [duplicate]

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.

Getting proper input for password activity

I am preparing a password activity and I want to get the proper input for it.
I am using the code
while(counter<5){
switch(counter){
case 1:pwdField();
counter++;
break;
case 2:pwdField2();
counter++;
break;
case 3:pwdField3();
counter++;
break;
case 4:pwdField4();
counter++;
break;
}
}
pwdField are the methods that contain listeners for buttons. But for some reason only the third textView receives input. It doesnt break off after the input is received. What am i doing wrong?
Moved from comments:
Why do you have the while loop? If the while loop condition is met and counter is not negative then the loop will go into a case and break out of the loop, thus only going through it once. If the condition is not met then the loop will be iterated 0 times. Why not replace the while loop with an if statement?
You may not want to have the breaks in there but I don't know the intent of this snippet.

Assign ressource dynamically vs. big switch case

I have a question regarding performance and best approach for my Android code.
What I need to do is fairly simple, I want to dynamically assign a text value to a string ressource, depending on a int parameter:
For now I am using a big switch case
int messagesCategory;
if(extras !=null) {
messagesCategory = extras.getInt("category");
}
TextView titleText;
titleText = (TextView) findViewById(R.id.headerTitle);
switch (messagesCategory) {
case 1: titleText.setText(R.string.TitleMessageList1); break;
case 2: titleText.setText(R.string.TitleMessageList2); break;
case 3: titleText.setText(R.string.TitleMessageList3); break;
case 4: titleText.setText(R.string.TitleMessageList4); break;
case ...: titleText.setText(R.string.TitleMessageList...); break;
case n: titleText.setText(R.string.TitleMessageListn); break;
default: titleText.setText("a default title"); break;
}
Let's say I have 30 lines in this switch...
It works but for many cases, it looks there is a better way to achieve this.
Unfortunately it does not look possible to assign something dynamic to R.string..
So my first question is: 1) performance wise, in this case, is it a problem to use a big switch for 30 cases or so?
2) what should be the best approach?
Thanks and have a good day
Simple,
int[] stringIds = {R.string.TitleMessageList1, R.string.TitleMessageList2,...};
int messagesCategory;
TextView titleText = (TextView) findViewById(R.id.headerTitle);
if(extras !=null) {
messagesCategory = extras.getInt("category");
if(messagesCategory <= n)
titleText.setText(stringIds[messagesCategory]);
else titleText.setText("a default title");
}
Now, there is no switch-case and comparison,, Basic Java and Android fundamentals make it to easy and short..
As R.string.XXX is an int value generated in R.java file you have to make a just int array of that values and just get value using your int messagesCategory. And directly set it to TextView..
You can also do this:
Field f = R.id.class.getField("TitleMessageList" + String.valueOf(messagesCategory));
int val = f.getInt(null);
titleText.setText(val);
It is fast without need to load all ids in the memory.
Enjoy!
switch case is the equivalent of GOTO in your code, and there is nothing to worry about with performance.
your code is fine, may not be nice but it works and it's efficient.
I don't think 30 case statements don't hurt much except you execute them in a loop, iterating over an array, and such.
Why don't you directly use the integers which R.string gives you? Is the mapping really necessary? You could pass the R.string identifiers around. Or else, you could have a lookup in an array if you're really worried about performance.

Categories

Resources