问题
I have created a custom ViewGroup in which I create a couple of custom child Views (in the java code, not xml). Each of these childs needs to have the same onClick event.
The method to handle these click events resides in the activity class that uses the layout. How do I set this method as the onClick handler for all child views?
Here is my code simplified.
The custom 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);
}
}
}
The activity that contains the method I want to use as the click handler:
public class SudokuGameActivity extends Activity {
//Left out everything else from the activity.
public void cellViewClicked(View view) {
{
//stuff to do here...
}
}
回答1:
Setup a single OnClickListener
(in CellContainerGroup
) which will call that method:
private OnClickListener mListener = new OnClickListener() {
@Override
public void onClick(View v) {
CellContainerGroup ccg = (CellContainerGroup) v.getParent();
ccg.propagateEvent(v);
}
}
where propagateEvent
is a method in CellContainerGroup
like this:
public void propagateEvent(View cell) {
((SudokuGameActivity)mContext).cellViewClicked(cell);
}
and where mContext
is a Context
reference like this:
private Context mContext;
public CellContainerGroup(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
//...
Don't forget to set the mListener
:
CellGrid[i][j].setOnClickListener(mListener);
来源:https://stackoverflow.com/questions/13976774/set-individual-onclick-events-in-custom-viewgroup