I would like to change the imageview src based on my string, I have something like this:
ImageView imageView1 = (ImageView)findViewById(R.id.imageView1);
String correctAnswer = "poland";
String whatEver = R.drawable+correctAnswer;
imageView1.setImageResource(whatEver);
Of course it doesnt work. How can I change the image programmatically?
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
use:
imageView1.setImageResource(getImageId(this, correctAnswer);
Note: leave off the extension (eg, ".jpg").
Example: image is "abcd_36.jpg"
Context c = getApplicationContext();
int id = c.getResources().getIdentifier("drawable/"+"abcd_36", null, c.getPackageName());
((ImageView)v.findViewById(R.id.your_image_on_your_layout)).setImageResource(id);
I don't know if this is what you had in mind at all, but you could set up a HashMap of image id's (which are ints) and Strings of correct answers.
HashMap<String, Integer> images = new HashMap<String, Integer>();
images.put( "poland", Integer.valueOf( R.drawable.poland ) );
images.put( "germany", Integer.valueOf( R.drawable.germany ) );
String correctAnswer = "poland";
imageView1.setImageResource( images.get( correctAnswer ).intValue() );
Related
I have this method which works fine for an EditText or a view.
public SpannableString strikeThrough(String txt){
SpannableString spannableString = new SpannableString(txt);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
spannableString.setSpan(strikethroughSpan,0, txt.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
return spannableString;
}
EditText etChecklistItem = checklistView.findViewById(R.id.et_checklist_item);
etChecklistItem.setText(strikeThrough(etChecklistItem.getText().toString()));
But my problem is after that, the text doesn't have StrikeThrough.
StringBuilder stringBuilderItem = new StringBuilder();
for( String list : itemslist) {
stringBuilderItem.append(list);
stringBuilderItem.append("\n");
}
String text = stringBuilderItem.toString();
strikeThrough(text);
dbHelper.insertChecklist(text);
When I get the data in RecyclerView, it would not be in Strikethrough.
Instead of storing a strike-through string inside the array, Create a class having two members a String and a boolean, and make the boolean true for the string you want to strike through.
class Message {
private String str;
private boolean strike;
public Message (String str, boolean strike) {
this.str = str;
this.strike = strike;
}
// getters and setters
}
and make string strike through when you're showing it on the screen
ArrayList<Message> arr = new ArrayList<>();
for (Message msg: arr) {
if (arr.getStrike()) {
// make string strikethrough
} else {
// keep as it is
}
}
To strike through a string in TextView
Method 1
textView.setText("I want like that")
textView.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
Method 2: If you want to strike through only a part of the text then use
String str = "I want like that";
SpannableStringBuilder builder = new SpannableStringBuilder(str);
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();
builder.setSpan(
strikethroughSpan,
0, // Start
4, // End (exclusive)
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE // Text changes will not reflect in the strike changing
);
textView.setText(spanBuilder);
Method 3: If you want to strike through text in strings.xml
<string name="yourName"><strike>I want like that</strike></string>
references: [1]
Just Checkout this Code
First you need to initialise you edit text or text view
textView = findViewById(R.id.textView);
textView.setText("Hello World");
textView.setPaintFlags(textView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
I hope this will help you, if any problem just comment down
So I have more imageView looking like this:
imageView1
...
imageView8
int defendPosition = defend(); // This is random generated number from 1-8;
String imageID = "imageView" + defendPosition;
int resID = getResources().getIdentifier(imageID, "id", getPackageName());
Log.i("resID", " "+ resID); // it logs value is 0
secondMove = findViewById(resID);
secondMove.setTranslationY(-1500); // When I try to run this, it says null refference;
I need to get the correct id
try
int resID=this.getResources().getIdentifier(imageID,"id",getActivity().getPackageName())
I'm trying to show a gridview with all the users images in it.
but loading the images from the android MediaStore.
I have to do a request and then loop over the images from the result to get every single thumbnail, this results in a huge lag!
how would I compress these calls into a single request or how would I save more time on this?
String[] projection = new String[]{
MediaStore.Images.Media._ID,
MediaStore.Images.Media.TITLE,
MediaStore.Images.Media.DATA,
MediaStore.Images.Media.MIME_TYPE,
MediaStore.Images.Media.SIZE,
MediaStore.Images.Media.DATE_TAKEN,
MediaStore.Images.Media.DATE_ADDED,
MediaStore.Images.Media.DATE_MODIFIED,
MediaStore.Images.Media.ORIENTATION
};
String sortOrder = MediaStore.Images.Media.DATE_ADDED + " DESC, " +
MediaStore.Images.Media.DATE_MODIFIED + " DESC";
ContentResolver cr = ctx.getContentResolver();
final Cursor cursorImages = cr.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
sortOrder);
ArrayList<ImageDataHolder> images = new ArrayList<ImageDataHolder>(cursorImages.getCount());
if (cursorImages.moveToFirst()) {
final int dataColumn = cursorImages.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
final int idColumn = cursorImages.getColumnIndexOrThrow(MediaStore.Images.Media._ID);
do {
final Long imageID = cursorImages.getLong(idColumn);
final String imagePath = cursorImages.getString(dataColumn);
final int imageOrientation = cursorImages.getInt(dataColumn);
// create new cursor to get thumbnail path
final Cursor cursorThumb = MediaStore.Images.Thumbnails.queryMiniThumbnail(ctx.getContentResolver(), imageID,
MediaStore.Images.Thumbnails.MINI_KIND, null);
String thumbPath = "";
if (cursorThumb != null) {
if (cursorThumb.getCount() > 0) {
cursorThumb.moveToFirst();
thumbPath = cursorThumb.getString(cursorThumb.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
}
cursorThumb.close(); // cleanup crew, isle 7
}
// create new ImageDataHolder and add to images ArrayList
// only if we have a thumbnail to show
if (thumbPath != "")
images.add(new ImageDataHolder(imagePath, thumbPath, imageID, imageOrientation));
} while (cursorImages.moveToNext());
}
cursorImages.close();
return images;
I have some xml data I am looping through. I would like to store each "entry" in an array spot in order to see it with an intent.putExtras(). My data has 3 elements: latlon,name,description. I would like to put each in my array. So I am setting it up like so: markerInfo[i][0] = Loc; etc... like so:
final List<XmlDom> entries = xml.tags("Placemark");
int i = entries.size();
int j=0;
for (XmlDom entry : entries) {
XmlDom lon = entry.tag("longitude");
XmlDom lat = entry.tag("latitude");
XmlDom name = entry.tag("name");
XmlDom desc = entry.tag("description");
String cdatareplace = desc.toString();
String description = cdatareplace.replace("<![CDATA[", "");
description = description.replace("]]>", "");
final String firename = name.text();
final String firedesc = description;
String geoLon = lon.text();
String geoLat = lat.text();
String coor = lat + "," + lon;
// Log.e("COORS: ", coor);
double lati = Double.parseDouble(geoLat);
double lngi = Double.parseDouble(geoLon);
LOCATION = new LatLng(lati, lngi);
String Loc = LOCATION.toString();
String[][] markerInfo = new String[i][3];
markerInfo[j][0] = Loc;
markerInfo[j][1] = firename;
markerInfo[j][2] = firedesc;
Log.e("MARKERINFO",markerInfo[j][0]);
Log.e("MARKERINFO",markerInfo[j][1]);
Log.e("MARKERINFO",markerInfo[j][2]);
map.addMarker(new MarkerOptions()
.position(LOCATION)
.title(markerInfo[j][1])
.snippet(markerInfo[j][2])
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.wfmi_icon48)));
map.setOnInfoWindowClickListener(new OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker arg0) {
// Show full description in new activity.
// fireDesc(arg0.getTitle(), arg0.getSnippet());
Intent i = new Intent(Map.this, MapSingleActivity.class);
i.putExtra("name", arg0.getTitle())
.putExtra("description", arg0.getSnippet())
.putExtra("lat", arg0.getPosition().latitude)
.putExtra("lon", arg0.getPosition().longitude);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
});
j++;
}
I am getting array index out of bounds. I figured if I filled it with the entries.size() that would not be the problem, so maybe i am not telling it how big correctly?
Thanks for any help
You need to make sure that the second dimension is also big enough
Fix it by changing the declaration of markerInfo to:
String[][] markerInfo = new String[i][3];
At the moment you are only creating i empty String arrays. With the above code you will create i arrays that can hold three String objects each.
Also, at the moment you are writing to the last location which is outside of the array bounds.
You need to change it to write to an available location. If you are trying to write to the last available location that would be i-1.
markerInfo[i-1][0] = Loc;
markerInfo[i-1][1] = firename;
markerInfo[i-1][2] = firedesc;
Looking at your code however, it seems like you may want to declare markerInfo outside of the loop and create a counter variable that you increment at each step of the loop.
Second size of the array is 0 - new String[i][0]. Then you try to insert something on position 0,1,2, which are not available.
Even if you write new String[i][3], then the maximum index is i-1.
I have code like this:
TextView wyniszczenie_zakres_bmi = (TextView)t.findViewById(R.id.wyniszczenie_zakres_bmi);
TextView wychudzenie_zakres_bmi = (TextView)t.findViewById(R.id.wychudzenie_zakres_bmi);
TextView niedowaga_zakres_bmi = (TextView)t.findViewById(R.id.niedowaga_zakres_bmi);
Can I do something like this?
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan){
TextView s + _zakres_bmi = (TextView)t.findViewById(R.id. + s + _zakres_bmi);
}
I know it's not work but is there any solution for this?
Try this:
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan) {
int myId = getResources().getIdentifier(s + "_zakres.bmi", "id", getPackageName());
TextView myTextView = (TextView)t.findViewById(myId);
// Do something with myTextView
}
If you need to save the textView references for later rather than acting on them immediately, then put myTextView into an array or hashtable after it's assigned.
Hashtable textViews = new Hashtable<String, TextView>();
List<String> arStan = new ArrayList<String>();
arStan.add("wyniszczenie");
arStan.add("wychudzenie");
arStan.add("niedowaga");
for(String s : arStan) {
int myId = getResources().getIdentifier(s + "_zakres.bmi", "id", getPackageName());
TextView myTextView = (TextView)t.findViewById(myId);
textViews.put(s + "_zakres.bmi", myTextView);
}
// When you need to get one of the TextViews:
TextView tv = textViews.get("niedowaga_zakres.bmi");
// Do something with tv.