I’m trying to accomblish the following task:
- A ListView, with textview rows
- When I click on an item, the text changes to italic
The change to italic can be something else – the point is to change the text in some way.
I thought to use Html.fromHtml, since that’s pretty easy to deal with when formatting text. However, I cannot get it to work accross my design.
In my main activity, I create and access the ListView and ArrayAdapter like this:
lv = (ListView) this.findViewById(R.id.itemslist);
I have a method for creating/updating the adapter, so that I can update the contents of the list:
private void displayList () {
adapter = new ItemArrayAdapter(getApplicationContext(), R.layout.item_listitem, items);
lv.setAdapter(adapter);
adapter.setNotifyOnChange(true);
}
My OnItemClickListener:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ShoppingListApp02Activity.this, "List item selected:" +
items.get(position).getId(), Toast.LENGTH_LONG).show();
items.get(position).setName("<i>" + items.get(position).getName() + "</i>");
displayList();
});
As you can see, on select/click of an item, I send the item’s name surrounded by the html tags, to the Item class’ setName() method. The name (type String) of the item object is now “<i>name</i>”
The setName() method in the Item class:
public void setName (String nname) { this.name = nname; }
Now, in the ArrayAdapter class (ItemArrayAdaper.java), the name is set in the TextView row of the ListView:
itemName.setText(item.name);
If I leave the code above as it is, when clicking the item in the list, the name changes to this: “<i>name</i>.
So far, it’s as I expected.
However, from there I need to convert the string “<i>name</i> to the html result, namely “name“. But when I try that like this:
itemName.setText(Html.fromHtml(item.name).toString());
it simply skips the html tags and displays the name string normally.
Why isn’t the fromHtml working here?
To compare, I tried just setting the contents of another TextView in my application (the footer) in the same way, with just:
footerview.setText(Html.fromHtml("<i><font color='#123456'>text</font></i>"));
And that worked just fine. But somewhere along the path, the tags surrounding the item name is lost. And that’s strange, because in the ItemArrayAdapter class when I don’t try to convert from html, the tags are there. They just aren’t honored when using the fromHtml method at the same place.
Any ideas?
And, I know there’s probably a better way to do this, and I’d be interested in that too 🙂
Easy solution: Remove the toString(). I didn’t try that because I had problems with it before, thinking that the data passed to a TextView HAS to be a pure string. However, it works like a charm without the toString() 🙂