2012-05-01 60 views
-3

大家好我是新的android开发,其实它是我的第一个应用程序。我想知道如何获得按下按钮的价值

<button 
android:text="1" /> 

在上面的标签中,text是按钮的值?如果是的话,我怎么能得到这个值或者将它存储在一个变量中。如果没有,那么如何在Android中的任何按钮后面定义一个值?

+1

这是很基本的功能。你甚至看过API吗? Button的扩展Textiviews(http://developer.android.com/reference/android/widget/TextView.html)。 – Gophermofur

回答

1

是其按钮的值,使用下面的代码获取按钮的文本。

Button b = (Button)findViewById(R.id.button1); 
String buttonText = b.getText().toString(); 

函数调用

b.setOnClickListener(new Button.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        // TODO Auto-generated method stub 
        function(); 
    } 
}); 
+0

当点击一个按钮时,这个onClick()方法会自动调用吗? – baig772

+0

代码改变你可以看到 –

+0

我明白了。我想要的是同样的东西,但点击:(。如何一个函数将被称为点击任何按钮时? – baig772

3

首先,您需要给该按钮的ID,像这样:

<Button 
android:id="@+id/buttonId" 
android:text="1" 
/> 

然后在你的代码做这样的事情:

Button b = (Button)findViewById(R.id.buttonId); 
b.getText(); // returns the value of your text. 
1
<Button 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="ButtonText" /> 

...

@Override 
public void onCreate(Bundle savedInstanceState) { 
    Button btn = (Button) findViewById(R.id.button1); 
    String text = btn.getText().toString(); 

}