【问题标题】:Set individual onClick events in custom ViewGroup在自定义 ViewGroup 中设置单个 onClick 事件
【发布时间】:2012-12-20 16:47:07
【问题描述】:

我创建了一个自定义 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...
    }
}

【问题讨论】:

    标签: android android-custom-view


    【解决方案1】:

    设置一个 OnClickListener(in 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);
    }
    

    其中mContextContext 引用,如下所示:

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

    别忘了设置mListener:

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

    【讨论】:

    • 谢谢,太好了!不过我只有一个问题。当我尝试单击其中一个单元格视图时,它似乎总是单击右上角的单元格。知道这可能是什么原因吗?
    • @BrunoCarvalhal 我认为这与OnCLickListener 完全无关,看看您的单元格是否正确放置在父单元中(因此它们不会相互重叠)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2011-01-20
    • 2014-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多