【问题标题】:SimpleAdapter not keeping position when scrolling滚动时 SimpleAdapter 不保持位置
【发布时间】:2015-08-25 03:45:56
【问题描述】:

我有一个 SimpleAdapter,用于显示两行列表视图。我希望这个简单适配器上的第 15 个位置具有不同的格式,但是当我滚动列表视图时,它会丢失位置并且格式会更改位置。有解决方案吗?我尝试过使用 convertView,但似乎无法获得正确的格式。我的代码如下。谢谢!

        SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"title", "publisher"}, new int[] {android.R.id.text1, android.R.id.text2}){
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = super.getView(position, convertView, parent);

            if (position == 15) {
                TextView text1 = (TextView) view.findViewById(android.R.id.text1);
                text1.setTextColor(Color.WHITE);
                TextView text2 = (TextView) view.findViewById(android.R.id.text2);
                text2.setTextColor(Color.WHITE);
                view.setBackgroundColor(getResources().getColor(R.color.teal_dark));
            }

            return view;
        }


    };

【问题讨论】:

    标签: android android-listview android-view simpleadapter


    【解决方案1】:

    尝试添加一个 else 子句将格式重置为默认格式

    if (position == 15) {
        TextView text1 = (TextView) view.findViewById(android.R.id.text1);
        text1.setTextColor(Color.WHITE);
        TextView text2 = (TextView) view.findViewById(android.R.id.text2);
        text2.setTextColor(Color.WHITE);
        view.setBackgroundColor(getResources().getColor(R.color.teal_dark));
    } else {
        TextView text1 = (TextView) view.findViewById(android.R.id.text1);
        text1.setTextColor(Color.BLACK);
        TextView text2 = (TextView) view.findViewById(android.R.id.text2);
        text2.setTextColor(Color.BLACK);
        view.setBackgroundColor(getResources().getColor(R.color.teal_light));
    }
    

    【讨论】:

    • 这成功了!谢谢 - 我只是不知道为什么......如果之前达到“位置 == 15”,会不会再次达到?
    • 实际上,android 会为你在listview 上的每一行回收视图。当您第一次到达第 15 行,然后滚动到另一个位置时,android 将重新使用第 15 行用于其他行,这就是格式似乎跳转到另一行的原因
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多