Strikethough text in listview?
I'm making something of a todo list and the one issue I'm facing is that I cannot figure ou开发者_开发知识库t how to make it for when I click on an item within a listview the text in that row gets the strikethrough effect. I know I'm supposed to call:
TextView text = (TextView)view.findViewById(android.R.id.text);
text.setPaintFlags(text1.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
I'm calling it from on onListItemClick
but it crashes when I click an item. Any suggestions?
Following code worked for me, in which contacts information is displayed as a list and when list item is clicked contact name is strikedthrough.
Add permission "android.permission.READ_CONTACTS" to manifest file to test the below code.
public class MyListActivity extends ListActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] projection={ContactsContract.Contacts.DISPLAY_NAME,ContactsContract.Contacts._ID};
int[] to={android.R.id.text1,android.R.id.text2};
Cursor c=getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
setListAdapter(new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,c,projection,to));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
TextView tv=(TextView) v.findViewById(android.R.id.text1);
tv.setPaintFlags(tv.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
I couldn't find the resource id "android.R.id.text" in API level 8, probably you need to correct this in your code.
PS:It is incorrect to modify the textview property since views are recycled by the framework and there is no guarantee that each todo list item has a separate view. Ideal way is to store the position of the list item that needs to be strikethrough and override getView() method by extending adapter and set the correct paint flag based on the stored state of current list item.
精彩评论