pb007
pb007

Reputation: 161

How to implement Item counter on RecyclerVIew?

I want to implement Item counter on RecyclerView in android. If we scroll the list so item counter will increase like below Image. I am new in android so Please suggest me what is it called and where can we get it to read it. Thanku

Item Counter's image

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

Upvotes: 1

Views: 2864

Answers (3)

Geethakrishna Juluri
Geethakrishna Juluri

Reputation: 540

Create BroadcastReceiver in your activity/fragment.

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

and register it in activity/fragment onResume() like this

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

Send broadcast from onBindViewHolder() something like this

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

Upvotes: 0

Sabid Habib
Sabid Habib

Reputation: 419

if you are using Array Adapter, you can set your counter text with item position overriding getView method in your adapter:

@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;
    }

if you are using RecyclerView Adapter, you can set your counter text with item position overriding onBindViewHolder method in your adapter:

@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));
    }

Upvotes: 2

Hemant Parmar
Hemant Parmar

Reputation: 3976

findFirstVisibleItemPosition() will return visible item position while scroll top/bottom.

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

for more about read this.

Upvotes: 0

Related Questions