2011-08-18 75 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(); 
     } 

希望这可以帮助你。

相关问题