0

My code works only for visible views.

 mGridView = (GridView) findViewById(R.id.gridView);
 mGridView.setAdapter(new ButtonAdapter(this, list));

Method called when chronometer ticks:

public void setBackground(int i) {
    Button button = (Button) mGridView.getChildAt(i); 
    button.setBackgroundResource(R.drawable.button_shape);

This method causes NPE because getChildAt cannot access non-visible childs. I tried some solutions found here but no luck so far (android - listview get item view by position - this solution did not causes NPE but was changing background for more buttons in one tick)

What I need is to change first button background on first tick, second button on second tick.. and last button on last tick and stay consistent while scrolling.

My getView method in ButtonAdapter:

public View getView(final int position,
                    View convertView, ViewGroup parent) {
    Button btn;
    LayoutInflater inflater = LayoutInflater.from(mContext);
    if (convertView == null) {
        // if it's not recycled, initialize some attributes          
        btn = (Button) inflater.inflate(R.layout.button, parent, false);
        int width = mContext.getResources().getDimensionPixelSize(R.dimen.gridView_param_width);
        int height = mContext.getResources().getDimensionPixelSize(R.dimen.gridView_param_height);
        GridView.LayoutParams params = new GridView.LayoutParams(width, height);
        btn.setLayoutParams(params);

    } else {
        btn = (Button) convertView;
    }

    btn.setText(list.get(position).getName());   
    btn.setId(position);
    btn.setTag(position);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SetGridViewListener activity = (SetGridViewListener) mContext;
            activity.onClickGridView(position);              
            Button btn = (Button)v;
            btn.setBackgroundResource(R.drawable.button_shape_clicked);
            btn.setClickable(false);
        }
    });
    return btn;
}

I think my problem is in getView method which is probably not recycling well for my purpose. Thanks in advance.

Community
  • 1
  • 1

1 Answers1

0

I have solved it already. I used ViewHolder pattern like here ListView subobject clickable confilct and this method to access buttons from my activity:

public View getViewByPosition(int pos, GridView gridView) {
   final int firstListItemPosition = listView.getFirstVisiblePosition();
   final int lastListItemPosition = firstListItemPosition + listView.getChildCount() - 1;

   if (pos < firstListItemPosition || pos > lastListItemPosition ) {
       return gridView.getAdapter().getView(pos, null, listView);
   } else {
       final int childIndex = pos - firstListItemPosition;
       return gridView.getChildAt(childIndex);
   }
}

(android - listview get item view by position)

If you would like my concrete solution, write in comment and I will add it.

Community
  • 1
  • 1