Switch case, getText of the case android - android

I have a simple switch case:
switch (view.getId()){
case R.id.one:
break;
case R.id.two:
break;
}
What I would like to do is write something smart and self sufficient to obtain the text value of the mentioned textviews. For example r.id.one holds text of 1, while r.id.two holds text of 2.
Whenever I press 1 I want to get it's text value.
I know it can be done by the following way:
TextView one = (TextView)findviewbyid(r.id.one);
one.getText();
But with the increase of textviews it will be hard to maintain, as I want to use the obtained value later on.
Thanks advance to all the downvotes, really helpful.
Solution:
switch (view.getId()){
case R.id.one:
String number = (String) ((TextView)view).getText();
break;
case R.id.two:
String number = (String) ((TextView)view).getText();
break;
}
Now number receives the value from the textview. Thanks all.

Instead of a switch, you can try to get the text if the view is any TextView. For instance:
if (view instanceof TextView) {
((TextView) view).getText();
}

Try Butterknife library.
Use something like :
#OnClick({R.id.textviewID1, R.id.textviewID1)
protected void onTextViewClick(TextView textView) {
textView.getText();
}
This allows you to use the same callback function for each textview using just a simple annotation.
And makes the code more readable as well.

Related

Is there a way to write a same onclick function for multiple controls?

I have came across a problem where i have multiple text view that should have the same onclick function. I can obviously write multiple onclick but i want an optimized code.
For example i have textviews of color red and othe textviews of color blue and i want all red to have same onclick and all blue to have a same onclick function different than red.
Is there a way to achieve this in android java?
declare your click event in a variable from type View.OnClickListener and then assign it to your textviews like this:
View.OnClickListener eventVar = new View.OnClickListener() {
#Override
public void onClick(View view) {
//do what you need
}
};
textview1.setOnClickListener(eventVar);
textview2.setOnClickListener(eventVar);
textview3.setOnClickListener(eventVar);
textview4.setOnClickListener(eventVar);
Assign an id for red colour and another id for blue. And write a switch statement, if as below
switch (id)
case 0:
runAmethod();
break;
case 1:
runAnotherMethod():
break;
default:
Write a common function for your all the color textview like
private void clickOfRedTextView(){
// your code.
}
Now implement your activity or fragment with OnClickListener listener and pass the on click
textviewred1.setOnClickListener(this);
textviewred2.setOnClickListener(this);
// so on ...
In the override method of onclick you can have a switch case with view id as follow.
public void onClick(View v) {
switch (v.getId()) {
case R.id.textviewred1:
case R.id.textviewred2:
so on....
// your function you want to call will come here.
clickOfRedTextView();
break;
}
}
You can use this simplest way:
Define your onClick in your xml file for your red type textviews and blue type textviews like this.
<TextView
//other attributes...
android:onClick="redTextViewMethod"/>
<TextView
//other attributes...
android:onClick="blueTextViewMethod"/>
And then define the redTextViewMethod method in your corresponding Java file like this
private void redTextViewMethod() {
//your code
}
private void blueTextViewMethod() {
//your code
}
Solution:
First, create common public method for getting TextView click,
public void onTextViewClick(View v) {
switch (v.getId()) {
case R.id.VIEW_ID:
case R.id.VIEW_ID:
case R.id.VIEW_ID:
// Performs action for Blue Text View
break;
case R.id.VIEW_ID:
case R.id.VIEW_ID:
// Performs action for Red Text View
break;
}
}
Then, in your xml write TextView onClick like this,
<TextView
...
android:onClick="onTextViewClick"/>

Multiple GridLayouts, each one contains TextView with same ID, retrieve only this inside specific GridLayout

