2

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

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

这是我的简化代码。

自定义视图组:

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...
    }
}
4

1 回答 1

1

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

private OnClickListener mListener = new OnClickListener() {

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

像这样propagateEvent的方法在哪里:CellContainerGroup

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);
于 2012-12-20T17:06:34.777 回答