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

标签 android android-custom-view

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

处理这些点击事件的方法驻留在使用布局的 Activity 类中。如何将此方法设置为所有 subview 的 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);
            }
    }
}

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

public class SudokuGameActivity extends Activity {

    //Left out everything else from the activity.

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

最佳答案

设置一个将调用该方法的 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);

关于android - 在自定义 ViewGroup 中设置单个 onClick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13976774/

相关文章:

Android libgdx 首选项迷路了

android - 在 Seekbars 步骤上方添加不同字体大小的标签,垂直对齐到 seekbars thumb

android - GridView 在一行中绘制其元素

android - 无法关闭 android 中的警报对话框

android - CustomLayout 的 subview 中出现意外的命名空间前缀应用程序

java - 围绕 java 类传递数据

android - 用 RxJava 替换监听器

java.net.SocketException : recvfrom failed: EBADF (Bad file descriptor) Android

java - 找不到如何转换Tango点云

Android listView 在错误的地方添加动态 View