Android 动态获取按钮的文本值

Android 动态获取按钮的文本值,android,Android,我的看法 我有一个未定义的按钮数量,需要让你在触摸事件文本 我怎么做 有很多 编辑: 谢谢大家,这是你们答案的结果=> 我的应用程序:D您可以使用该方法获取按钮的文本。以下是一个完整的示例: <Button android:id="@+id/button1" android:text="Text 1" android:layout_height="wrap_content" android:layout_width="fill_parent">&l

我的看法


我有一个未定义的按钮数量,需要让你在触摸事件文本

我怎么做

有很多

编辑:

谢谢大家,这是你们答案的结果=>
我的应用程序:D

您可以使用该方法获取按钮的文本。

以下是一个完整的示例:

<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> 
你可以做:

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();
    }
}

如果您将所有按钮命名为“button1、button2、button3…”,则可以执行以下操作:

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

您的活动将需要实现
OnClickListener

是,但我需要在发生ontouch事件之前获取按钮的id。。。怎么会?非常奇怪,但我想一百个按钮。。。此操作不正常=\当然,您可以包括其他按钮,它将正常工作。没问题……请记住,此操作可能非常缓慢,如果可以避免,则不建议使用此操作。
for(int i = 1; i <= buttonCount; i++) {
    int id = getResources().getIdentifier("button" + i, "id", getPackageName() );
    findViewById(id).setOnClickListener(this);
}
public void onClick(View v) {
    if (v instanceof TextView) {
        CharSequence text = ((TextView) v).getText();
        // Do fun stuff with text
    }
}