我创建了一个自定义 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);
}
}
其中 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);
关于android - 在自定义 ViewGroup 中设置单个 onClick 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13976774/