【问题标题】:Update ListView items appearance depending on screen position根据屏幕位置更新 ListView 项目外观
【发布时间】:2017-07-20 13:07:02
【问题描述】:

我有以下问题:

我的 Android 应用中有一个 ListView。此列表视图的每个项目都有 2 个 TextView(例如,左右)。我想实现如下效果:左侧TextView始终可见,右侧TextView仅在位于屏幕上半部分时可见,并且当用户滚动ListView时其可见性发生变化。

+-------+   
|l1   r1|
|l2   r2| <= initial positions, r3 and r4 aren't displayed
|l3     |
|l4     |
+-------+

+-------+   
|l3   r3|
|l4   r4| <= the user has scrolled the list up, r3 and r4 are displayed
|l5     |
|l5     |
+-------+

如何达到这样的效果?

我的 ListView 使用了一个适配器,从 BaseAdapter 扩展而来,这个适配器看起来像

public class ItemAdapter extends BaseAdapter {

Context ctx;
LayoutInflater lInflater;
private List<Item> items;

....

@Override
public View getView(int i, View view, ViewGroup viewGroup) {

    if (view == null) {
        view = lInflater.inflate(R.layout.sample_list_item_view, viewGroup, false);
    }

    Item item = items.get(i);
    ((TextView) view.findViewById(R.id.l)).setText(item.key);
    ((TextView) view.findViewById(R.id.r)).setText(item.value);
    return view;
}

}

我很高兴能够在 getView() 中更改正确 TextView 的可见性,但是当列表滚动时不会调用此方法。

【问题讨论】:

    标签: android listview


    【解决方案1】:

    按照我对 BaseAdapter 的理解,只有在 Android 创建要在屏幕上显示的项目时才会调用 getView() 方法。如果项目已经在屏幕上,则不会调用 getView()。

    【讨论】:

    【解决方案2】:

    找到了解决办法。

            listView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
            }
    
            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
                for (int index = 0; index < i1; index++) {
                    View child = listView.getChildAt(index);
                    if (child != null) {
                        int[] out = new int[2];
                        child.getLocationOnScreen(out);
                        int alpha = (800 - out[1]);
                        if (alpha < 0) alpha = 0;
                        if (alpha > 255) alpha = 255;
                        ((TextView) child.findViewById(R.id.r)).setTextColor(Color.argb(alpha, 60, 60, 60));
                    }
                }
            }
        });
    

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 2017-04-16
      相关资源
      最近更新 更多