2011-11-03 136 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();