I got 16 GridLayouts and inside them I got one TextView with same ID for each GridLayout. I want to find only this TextView which is inside of gridLayout1 or gridLayout2 etc. Is that possible?
switch (view.getId()) {
case R.id.gridLayout1:
findViewById(R.id.textView)
case R.id.gridLayout2:
findViewById(R.id.textView)
....
case R.id.gridLayout16:
findViewById(R.id.textView)
If you perform findViewById on the specific GridLayout, you should be able to find that specific TextView.
Try this code:
switch (view.getId()) {
case R.id.gridLayout1:
view.findViewById(R.id.textView);
break;
case R.id.gridLayout2:
view.findViewById(R.id.textView);
break;
....
case R.id.gridLayout16:
view.findViewById(R.id.textView);
break;
But notice that actually you don't need this switch statement.
If you want to get the textview inside gridLayout1 just use
gridLayout1.findViewById(R.id.textview);

Spinner selected string dependent on language used in switch case

I have a Spinner on my Activity with items "hello" and "goodbye" for user to choose. These items, when device is in Spanish, would be "hola" and "adios", as strings are chosen from string-es/ instead from string.
The problem is that I've got many switch cases on my code like this:
switch(spinnerSelectedItem){
case "hello":
case "hola":
//do something
break;
case "goodbye":
case "adios":
//do something else
break;
}
I've tried to create a final String initialized with string resource, but it complains saying "Constant Expression Required"
final String resHello = getResources().getString(R.string.helloText);
final String resGoodbye = getResources().getString(R.string.goodbyeText);
switch(spinnerSelectedItem){
case resHello :
//do something
break;
case resGoodbye :
//do something else
break;
}
This is a simplified version, I have many more items and more than two languages
One solution would be to use strings id instead of value, or use if clauses instead of switch, but I would like to find a "smart" or "clean" way to do this, do you have any idea?
You can use the getIdentifier method of Resources to get the id of the string. eg:
getResources().getIdentifier(resValue, "string", getPackageName())
This will return the id which you can then use in your switch statements and compare.

How do you reference strings from strings.xml in code?

I'm using the following code to update an image switcher and corresponding strings when the next button is clicked,but I'm having trouble referencing the strings from the res/strings folder in the GetMyString().
For example one of my strings is named cutString.How do I reference it instead of YOUR_STRING_01? Is there a simple way to do call the string or is there a flaw in this implementation?
btnNext.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
currentIndex++;
// If index reaches maximum reset it
if(currentIndex==messageCount)
currentIndex=0;
imageSwitcher.setImageResource(imageIds[currentIndex]);
tView.setText(getMyString(clicks++));
}
});
//method called to update textview strings.
public String getMyString(int variable){
switch(variable){
case 1:
return YOUR_STRING_01;
break;
case 2:
return YOUR_STRING_02;
break;
case 3:
return YOUR_STRING_03;
break;
}
So I notice that your implementation doesnt necessarily have reference to a context so you will need to do something like this.
//method called to update textview strings.
public String getMyString(final int variable, final Context applicationContext){
switch(variable){
case 1:
return applicationContext.getResources().getString(R.string.something);
break;
case 2:
return applicationContext.getResources().getString(R.string.something2);
break;
case 3:
return applicationContext.getResources().getString(R.string.something3);
break;
}
}
You can access Strings stored in the strings.xml via the getString() function.
Example:
XML file saved at res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello!</string>
</resources>
This layout XML applies a string to a View:
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
This application code retrieves a string:
String string = getString(R.string.hello);
You can use either getString(int) or getText(int) to retrieve a string. getText(int) will retain any rich text styling applied to the string.
use either String str = getResources().getString(R.string.cutString); or String str = getString(R.string.cutString);
both options are part of Context - http://developer.android.com/reference/android/content/Context.html
You reference your string as any other resource, using R class, i.e.:
R.string.cutString;
To get value, use getString():
String text = getResources().getString(R.string.cutString);
Every class that inherits from the Context class has a method called getString, which you can use to retrieve your value.
Assuming that btnNext is inside your activity you just have to call
getString(R.string.cutString)
and the result should be that value of your string.
See http://developer.android.com/reference/android/content/Context.html#getString(int)
Rather than returning a String from getMyString(), why don't you return the resource ID (R.string.cutString) and then use TextView.setText(int resid) to set the text. Essentially, you should just change the return type of getMyString() to int and the return value from the switch statement to something like this:
public int getMyString(int variable){
switch(variable){
case 1:
return R.string.YOUR_STRING_01;
break;
case 2:
return R.string.YOUR_STRING_02;
break;
case 3:
return R.string.YOUR_STRING_03;
break;
}

radio button activity source code

This method is called at button click because of assigned name to the
"OnClick property" of the button,what should be the correct code of case in below coding.it giving error that it should be constant expression in case.
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
RadioButton AButton = (RadioButton) findViewById(R.id.radio0);
RadioButton BButton = (RadioButton) findViewById(R.id.radio1);
if (text.getText().length() == 0) {
Toast.makeText(this, "Please enter a valid number",
Toast.LENGTH_LONG).show();
return;
}
You must be using this code in a project that will be marked as library. Is It?
If yes, then you must need to understand that in this case view.getId() value can not be used as constant.
In such projects, you can use if else statements.
The reason behind this is, in the main project if you would have defined a resource with the same id, there would be wrong result returned or initialized.
So, this is to avoid that situation as it would be more difficult to debug.
Use, if - else statement.
Also, I dont remember the ADT version, but after that view ids are not considered as the constants.
Just convert your switch case statement to if statement and it should suffice. For explanation read switch case statement error: case expressions must be constant expression

Categories

Resources