我有一个使用Listview来显示Lectures的应用程序。讲座根据其类型进行颜色编码。我使用自定义适配器来控制每个讲座的不同颜色。我使用下面的代码调用适配器 -
cursor = myDbHelper.getReadableDatabase().rawQuery(sql, null);
startManagingCursor(cursor);
adapter = new Lectures_Adapter(this,R.layout.menu_item,cursor,FROM,TO);
menuList.setAdapter(adapter);
这一切都正常,直到我按照位置重新订购讲座。我使用的代码是 -
Cursor newCursor = myDbHelper.getReadableDatabase().rawQuery(sqlStr, null);
adapter.changeCursor(newCursor);
我的自定义适配器(Lectures_Adapter)中的代码位于下方,但在重新订购Lectures时未调用。
public class Lectures_Adapter extends SimpleCursorAdapter {
private Context appContext;
private int layout;
private Cursor mycursor;
public Lectures_Adapter(Context context, int layout, Cursor c, String[] from,int[] to) {
super(context, layout, c, from, to);
this.appContext=context;
this.layout=layout;
this.mycursor=c;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = super.getView(position, convertView, parent);
try {
if (position > 0)
{
RelativeLayout rowFill = (RelativeLayout) convertView.findViewById(R.id.rowFill);
String title = mycursor.getString(1);
int myColor = 0;
int myPos = title.indexOf("Nursing");
int myPos2 = title.indexOf("Masterclass");
if (myPos >= 0)
{
myColor = Color.parseColor("#99FF66");
}
else if (myPos2 >= 0)
{
myColor = Color.parseColor("#FF99FF");
}
else
{
myColor = Color.parseColor("#FFFF66");
}
convertView.findViewById(R.id.rowFill).setBackgroundColor(myColor);
}
}catch(Exception e) {
}
if (convertView == null) {
LayoutInflater inflator = (LayoutInflater) this.appContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(this.layout,null);
} else {
convertView = (View) convertView;
}
return view;
}
}
有人可以告诉我如何动态重新订购Listview并每次都给我调用自定义适配器。
答案 0 :(得分:1)
问题是你的getView()代码从类变量mycursor
获取数据,但是当你调用changeCursor时,mycursor
变量没有得到更新,所以你仍然可以看到原始的名单。您应该拨打mycursor
而不是getCursor()
。
答案 1 :(得分:0)
您是否尝试在调用changeCursor后调用adapter.notifyDataSetChanged()?这应该会强制更新menuList。
答案 2 :(得分:0)
您可能不想使用getView,而是使用newView和bindView方法......这是我编写的一些代码的示例。
private static class ViewHolder {
HistoryRowView rowvw;
}
class ReportHistoryAdapter extends CursorAdapter {
ViewHolder _holder;
private static final String INFLATER_SVC = Context.LAYOUT_INFLATER_SERVICE;
private LayoutInflater _inflater;
public PostureReportAdapter( Context context, Cursor cursor ) {
super( context, cursor );
_inflater = (LayoutInflater) context.getSystemService(INFLATER_SVC);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View vw = _inflater.inflate( R.layout.reports_history_view, null );
_holder = new ViewHolder();
_holder.rowvw = (HistoryRowView)vw.findViewById( R.id.rhv_history_row_vw );
vw.setTag( _holder );
return vw;
}
@Override
public void bindView(View vw, Context context, Cursor cursor) {
_holder = (ViewHolder)vw.getTag();
int poor = cursor.getInt( 0 );
int fair = cursor.getInt( 1 );
int good = cursor.getInt( 2 );
int date = cursor.getInt( 3 );
_holder.rowvw.setData( poor, fair, good, date );
}
}