Set individual onClick events in custom ViewGroup

大憨熊 提交于 2019-12-11 02:37:26

问题


I have created a custom ViewGroup in which I create a couple of custom child Views (in the java code, not xml). Each of these childs needs to have the same onClick event.

The method to handle these click events resides in the activity class that uses the layout. How do I set this method as the onClick handler for all child views?

Here is my code simplified.

The custom ViewGroup:

public class CellContainerGroup extends ViewGroup
{
    CellView[][] CellGrid = new CellView[9][9];

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

        TypedArray a = context.obtainStyledAttributes(R.styleable.CellContainerGroup);

        try {
                //initialize attributes here.       
            } finally {
               a.recycle();
            }

        for(int i = 0; i < 9 ; i++)
            for(int j = 0 ; j < 9 ; j++)
            {
                //Add CellViews to CellGrid.
                CellGrid[i][j] = new CellView(context, null); //Attributeset passed as null
                //Manually set attributes, height, width etc.               
                //...

                //Add view to group
                this.addView(CellGrid[i][j], i*9 + j);
            }
    }
}

The activity that contains the method I want to use as the click handler:

public class SudokuGameActivity extends Activity {

    //Left out everything else from the activity.

    public void cellViewClicked(View view) {
    {
        //stuff to do here...
    }
}

回答1:


Setup a single OnClickListener(in CellContainerGroup) which will call that method:

private OnClickListener mListener = new OnClickListener() {

     @Override
     public void onClick(View v) {
          CellContainerGroup ccg = (CellContainerGroup) v.getParent();
          ccg.propagateEvent(v);
     }
}

where propagateEvent is a method in CellContainerGroup like this:

public void propagateEvent(View cell) {
     ((SudokuGameActivity)mContext).cellViewClicked(cell);
}

and where mContext is a Context reference like this:

private Context mContext;

public CellContainerGroup(Context context, AttributeSet attrs) {
   super(context, attrs);
   mContext = context;
//...

Don't forget to set the mListener:

CellGrid[i][j].setOnClickListener(mListener);


来源:https://stackoverflow.com/questions/13976774/set-individual-onclick-events-in-custom-viewgroup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!