Change text of items in ListView when it is displayed using SimpleCursorAdapter

一个人想着一个人 提交于 2019-12-12 00:47:26

问题


How to change text of items in ListView when it is displayed using SimpleCursorAdaptor? Here is my code.

Cursor allTaskcursor = databaseHelper.getAllTasks();
String[] from = {"name", "date"};
int[] to = new int[] {android.R.id.text1, android.R.id.text2};
SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_2, allTaskcursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
allTaskListView.setAdapter(cursorAdapter);

getAllTasks() returns a cursor where date is an Integer value (example 10) which is displayed in android.R.id.text2. I want to change that text (example "10 days").


回答1:


If you want to update single list item and you know the index of item, you can call getChildAt(int) on the ListView to get the view and update it like -

TextView text2 = (TextView) v.findViewById(R.id.text2);
text2.setText("Updated Text");

Or If, you want to update all values in array, you can update the array and call notifyDataSetChanged on adapter to reflect the updated values.




回答2:


SimpleCursorAdapter.ViewBinder did the job. As answered here, I changed the code to..

Cursor allTaskcursor = databaseHelper.getAllTasks();
    String[] from = {"name", "date"};
    int[] to = new int[] {android.R.id.text1, android.R.id.text2};
    SimpleCursorAdapter cursorAdapter = new SimpleCursorAdapter(context, android.R.layout.simple_list_item_2, allTaskcursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
    cursorAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
        @Override
        public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
            if (view.getId() == android.R.id.text2) {
                int getIndex = cursor.getColumnIndex("date");
                int date = cursor.getInt(getIndex);
                TextView dateTextView = (TextView) view;
                dateTextView.setText(date + " days");
                return true;
            }
            return false;
        }
    });
    allTaskListView.setAdapter(cursorAdapter);


来源:https://stackoverflow.com/questions/23252170/change-text-of-items-in-listview-when-it-is-displayed-using-simplecursoradapter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!