Use string from MainActivity.java in activity_main.xml - android

I have a string defined in MainActivity.java:
public String counter1 = String.valueOf(e.getCount());
I would like to use this string in activity_main.xml as:
android:text="#string/counter1"
As you can tell I am very new to this so basic steps would be appreciated.
Thanks

Short answer: you cannot. The resources you set in your xml layouts must be statically defined in resources files, like.-
<string name="counter1">COUNTER VALUE</string>
To dynamically define new strings, you must set them programmatically.-
TextView textView = (TextView) findViewById(R.id.textViewId);
textView.setText(counter1);

What do you want to do if you could get this to work? If you want to set text dynamically, you can use setText:
yourTextView.setText(counter1);

If you want to set something programmatically which you can... you should use
txtview.setText(yourString);
if you want to set a String in XML then you either set it in the XML like you did
android:text="Exercise Name"
or using strings which then you can use programmatically as well
in strings:
<string name="Delete">Delete</string>
in code you can call it with R.string.Delete or getString(R.string.app_name);
of course you can also set from strings in XML with #string...
by the sound of what you are trying to do, you want the TextView to change while program is running so the first option would suit you well

you can not,if you want to acheive this kind of solution:
create string in strings.xml
<string name="counter1">value of counter</string>
and if you want to set the text of counter dynamically then in you activity:
TextView tView = (TextView) findViewById(R.id.textViewId);
tView.setText(counter1);
you should follow this,because all static strings shoul always be defined in strings.xml

Related

Set text colour in strings started min SDK version 7

