How To Add Imageview's That Are Depending On The Text Of The Textview In A Listview
I have a custom ListView with a RowItem that contains TextView and a ImageView . The RowItems will be added dynamically. I just want to know how to add the ImageView to a specific
Solution 1:
You can make a switch-case
statement based on the text of the TextView
like below
switch(tv.getText().toString()){
case"Title1" : image.setImageResource(R.drawable.ic_title1);
break;
case"Title2" : image.setImageResource(R.drawable.ic_title2);
break;
default:
//Default image here, if no case foundbreak;
}
Note: above answer requires JRE 1.7 compliance
Solution 2:
The solution in this instance would be to add methods for getting and setting the individual fields for your ListView
object. For example, since you have a TextView
and an ImageView
in your row item, let us assume that your row object looks something like the following:
publicclassListObject
{
publicListObject (String textView, String imageView)
{
super();
this.textView = textView;
this.imageView = imageView;
}
privateString textView;
privateString imageView;
publicString getTextView ()
{
return textView;
}
publicvoid setTextView (String pTextView)
{
this.textView = pTextView;
}
publicString getImageView ()
{
return imageView;
}
publicvoid setImageView (String pImageView)
{
this.imageView = pImageView;
}
}
Once these are implemented, you can easily set your ImageView
based on your TextView
like so:
// As an example, let us use the first list itemListObjectlistObject= (ListObject) parent.getItemAtPosition(0);
if (listObject.getTextView == "Title1")
{
listObject.setImageView("NameOfResource");
}
// so on and so forth
Solution 3:
What about something like this.
image.setImageResource(getImageId(this, "ic_" + tv.getText().toString().toLowerCase());
So basically you're getting the title from the text view manipulating it to be in the format you're storing your images and calling the below helper to get the correct image id.
publicstatic int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
Post a Comment for "How To Add Imageview's That Are Depending On The Text Of The Textview In A Listview"