Get the values from GridView items

前端 未结 1 737
滥情空心
滥情空心 2021-01-23 09:05

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 infla

相关标签:
1条回答
  • 2021-01-23 09:22

    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:

    private GridAdapter gridAdapter;
    private String[] numbers;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        numbers = new String[25];
        gridAdapter = new GridAdapter(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.

    public void numberFill(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.

    0 讨论(0)
提交回复
热议问题