2011-11-03 70 views
0

我查看获取按钮动态

<Button android:id="@+id/button1" android:text="Text 1" 
android:layout_height="wrap_content" 
       android:layout_width="fill_parent"></Button> 

     <Button android:id="@+id/button2" android:text="Text 2" 
android:layout_height="wrap_content" 
       android:layout_width="fill_parent"></Button> 

     <Button android:id="@+id/button3" android:text="Text 3" 
android:layout_height="wrap_content" 
       android:layout_width="fill_parent"></Button> 

     <Button android:id="@+id/button4" android:text="Text 4" 
android:layout_height="wrap_content" 
       android:layout_width="fill_parent"></Button> 

的文本值我有按钮的不确定的量,需要让你在触摸事件文本。

我该怎么做?

Tnks很多。

编辑:

感谢所有,这是你的答案的结果=>https://play.google.com/store/apps/details?id=br.com.redrails.torpedos 我的应用:d

回答

1

如果你命名你所有的按钮 “按钮1,按钮2,BUTTON3 ......” 你可以这样做:

for(int i = 1; i <= buttonCount; i++) { 
    int id = getResources().getIdentifier("button" + i, "id", getPackageName()); 
    findViewById(id).setOnClickListener(this); 
} 

其中buttonCount是您拥有的按钮数量。这种方法将被放置在onCreate()

然后为您的onClick:

public void onClick(View v) { 
    if (v instanceof TextView) { 
     CharSequence text = ((TextView) v).getText(); 
     // Do fun stuff with text 
    } 
} 

你的活动将需要实现OnClickListener

+0

就是这样!完善! Very tnks –

+0

没问题...请记住,此操作可能非常慢,但如果可以避免,建议不要使用它。 –

0

您可以通过使用getText()方法得到一个按钮上的文字。

+0

是的,但我需要得到前一个按钮的ID与ontouch事件......怎么样? –

0

下面是一个完整的例子:

import android.os.Bundle; 
import android.widget.Toast; 
import android.widget.Button; 
import android.view.View; 
import android.view.View.OnClickListener; 

public class MainActivity extends Activity implements OnClickListener 
{ 
    private Button btn1, btn2, btn3, btn4; // You can add more if you like 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     btn1 = (Button) findViewByID(R.id.button1); 
     btn2 = (Button) findViewByID(R.id.button2); 
     btn3 = (Button) findViewByID(R.id.button3); 
     btn4 = (Button) findViewByID(R.id.button4); 
     // declare the other buttons if any 

     btn1.setOnClickListener(this); 
     btn2.setOnClickListener(this); 
     btn3.setOnClickListener(this); 
     btn4.setOnClickListener(this); 
     // register the other buttons as well if any 
    } 

    @Override 
    public void onClick(View v) 
    { 
     String text = ((Button) v).getText(); 
     Toast.makeText(this, "You clicked " + text , Toast.LENGTH_SHORT).show(); 
    } 
} 
+0

Very Tnks Fouad,但我想象一百个按钮......当然,这不工作很好= \ –

+0

,你可以包括其他按钮,它会工作得很好。 –

0

你可以这样做:

Button button4= (Button) findViewById(R.id.button4); 
text = button4.getText();