【问题标题】:Android - ImageView source incorrect in ListViewAndroid - ListView 中的 ImageView 源不正确
【发布时间】:2012-07-17 08:59:04
【问题描述】:

我有一个 ListView,它通过 CursorAdapter 显示来自数据库的一些结果...标题、文本和一个标志,以指示用户是否已经查看过该项目(通过将它们带到另一个屏幕)... 基本上,如果数据库“已访问”值为 0,则需要在项目旁边显示一个小的“新”图标...如果不是,则不应显示任何图标...

问题在于,当它加载列表时,它似乎随机分配标志...访问过的没有标志,但一些未访问过的也错过了标志...

我尝试在 BindView 和 NewView 之间移动“已访问”检查,但得到相同的结果...

我的适配器:

public class newsAdapter extends CursorAdapter{

public newsAdapter(Context context, Cursor cursor){

    super(context, cursor);

}

@Override
public void bindView(View view, Context context, Cursor cursor) {

    TextView title = (TextView) view.findViewById(R.id.newsItemTitle);
    TextView text = (TextView) view.findViewById(R.id.newsItemText);

    ImageView newflag = (ImageView) view.findViewById(R.id.newsNewFlag);
    if(cursor.getInt(cursor.getColumnIndex("visited")) == 0){
        Log.i("extra","Not visited yet");
        newflag.setImageResource(R.drawable.icon_new);
    }

    title.setText(cursor.getString(cursor.getColumnIndex("title")));
    text.setText(cursor.getString(cursor.getColumnIndex("text"))); iv);
}

@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
    LayoutInflater inflater = LayoutInflater.from(parent.getContext());
    View view = inflater.inflate(R.layout.news_item, parent, false);

    return view;
}


}

我确定数据库中的数据是正确的... 提前致谢!

【问题讨论】:

    标签: android listview


    【解决方案1】:

    试试这个,

    在您的以下代码中添加一个 else 块,并在其中将 imageview 设置为不可见/消失。您也可以将 imageresource 设置为 null,但何必呢?

    if(cursor.getInt(cursor.getColumnIndex("visited")) == 0){
            Log.i("extra","Not visited yet");
            newflag.setImageResource(R.drawable.icon_new);
        }
    

    但是,将其设置为“消失”可能会影响您的布局。如果您打算使用 GONE,请处理好。

    您可以尝试的另一件事是实现 getView() 而不是 newView() 并实现 ViewHolder 模式。它提高了效率,据我所知更不容易出错。

    【讨论】:

    • 你覆盖了 getView() 吗?
    • 不,我没有,我应该用什么覆盖它?
    • 您可以查看此帖子 stackoverflow.com/questions/5183813/… 可能会有所帮助。也为此 LayoutInflater inflater = LayoutInflater.from(parent.getContext());使用上下文而不是 parent.getContext()
    • 将代码粘贴到 GetView 似乎已经成功了!不知道为什么我会使用 new/bindview ......非常感谢!我不确定 StackOverflow 的规则,但我会接受你的答案,因为它在 cmets 中......
    • 我会将其添加到答案中,以便其他引用它的人得到它:)
    猜你喜欢
    • 1970-01-01
    • 2016-11-05
    • 2017-08-02
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多