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;
}
Related
I have one textview and one button ,i coud change textview text with below code :
final Textview c_tv_matn;
Button c_btn_dokme;
c_btn_dokme = (button) findviewbyid(R.id.btn1);
c_tv_matn = (Textview) findviewbyid(R.id.txt1);
c_btn_dokme.setonclickListener(new OnclickListener() {
#Override
public void onClick(View v) {
c_tv_matn.SetText("this is second text");
});
But i wanna change text from String.xml and make Next Button Like this ;
"matn_1","matn_2"matn_3"matn_4...
STRING.XML
<string name="matn_0">Hello world!</string>
<string name="matn_1">You are hero john</string>
<string name="matn_2">you can change this world</string>
<string name="matn_3">You are so clever</string>
cAN YOU HELP ME TO GET RES FROM STRING AND CHANG TEXTVIEW TEXT WITH NUMBERS?
cAN YOU HELP ME TO GET RES FROM STRING AND CHANG TEXTVIEW TEXT WITH NUMBERS?
You can use either getString(int) or getText(int) to retrieve a string. getText(int) retains any rich text styling applied to the string.
But in this case you'll use getString(int) that returns the string value associated with a particular resource ID. It will be stripped of any styled text information.
Sometimes you'll need a context like on this case that you want to do it inside a Button then you can get the context from your View, or if you have a global context in your Activity/Fragment you can use it also.
Example
If I did not misunderstood, what you want is to put the text from Strings.xml to TextView, so you can do it like this :
final Textview c_tv_matn;
Button c_btn_dokme;
int textNumber = 1;
c_btn_dokme = (button) findviewbyid(R.id.btn1);
c_tv_matn = (Textview) findviewbyid(R.id.txt1);
c_btn_dokme.setonclickListener(new OnclickListener() {
#Override
public void onClick(View v) {
switch(textNumber){
case 1:
c_tv_matn.setText(v.getContext().getString(R.string.matn_1))
textNumber++;
break;
case 2:
c_tv_matn.setText(v.getContext().getString(R.string.matn_2))
textNumber++;
break;
case 3:
c_tv_matn.setText(v.getContext().getString(R.string.matn_3))
textNumber++;
break;
default:
textNumber = 1;
c_tv_matn.setText(v.getContext().getString(R.string.matn_1)
break;
});
To get the String from string.xml you need a Context.
An Activity is a Context so, if you are in an Activity you can just call getString(R.string.<the name in string.xml>) to retrieve the String you need.
For example getString(R.string.matn_0).
Then it can be applied to your needs:
c_tv_matn.SetText(getString(R.string.matn_0));
If you are not in an Activity then you need to get hold of a Context, probably passing it in as a parameter to the constructor of the class (and store it as an attribute) or as a parameter to the method that will do the setting of the text.
Create an array in an Android XML file
you need an array in string.xml. For reference please have look on below link
https://www.homeandlearn.co.uk/android/grid_view_array.html
My app prints chars to a custom view and I can set the color of printed chars with the following:
public void setColor(){
curColor++;
int NUMBEROFCOLORS = 5;
curColor = curColor % (NUMBEROFCOLORS -1);
switch(curColor){
case 0:
paintTxt.setColor(Color.GREEN);
break;
case 1:
paintTxt.setColor(Color.BLUE);
break;
case 2:
paintTxt.setColor(Color.RED);
break;
case 3:
paintTxt.setColor(Color.YELLOW);
break;
case 4:
paintTxt.setColor(Color.MAGENTA);
break;
case 5:
paintTxt.setColor(Color.WHITE);
break;
}
}
And then use it on the onClick method of a button:
colorChanger.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
myCustomView.setColor(); //this changes the color of chars that are being printed to the custom view
// myEditText.setText(myCustomView.getColor()); // This doesnt do anything
}
}
);
}
The bellow works fine, however I would also print the current color in an EditText. Say when White is set, print something like "Current color: White" and so forth.
I can use something like:
myEditText.setText(myCustomView.getColor());
It doesnt work. I'm aware I'm not doing things as they should be done, still a beginner.
creating a getter the calling the code above, crashes the app :
public int getColor() {
return curColor;
}
The log :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.esqmo.apps.digitalraineffects, PID: 11373
android.content.res.Resources$NotFoundException: String resource ID #0x1
Please advice me understand how I can achieve this.
From the error, it looked like setText is String, but getColor return int.
So you have to change your code to
myEditText.setText(myCustomView.getColor()+"");
or to this
myEditText.setText(Integer.toString(myCustomView.getColor()));
To prints color name instead of int in editText
String colorName = color(myCustomView.getColor());
myEditText.setText(colorName);
public String color(int colorNum)
{
String color;
switch(colorNum) {
case 0:
color = Color.GREEN;
......
break;
case 1:
.....
break;
}
return color;
}
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.
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.
Android 2.3.3
I have a table with N rows and N columns. For each row, I should add 4 buttons dynamically, and later do actions based on the button clicked. I know we can set the button IDs with Integer values with button.setID(), but I want to know whether we can set IDs as string values as we set in XML files, such as btnXYZ1 and btnXYZ2 etc.,
You can use tags for that purpose . For example
btn.setTag("btXYZ");
for (int i=0;i<nob;i++) {
Button btn = new Button(this);
btn.setId(i+1);
btn.setText("Button"+(i+1));
btn.setOnClickListener(btnclick); <<<<<<<set click
btn.setLayoutParams(lprams);
dynamicview.addView(btn);
}
And add this listner outside the any method and inside class
OnClickListener btnclick = new OnClickListener() {
#Override
public void onClick(View view) {
switch(view.getId()) {
case 1:
//first button click
break;
//Second button click
case 2:
break;
case 3:
//third button click
break;
case 4:
//fourth button click
break;
.
.
.
default:
break;
}
}
};
The strings you use in your XML files correspond to an int in R.java, and are hence actually ints. The setId() method will only accept an int value as an argument. You could define your IDs in a constants file, something like:
public class Ids {
public static final int ID_ONE = 1;
}
and then use it as:
button.setId(Ids.ID_ONE);
No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value
No you cannot set it to String, the id is int value, even when you set it from XML it is just the resource name of an int value
If you have the references to the views anyway , you can simply save them all into a HashMap, for example using HashMap .
Another alternative , so that you will avoid any typos , is to have an enum as the key of the hashMap , for example : HashMap .