I have this line in my code.
String credit= "<font color='#0166b9'>Credit: </font>";
I need to get "Credit: " string from my resources, because It can change depended of device default language. So how I can use value of some variable in this line ?
EDIT:
I must have only one word or some text coloured. It means that I must have different coloured TextView.
There is some way to set colour in your R.strings , here is the example
<string name="clients_credit"> <font fgcolor="#0166b9">Credit: </font> </string>
But it works only for latest versions. So it'll be great to find some way to setting colour in string.xml.
Use can use Html.fromHtml();
You can define your string in string.xml as
<string name="title"><![CDATA[<font color='#0166b9'>Credit: </font>]]></string>
And in java file you need to use spannable text
textView.setText(Html.fromHtml(getResources.getString(R.string.title)), TextView.BufferType.SPANNABLE);
You can do this :
Textview tV;
// Initialize textview
tV.setText(R.string.credit);
tV.setBackgroundResource(R.color.background_color);
tV.setTextColor(getResources.getColor(R.color.text_color));
Add Credit: to your strings file and then retrieve it later on like getResources().getString(R.string.credit) and add colour like getResources().getColor(R.color.textColour). Add
<color name="textColor">#0166b9</color>
to your color XML in res folder. If you don't have one create one.
Put file named colors.xml under res/values of your Android project.
Declare the color in that file
<color name="myColor">#ff0166b9<color>
Declare the string in strings.xml under res/values
<string name="credit">"Credit: "</string>
In your Activity, get reference to TextView defined in activity layout using the
textView = (TextView) findViewById(R.id.idOfTextView);
and then use the following to set the string and text color.
textView.setText(R.string.credit);
textView.setTextColor(getResources().getColor(R.color.myColor));
Hope this helps.
I found the solution. Here is it.
TextView debitTxtView = (TextView) view.findViewById(R.id.txtViewclientDebit);
final Spannable clientsDebit= new SpannableString(mContext.getString(R.string.clients_debit));
clientsDebit.setSpan(new ForegroundColorSpan(mContext.getResources().getColor(R.color.blue)), 0, clientsDebit.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
debitTxtView.setText(clientsDebit);
debitTxtView.append(" " + file.getDebit());

String size and font change in string.xml file

In my android application, i have to write a string into a file. Before that I want to format the string to make the font bold and have a new text size. So I modify the string.xml by
"<string name="file_title" ><b>#title*</b></string>",
for bold the text and wrote to text file. But it is not showing as bold in the file.
Is that right method i used to implement the string bold?
Also i want to know how to change the text size of a string direct
from string.xml
how to add that boldness in file... i tried
"<string name="note"><![CDATA[<b>title</b>]]></string>"
in java code get your string
yourtextview.setText(Html.fromHtml(getString(R.string.note)));
by using texview it"s coming bold , exaclty i want to write to file, using the below code
"bufferWritter.write(String.valueOf(Html.fromHtml(getString(R.string.note))));"
but i can"t see the boldness in my print.txt file...
Thanks & Regards
Anoop
You Should try to use dimens.xml for dimension values
then reference it #dimen/yourDimensionName
Refer this link for
Or other way is using HTML from java code
I tried this is working.
In your string.xml file try this
<string name="test"><![CDATA[<b>test</b>]]></string>
In your java code settext this string value from string resource like this
textview.setText(Html.fromHtml(getString(R.string.test)));
Its working fine....
Try this
in string.xml write like this
<string name="note"><![CDATA[<b>title</b>]]></string>
in java code get your string
yourtextview.setText(Html.fromHtml(getString(R.string.note)));
This is not the right way. Just change its size from xml directly. use.
android:text="Date"
android:textStyle="bold"
android:textSize="xdp"
In order to do that, you should have your xml resource as:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="file_title"><b>title*</b>!</string>
</resources>
And then use:
Resources res = getResources();
String text = res.getString(R.string.file_title);
CharSequence styledText = Html.fromHtml(text);
In order to change the text or other parameters, you can add a <span></span> with specific css style around your text.
For more information please check here: http://developer.android.com/guide/topics/resources/string-resource.html
Hope this helps!

how can i reference something in the /values/strings.xml file programatically?

i had some items in my strings.xml file that i want to change programatically, and originally i was doing it through a setText();call but now i am attempting to translate my app to a different language which means everything needs to be set in my strings.xml file. is it possible to put all the text for my app into a strings.xml and change things programatically through references to the string names, instead of using the setText() function call? for example how would i reference "GrandTotal"?
<string name="GrandTotal">Grand Total:</string>
<string name="choose_prompt">Choose a Mode</string>
You can use setText(R.string.GrandTotal);
If you don't have the possibility to set the text via resId directly you can use getString(R.string.GrandTotal);
To avoid confusion between resourceIds and real ints, you could also use statements like
String s = getResources().getString( R.string.grand_total );
but for most ui methods an overload often provides support for passing directly resourceIds as #Keyboardsurfer said
Try this way . I hope it helps you .
setText(getResources().getString(R.string.GrandTotal));
in an Acrivity:
String str = getString(R.string.choose_prompt);
or
String str = this.getString(R.string.choose_prompt);

Loading data to TextView in Android

I have a XML tag like "Yes,No,Dontknow " and I am parsing the XML file and getting the data. Now I need to display each option in separate TextView, i.e: 'yes' should be displayed in one TextView, 'No' should be displayed in another TextView, and 'Dontknow' should be displayed in another TextView, but how can I do this, can anyone give me some idea (I am new to Android).
Use setText() method of TextView to load text into it.
You can use string tokenizer:
StringTokenizer tokens = new StringTokenizer(theString, ",");
while( tokens.hasMoreTokens() ){
String token = tokens.nextToken();
// here you must have the reference to the text view...
textView.setText(token);
}
If you are creating the text views programmatically, then you must create or reference those text views inside the loop. Other wise, if the text views are static, you better put each token inside an array or something (words[0] will be Yes, word[1] will be No, etc) and then you set those strings manually.
You can just declare 3 separate TextView in you Activity layout file. Using attribute android:text you can assign the text for the TextView.
Example:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Yes"
/>
parse xml file store that in a string.take an array like String[] array = parsedstring.split(","); then take 3 text views ,put array[0],array[1],array[2] on to textview
If you want to split comma-separated strings, take a look at using java.util.StringTokenizer. You can tell it to use , as the token separator.

Change Layout Of Text Created In Java [Android]

Ok right , i asked how to create a random number from 1-100 for android and i came to this
TextView tv = new TextView(this);
int random = (int)Math.ceil(Math.random()*101);
tv.setText("Your Number Is..."+ random );
What this does is create the default kinda "hello world" style text view and says "Your Number Is.... [Then Random Number]
My problem is that i cant change the layout of this text , because it is not defined in XML, if someone could tell me how to change the style , or like make the random number into a string so i could use it for any Textview layout that would be great ..
Thanks :)
If by change the style you mean the text color, text size, and you want to change them programmatically, have a look at the setTextColor and setTextSize methods.
More info here
If you want more advanced formatting to set programmatically, see this link.
The below example demonstrates how to make your text bold and italic.
tv.setText("Your Number Is..."+ random, TextView.BufferType.SPANNABLE );
Spannable myText = (Spannable) tv.getText();
myText.setSpan(new StyleSpan(android.graphics.Typeface.BOLD_ITALIC),0,myText.length(),0);
Edit:
Try the below for the android:textSize="100dp" and android:gravity="center" :
tv.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 100);
tv.setGravity(Gravity.CENTER);
Putting it into a string is easy.
String randomAsAString = Integer.toString(random)
You can then use the XML properties of the TextView to change its formatting, such as android:textSize="30dp" or android:textColor="#900".
By the way, if you're happy with the answer to your previous question, you should go back and mark an answer as "Accepted". That gives 'reputation' points to the person whose answer you accepted and closes the question so that people don't think you're still waiting for a better answer. You can read more about reputation in the FAQ.
Edit:
You can't reference the string entirely in xml while still giving it a random number. This is because the "#string/some_string" format only allows unchangeable strings. The execption to this is using parameters, e.g. setting the string as
<string name="random_number">The random number is %d</string>
Then you could call up that string using something like
yourTextView.setText(this.getString(R.string.random_number, random))
As for your other question about setting a background to a textView, that's also easy.
yourTextView.setBackgroundDrawable(R.drawable.....)
You should take advantage of Eclipse's autocomplete feature... it makes finding these commands a lot easier. For example, simply type the name of your TextView followed by a period, pause half a second for the list of options to come up, then "setB" and it should then filter the list to the three setBackground Drawable/Resource/Color options.
tv.setText(Html.fromHtml("Your number is: <b>" + random + "</b>"));
For basic HTML text-styling tags.
You could also do something like this.
Define your string in strings.xml like:
<string name="your_number_is">Your number is <xliff:g id="number">%s</xliff:g>.</string>
Create a TextView in a layout xml:
<TextView android:id="#+id/your_number_is"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/your_number_is"
android:gravity="center"
android:textSize="100dip"
/>
Then your code would look like:
TextView tv = (TextView) findViewById(R.id.your_number_is);
int random = (int)Math.ceil(Math.random()*101);
tv.setText(getString(R.string.your_number_is, random));
This will make it a lot easier when you later on would like to change your text or maybe localize your app.
if you have thead troubles use this:
new Thread(){
public void run(){
TextView v = (TextView)findViewById(R.id.mytext);
v.setText("TEST");
}
}.start();

Categories

Resources