2012-12-20 22 views
2

我創建了一個自定義ViewGroup,在其中創建了幾個自定義子視圖(在java代碼中,而不是xml)。 這些孩子中的每一個都需要具有相同的onClick事件。在自定義ViewGroup中設置單個onClick事件

處理這些點擊事件的方法駐留在使用佈局的活動類中。如何將此方法設置爲所有子視圖的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); 
      } 
    } 
} 

包含我想作爲click處理程序使用方法的活動:

public class SudokuGameActivity extends Activity { 

    //Left out everything else from the activity. 

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

回答

1

設置一個OnClickListener(在CellContainerGroup),它會調用該方法:

private OnClickListener mListener = new OnClickListener() { 

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

其中propagateEvent是一個會面HOD在CellContainerGroup這樣的:

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); 
+0

謝謝,這是完美的!但我只有一個問題。當我嘗試點擊其中一個單元格時,它似乎總是點擊右上角的單元格。任何想法這可能是什麼原因? –

+0

@BrunoCarvalhal我不認爲這與OnCLickListener有關,看看你的單元格是否正確放置在父類中(因此它們不在彼此之上)。 – Luksprog

+0

好的,謝謝你的幫忙! –

相關問題