在自定义ViewGroup中设置单个onClick事件

时间:2012-12-20 16:47:08

标签: android android-custom-view

我创建了一个自定义ViewGroup,我在其中创建了几个自定义子视图(在java代码中,而不是xml)。 这些孩子中的每一个都需要具有相同的onClick事件。

处理这些点击事件的方法驻留在使用布局的活动类中。如何将此方法设置为所有子视图的onClick处理程序?

这是我的代码简化。

自定义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);
            }
    }
}

包含我想用作点击处理程序的方法的活动:

public class SudokuGameActivity extends Activity {

    //Left out everything else from the activity.

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

1 个答案:

答案 0 :(得分:1)

设置一个OnClickListener(在CellContainerGroup中)将调用该方法:

private OnClickListener mListener = new OnClickListener() {

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

其中propagateEventCellContainerGroup中的方法,如下所示:

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

以及mContext这样的Context引用,如下所示:

private Context mContext;

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

不要忘记设置mListener

CellGrid[i][j].setOnClickListener(mListener);
相关问题