如何在RecyclerVIew上实现项目计数器?

时间:2018-01-02 06:57:24

标签: android recycler-adapter recyclerview-layout

我想在android中的RecyclerView上实现Item计数器。如果我们滚动列表,那么项目计数器将增加如下图像。我是android的新手,所以请建议我叫什么,我们在哪里可以阅读它。 Thanku

Item Counter's image

here you can see that the counter text is changed when scrolled

3 个答案:

答案 0 :(得分:1)

如果您使用的是数组适配器,则可以在适配器中使用项目位置覆盖getView方法设置计数器文本:

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //necessary code for inflating list items
        //as index position starts from 0, set position+1 in textview
        tvCounter.setText(Integer.parseInt(position+1)); 
        return convertView;
    }

如果您使用 RecyclerView适配器,则可以在适配器中使用项目位置覆盖onBindViewHolder方法设置计数器文本:

@Override
    public void onBindViewHolder(ItemViewHolder holder, int position) {
        //other parts

        //as index position starts from 0, set position+1 in textview
        holder.tvCounter.setText(Integer.toString(position+1));
    }

答案 1 :(得分:0)

findFirstVisibleItemPosition()将在滚动顶部/底部时返回可见的项目位置。

LinearLayoutManager myLayoutManager = myRecyclerView.getLayoutManager();
int scrollPosition = myLayoutManager.findFirstVisibleItemPosition();

了解有关read this.

的更多信息

答案 2 :(得分:0)

在您的activity / fragment中创建BroadcastReceiver。

private BroadcastReceiver counterChangeReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        //set text by getting value from intent extras
    }
};

并将其注册在activity / fragment onResume()中,如此

LocalBroadcastManager.getInstance(context).registerReceiver(counterChangeReceiver , new IntentFilter("COUNTER_CHANGE"));

从onBindViewHolder()发送广播

 Intent intent = new Intent("COUNTER_CHANGE");
 intent.putExtra("value",(position+1));
 LocalBroadcastManager.getInstance(MyApplication.getInstance().getBaseContext()).sendBroadcast(intent);