Как получить доступ к представлению в GridView? - PullRequest
1 голос
/ 12 апреля 2019

У меня есть GridView, который показывает количество цветов.Я хочу, чтобы некоторые из них были выбраны, но я не могу понять, как получить доступ к отдельным цветам, чтобы сделать это.

Вот что у меня есть:

GridView рисуется в DialogFragment, называемом DialogFragmentSelectColour.Для отображения в GridView (mColours) требуется ArrayList<ChartColours> из ChartColours и ArrayList<ChartColours> из ChartColours, которые уже выбраны (mSelectedColours):

public class DialogFragmentSelectColour extends DialogFragment {

        private ArrayList<ChartColour>  mColours, mSelectedColours;
        private AdapterChartColour      mColourAdapter;
        private Context                 mContext;
        private GridView                mGVColours;
        private OnColoursSelected       mCallback;

        static public DialogFragmentSelectColour newInstance(Context context, ArrayList<ChartColour> colours, ArrayList<ChartColour> selectedColours, OnColoursSelected callback) {

            DialogFragmentSelectColour f = new DialogFragmentSelectColour();
            f.setRequiredData(context, colours, selectedColours, callback);

            return f;
        }

        public void setRequiredData(Context context, ArrayList<ChartColour> colours, ArrayList<ChartColour> selectedColours, OnColoursSelected callback) {

            this.mContext = context;
            this.mColours = colours;
            this.mCallback = callback;

            // Selected colours is initially null if no colours have yet been selected
            if(selectedColours == null) {
                this.mSelectedColours = new ArrayList<>();
            }else {
                this.mSelectedColours = selectedColours;
            }

        }

        @Override
        public View onCreateView(@NonNull LayoutInflater inflater,
                                    ViewGroup container,
                                    Bundle savedInstanceState) {

            // Inflate layout
            return inflater.inflate(R.layout.dialog_fragment_select_colour, container, false);

        }

        public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
            super.onViewCreated(view, savedInstanceState);

            mGVColours = view.findViewById(R.id.gv_colours);

            drawColours();
            selectColours();

        }

        private void drawColours() {

            // Now set up AdapterChartColour to display colours in grid
            mColourAdapter =
                    new AdapterChartColour(mContext, mColours,
                            mSelectedColours);
            mGVColours.setAdapter(mColourAdapter);

        }

        private void selectColours() {

            // Highlight selected colours and unhighlight all others
            // Loop over all colours; if colour is in "selected" array, select it; otherwise, unselect it

            for(int ii=0; ii < mGVColours.getChildCount(); ii++) {

    // I've tried both of the following, but neither returned a ChartColourCell:
                // ChartColourCell cell = (ChartColourCell) mGVColours.getChildAt(ii);
                // ChartColourCell cell = (ChartColourCell) mGVColours.getItemAtPosition(ii);

        }
}

ChartColour - это просто класс, который содержит имя цвета (в виде строки) и его значения rgb (как целые числа).

ChartColourCell - это класс, который отображает ChartColour следующим образом(Я упустил некоторые детали, которые не имеют отношения):

public class ChartColourCell extends View {

    private boolean     mSelected;
    private ChartColour mColour;        // Colour to be shown
    private Paint       mPaint;         // Paint variable to use

    public ChartColourCell(Context context, AttributeSet attrs) {
        super(context, attrs);

        mSelected = false;
        mPaint = new Paint();
        mPaint.setStrokeWidth(10f);

    }

    public ChartColour getColour() { return this.mColour; }

    // Set the colour to be shown in the circle
    public void setColour(ChartColour colour) {

        this.mColour = colour;
        invalidate();

    }

    // Change whether the colour is selected or not
    public void setSelected(boolean selected) {

        this.mSelected = selected;
        invalidate();

    }

    // Draw the circle
    // If selected, overlay the circle with a tick mark
    protected void onDraw(Canvas canvas) {

        if(this.mColour == null) return;

        // Get canvas size, initialise Paint, get radius & centre
        ... I've left out the details of this to save space ...

       // Draw circle
        canvas.drawCircle(cx, cy, radius, mPaint);

        // If the colour is selected, overlay a tick
        Drawable drawable = getResources().getDrawable(R.drawable.icon_tick);
        drawable.setBounds(0, 0, getWidth(), getHeight());
        drawable.draw(canvas);

    }

}

AdapterChartColour выглядит следующим образом:

public class AdapterChartColour extends ArrayAdapter<ChartColour> {

    private Context                 mContext;
    private ArrayList<ChartColour>  mColourArray, mSelectedArray;

    public AdapterChartColour(Context context, ArrayList<ChartColour> colourArray, ArrayList<ChartColour> selectedArray) {
        super(context, layout_id, colourArray);

        this.mContext       = context;
        this.mColourArray   = colourArray;
        this.mSelectedArray = selectedArray;

    }

    private static class ViewHolder {

        private ChartColourCell colourCell;
        private TextView colourName, colourKey;

    }

    @NonNull
    @Override
    public View getView(final int position, View convertView, @NonNull ViewGroup parent) {

        ViewHolder mViewHolder;

        if(convertView == null) {

            mViewHolder = new ViewHolder();

            LayoutInflater layoutInflater
                    = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            if (layoutInflater != null) {

                // Inflate appropriate layout
                convertView = layoutInflater.inflate(R.layout.adapter_chart_colour_cell, parent, false);
                if (convertView != null) {

                    // Find views
                    mViewHolder.colourCell = convertView.findViewById(R.id.chart_colour_cell);

                    mViewHolder.colourCell.setSelected(false);

                    convertView.setTag(mViewHolder);

                    ChartColour cellColour = mColourArray.get(position);
                    mViewHolder.colourCell.setColour(cellColour);           // Causes cell to draw

                    // Now determine whether this colour is selected

                    if (mSelectedArray.contains(cellColour)) {
                        mViewHolder.colourCell.setSelected(true);
                    } else {
                        mViewHolder.colourCell.setSelected(false);
                    }
                }
            }
        }

        return convertView;
    }

    public int getCount() { return mColourArray.size();}

    public ChartColour getItem(int position) { return mColourArray.get(position);}

}

Макет adapter_chart_colour_cell просто содержит:

<mypath.appname.models.ChartColourCell
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/grid_cell_column_width"
    android:layout_height="@dimen/grid_cell_column_width"
    android:id="@+id/chart_colour_cell"/>

Надеюсь, это все, что требуется, чтобы иметь смысл, но я могу добавить больше, если это необходимо.Итак, как мне получить доступ к индивидуальному ChartColourCells в GridView, чтобы я мог выбрать и отменить выбор?

...