Skip to content Skip to sidebar Skip to footer

Get The Values From Gridview Items

I am working on a project where I have a let's say 5x5 grid of TextViews and I want to check if an entire row or column has equal elements. I am using an Adapter class to inflate m

Solution 1:

When using an AdapterView – such as your GridView – you generally don't want to directly access and manipulate its child Views outside of its Adapter. Instead, the dataset backing the Adapter should be updated, and the GridView then refreshed.

In your case, you presumably have a setup similar to this in your Activity:

privateGridAdapter gridAdapter;
privateString[] numbers;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
    ...
    numbers = newString[25];
    gridAdapter = newGridAdapter(this, numbers);
}

Here, the numbers array is what you want to directly modify, rather than the text on the GridView's child TextViews. That array is then easily iterated over to do your row and column value checks.

Since the array will be modified in the Activity, we need a way to pass the clicked TextView's position in the Adapter to the Activity's click method, as we'll need it to access the correct array element. For this, we can utilize the tag property available on all View's, via the setTag() and getTag() methods. For example, in GridAdapter's getView() method:

...
TextView textView = (TextView) gridView.findViewById(R.id.cell);
textView.setText(numbers[position]);
textView.setTag(position);
...

In the click method, the position can be easily retrieved with getTag(), and used as the index to get the clicked TextView's text from the numbers array. You can then do the necessary processing or calculation with that text, set the modified value back to the array element, and trigger a refresh on the Adapter.

publicvoidnumberFill(View view){
    int index = (Integer) view.getTag();

    // Do your processing with numbers[index]

    numbers[index] = "new value";

    gridAdapter.notifyDataSetChanged();
}

The notifyDataSetChanged() call will cause the GridView to update its children, and your new value will be set in the appropriate TextView. The numbers array now also has the current values, and is readily available in the Activity to perform the necessary checks there.

Post a Comment for "Get The Values From Gridview Items"