I have a viewPager that get its text from the string.xml.
The plan is, depending on the position of ViewPager, it gets the text from strings, for example if the user is in page 3 it should get text from string name="page3".
the important issue is I want to write my code in layoutInflater not in Activity.
here is the code that works just in Activity:
String name = "page" + position;
int id = getResources().getIdentifier(name, "string", getPackageName());
tv.setText(id);
As per your code, you are getting identifier means id of particular string in R.java but not string.
So you can do one thing like this
int[] arr = {R.string.page1,R.string.page2,R.string.page3};
tv.setText(getResources.getString(arr[pos]));
Related
I am selecting a part of the TextView and on click of a "highlight" button, I am sending the start and the end index of selection to the database. Then I am loading all the start and end indexes from db and changing the color of text between them.
The problem is after once or twice, the app is changing the color of text that is not in selection.. and the selected part remains unchanged.
MY CODE:
When user selects and presses the highlight button
int i=contentText.getSelectionStart();
int j=contentText.getSelectionEnd();
db.insertHiglightIndex(String.valueOf(i),String.valueOf(j));
setHighlightedText();
The setHighlightedText() method..
String fullText=contentText.getText().toString();
for(int i=0; i<db.getAllStartIndex().size();i++){
String a=fullText.substring(Integer.parseInt(db.getAllStartIndex().get(i)),Integer.parseInt(db.getAllEndIndex().get(i)));
fullText = fullText.replace(a, "<font color='red'>"+a+"</font>");
}
contentText.setText(Html.fromHtml(fullText), TextView.BufferType.SPANNABLE);
MY SCREENSHOTS.
The selection:
The Result:
Clearly the selected area is from "Garrick" to "Bart", and the result is from "entity" to "2012"
I am not able to understand why is this happening. I think there is some problem with this <font color='red'>"+a+"</font> line.
Thank you
It got wrong indexed because There is already added <font color='red'> in the beginning, So that in second time This tag is also counted as a part of string, So I suggest creating a new temporary String, assign same text to the String but after replacing the previous font tag it held. Use this syntax to remove previous font tag from originalString
String tempString = originalString.replaceAll("[<](/)?font[^>]*[>]", "");
After that work with only tempString. That means again add every previous font tag you have to tempString and set that text.
In next time again do the same first remove all font tag and again add all of them back in tempString as well as current selection using same loop you are using currently.
You have wrong indexes because you are modifying the fullText content within the loop.
Taking a look at this example you can figure it:
final TextView tv = (TextView) findViewById(R.id.textView);
tv.setText( "abcdefghijklmnopqrstuvwxyz0123456789");
String fullText= tv.getText().toString();
// your first iteration
String a = fullText.substring(1,3);
// a contains "ab"
fullText = fullText.replace(a, "<font color='red'>"+a+"</font>");
After the first iteration full text contains now
a<font color='red'>bc</font>defghijklmnopqrstuvwxyz0123456789"
Then the substring() in the second iteration won't returns the substring base on your initial content.
If you want to be able to have multiple substrings colored in red you can try this:
String fullText = contentText.getText().toString();
StringBuilder result = new StringBuilder();
for(int i=0; i < db.getAllStartIndex().size(); i++){
fullText = applyFont(result, fullText, Integer.parseInt(db.getAllStartIndex().get(i)), Integer.parseInt(db.getAllEndIndex().get(i)));
}
// Add here the remaining content
result.append(fullText);
contentText.setText(Html.fromHtml(result.toString()), TextView.BufferType.SPANNABLE);
private String applyFont(StringBuilder result, String source, int from, int to){
result.append(source.substring(0, from));
result.append("<font color='red'>");
result.append(source.substring(from, to));
result.append("</font>");
return source.substring(to, source.length());
}
I have a viewPager that get its text from the string.xml.
The plan is, depending on the position of ViewPager, it gets the text from strings, for example if the user is in page 3 it should get text from string name="page3".
Here is my beta code that is incorrect:
tv.setText(R.string.page + position);
You can get a resource from its name by using Resources.getIdentifier, eg:
String name = "page" + position;
int id = getResources().getIdentifier(name, "string", getPackageName());
tv.setText(id);
I have an Activity which has variable position that comes from another activity. I handle this variable with Intent like below. (Actually position is listView's position from another activity.) and values of position variable are 0 to 200
I took my Extra, then assigned it to a string than I parsed it to an Integer. These are normal and easy for me and working.
Intent i = getIntent();
String position = i.getStringExtra("POSITION");
int position_to_int = Integer.parseInt(position);
But my problem is about resources.
Simply I want to put an image to my LinearLayout dynamically . I have some country flags and they named in format like 0.gif, 1.gif, 2.gif, 3.gif ...
My idea is using position variable's value for this purpose.
but when I try to use position_to_int variable for name of flag, Eclipse returning error normally. Because R.drawble.XXX values storing in R.java
ImageView imageView = new ImageView(this);
// setting image resource
imageView.setImageResource(R.drawable.position_to_int);
How can I use position_to_int variable to show an ImageView dynamically?
You can't access it directly. You'll have to get the resource using its name:
private Drawable getDrawableResourceByName(int name) {
String packageName = getPackageName();
int resId = getResources().getIdentifier("character_you_prefixed" + String.valueOf(name), "drawable", packageName);
return getResources().getDrawable(resId);
}
Note that your resource names must begin with a letter, not a number, or else your project will not compile. Try adding a character to the beginning of each file name.
I have an imageView that I want to display a little icon of the country that you are currently in. I can get the country code, but problem is I can't dynamically change the imageView resource. My image files are all lowercase (Example: country code=US, image file=us)
My code (countryCode is the current countryCode in uppercase letters):
String lowerCountryCode = countryCode.toLowerCase();
String resource = "R.drawable." + lowerCountryCode;
img.setImageResource(resource);
Now, of course this will not work because setImageResource wants an int, so how can I do this?
One easy way to map that country name that you have to an int to be used in the setImageResource method is:
int id = getResources().getIdentifier(lowerCountryCode, "drawable", getPackageName());
setImageResource(id);
But you should really try to use different folders resources for the countries that you want to support.
This is how to set an image into ImageView using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
you use that code
ImageView[] ivCard = new ImageView[1];
#override
protected void onCreate(Bundle savedInstanceState)
ivCard[0]=(ImageView)findViewById(R.id.imageView1);
You can use this code:
// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];
// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...
// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
if(countriesId[i][0].equals(countryCode))
break;
}
// Now "i" is the index of the country
img.setImageResource(Integer.parseInt(countriesId[i][1]));
you may try this:-
myImgView.setImageDrawable(getResources().getDrawable(R.drawable.image_name));
I've set up an onTouch class to determine when one of my 40 buttons is pressed.
The problem I am facing is determining which button was pressed.
If I use:
int ID = iv.getId();
When I click on button "widgetA1"
I receive the following ID:
2131099684
I would like it to return the string ID "widgetA1"
from:game.xml
<ImageView android:layout_margin="1dip" android:id="#+id/widgetA1" android:src="#drawable/image" android:layout_width="wrap_content" android:layout_height="wrap_content"></ImageView>
from:game.java
public boolean onTouch(View v, MotionEvent event) {
ImageView iv = (ImageView)v;
int ID = iv.getId();
String strID = new Integer(ID).toString();
Log.d(TAG,strID);
//.... etc
}
+-+-+-+-+-+-
I other wise works fine, it knows what button you are pressing. I am quite new to this Android JAVA. Let me know if you guys can help me.
Edit - TL;DR:
View v; // handle to your view
String idString = v.getResources().getResourceEntryName(v.getId()); // widgetA1
Original:
I know it's been a while since you posted, but I was dealing with a similar problem and I think I found a solution by looking at the Android source code for the View class.
I noticed that when you print a View (implicitly calling toString()), the data printed includes the ID String used in layout files (the one you want) instead of the integer returned by getId(). So I looked at the source code for View's toString() to see how Android was getting that info, and it's actually not too complicated. Try this:
View v; // handle to your view
// -- get your View --
int id = v.getId(); // get integer id of view
String idString = "no id";
if(id != View.NO_ID) { // make sure id is valid
Resources res = v.getResources(); // get resources
if(res != null)
idString = res.getResourceEntryName(id); // get id string entry
}
// do whatever you want with the string. it will
// still be "no id" if something went wrong
Log.d("ID", idString);
In the source code, Android also uses getResourcePackageName(id) and getResourceTypeName(id) to build the full string:
String idString = res.getResourcePackageName(id) + ":" + res.getResourceTypeName(id)
+ "/" + res.getResourceEntryName(id);
This results in something to the effect of android:id/widgetA1.
Hope that helps!
You cannot get that widgetA1 string...You will always get an integer. But that integer is unique to that control.
so you can do this to check, which button is pressed
int ID = iv.getId();
if(ID == R.id.widgetA1) // your R file will have all your id's in the literal form.
{
}
Xml
android:tag="buttonA"
Src
Button.getTag().toString();
Of course you can get widgetA1, simply do:
ImageView iv = (ImageView)v;
int id = iv.getId();
String idStr = getResources().getResourceName(id);
It should give you your.package.name:id/widgetA1, then do what you want with that string.
We will get the Integer value corresponds to the views id. For finding on which button you are clicking, better to use tags. you can set tag in the layout xml file and can compare which item you have clicked using.
<Button
android:id="#+id/btnTest"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button"
android:tag="btntestTag"/>
This is sample usage.
i think that you can use this
try it
ImageView imgView = new ImageView(this);
String imgName = "img"//in your case widgetA1
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
For the implementation you could use the hint attribute to store the button name, which is accessible. For example in the button code (.xml file) use the following line:
android:hint="buttonName"
Then in the onClicked function (.java file), write the following to get the hint:
String hint = ((Button)v).getHint().toString(); //v is the view passed onClick