2016-11-30 125 views
0

我在RelativeLayout中有一個manualy createt TextView數組。所有展示除了完美:onclicklistener不行 代碼:textview onclicklistener不工作

private RelativeLayout mRLMain; 
private TextView [] mTV; 
private OnClickListener mTextOnClickListener; 

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    mRLMain = (RelativeLayout) findViewById(R.id.rlMainGame); 
    mTV = new TextView[20]; 

    mSqueareLayout = new RelativeLayout.LayoutParams(mSquareWidth,mSquareWidth); 

    for (i = 0; i < 20; i++) { 
     mTV [i] = new TextView(MainActivity.this); 
     mTV [i].setBackgroundColor(Color.RED); 
     mTV [i].setTextColor(Color.WHITE); 
     mTV [i].setX(i+100); 
     mTV [i].setId(i); 

     mTV [i].setOnClickListener(mTextOnClickListener); 

     mRLMain.addView(mTV [i], mSqueareLayout); 
    } 

    mTextOnClickListener = new OnClickListener() { 
     @Override 
     public void onClick(View view) { Log.d("XXX","CLICK"); } 
    }; 
} 

嘗試用

mTV [i].setFocusable(false); 
mTV [i].setFocusableInTouchMode(false); 
mTV [i].setClickable(true); 
mTV [i].setDuplicateParentStateEnabled(false); 

並沒有什麼: - 沒有錯誤 - 沒有日誌的

回答

2

初始化您clickListener stting之前。所以更改訂單可以解決您的問題。

for (i = 0; i < 20; i++) { 
    mTV [i] = new TextView(MainActivity.this); 
    mTV [i].setBackgroundColor(Color.RED); 
    mTV [i].setTextColor(Color.WHITE); 
    mTV [i].setX(i+100); 
    mTV [i].setId(i); 

    // Set clickListener 
    mTV [i].setOnClickListener(new OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Log.d("XXX","CLICK"); 
      Toast.makeText(MainActivity.this, "Position "+ i, Toast.LENGTH_LONG).show(); 
     }); 

    mRLMain.addView(mTV [i], mSqueareLayout); 
} 
+0

還是什麼都沒有.... – S2K

+0

檢查更新的答案 – Rahul

+0

Yes..Thank的......工作。但爲什麼我不能用setX的和塞蒂 - 我需要在將來使用它......反正 - 謝謝.... – S2K

0

如果ClickListener將有一些複雜的邏輯,它甚至更好地將其提取到單獨的類(內部類,例如)。

// same top part 
for (int i = 0; i < 20; i++){ 
      mTV [i] = new TextView(MainActivity.this); 
      mTV [i].setBackgroundColor(Color.RED); 
      mTV [i].setTextColor(Color.WHITE); 
      mTV [i].setX(i+100); 
      mTV [i].setId(i); 

      // main change here 
      mTV [i].setOnClickListener(new CustomClickListener(i)); 

      mRLMain.addView(mTV [i], mSqueareLayout); 
     } 
    } 

static class CustomClickListener implements View.OnClickListener { 

    private int viewId; 

    // another option is to pass a reference to a view here 
    // private View view; 
    // in this case, you should create appropriate constructor 

    public CustomClickListener(int viewId) { 
     this.viewId = viewId; 
    } 

    @Override 
    public void onClick(View view) { 
     Log.d("XXX","Click on view " + viewId); 
     // some logic on this view 
    } 
}