2011-08-18 69 views
1

我創建了一個使用循環的5個可點擊文本視圖的數組,設置了它們的參數(大小,顏色,背景圖像,可點擊等)並設置了onClickListener,並調用該數組「myArrayofTVs」。他們的ID已經使用循環int(i)設置。我有另一個預定義的數組,其中包含文本字符串,並且其他文本視圖出現在佈局中。後來在onclick方法,並且所有的按鈕/點擊textviews做的非常類似的東西,我希望能夠做這樣的事情:以編程方式創建按鈕的onClick方法

@Override 
public void onClick(View v) { 

if(v == myArrayofTVs[i]) {    //using 'i' here doesn't seem to work 
tv1.setText(myArray2[i]); 
tv2.setText(myArray2[i+1];} 
etc 
etc} 

我已經嘗試了各種不同的充方式,如使用開關case語句(真的不想使用它們,因爲會有很多重複的代碼,並且每次我希望在未來添加新的textview /按鈕時,我都必須添加一個新的case語句)。是否有無論如何使用一個語句,將基於給定的變量id處理所有按鈕/可單擊的文本視圖,還是必須爲每個變量使用單獨的case/tag/id語句?

非常感謝提前!

回答

0

將視圖添加到您的ViewGroup並使用getChildAt(int index)和getChildCount()創建一個循環。你可以循環所有兒童/視圖的ViewGroup中,你可以用

if(child instanceof TextView) 

檢查,如果他們是正確的類型。然後,您可以將視圖轉換回TextView/Button/View並執行您想要執行的操作。

但它聽起來像你想要的東西的列表。所以我建議使用帶有適配器的ListView。

0

我真的認爲你應該使用由Android提供的id而不是試圖比較對象。你的代碼無法工作的原因,如果它有足夠的循環周圍,這有點神祕,但我會試着通過比較ID和非對象來儘可能地平行示例中看到的switch語句。

for(int i = 0; i < myArrayofTvs.length; i++) 
    if(v.getId() == myArrayofTVs[i].getId()) {    
     tv1.setText(myArray2[i]); 
     tv2.setText(myArray2[i+1]; 
    } 
} 

此外,顯然你會想要避免在第二個內部語句中出現數組越界的錯誤。

0

我所做的是以編程方式膨脹我的自定義佈局,並使用onClickListener從該自定義佈局膨脹的按鈕上。然後與一個特定的項目進行交互,我得到了被點擊的視圖的父視圖,例如。您的按鈕,然後使用該視圖來更改視圖的屬性。這是我的代碼片段。 alertDialog的onClick是我去改變新膨脹視圖的值的地方。

  // if an edit button of numbers row is clicked that number will be edited 
     if (view.getId() == R.id.NumberRowEditButton) 
     { 
      AlertDialog.Builder alert = new AlertDialog.Builder(this); 

      alert.setTitle("Contact edit"); 
      alert.setMessage("Edit Number"); 

      // Set an EditText view to get user input 
      final EditText input = new EditText(this); 

      input.setSingleLine(); 
      alert.setView(input); 

      alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
      { 
       public void onClick(DialogInterface dialog, int whichButton) 
       { 
        // get input 
        Editable value = input.getText(); 
        if(value.length() > 4){ 

         View tempView = (View) view.getParent(); 
         TextView tempTV = (TextView) tempView.findViewById(R.id.numberRowTextView); 
         String number = tempTV.getText().toString(); 

         tempTV.setText(value.toString()); 
        } 
        else 
        { 
         // ...warn user to make number longer 
         final Toast msgs = Toast.makeText(ContactEdit.this, "Number must be over 4 digits.", Toast.LENGTH_SHORT); 
         msgs.setGravity(Gravity.CENTER, msgs.getXOffset()/2, msgs.getYOffset()/2); 
         msgs.show(); 
        } 
       } 
      }); 

      alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
      { 
       public void onClick(DialogInterface dialog, int whichButton) 
       { 
        // cancel the dialog 
        dialog.cancel(); 
       } 
      }); 

      alert.show(); 
     } 

希望這可以幫助你。

相關問題