2012-07-27 117 views
2

我有一個按鈕(像)是從字符串資源寫入的,點擊我想切換到不喜歡&反之。比較字符串存儲在Android的字符串資源?

如何比較按鈕包含像或不同於字符串資源?

我string.xml包含

<string name="like">Like</string> 
<string name="unlike>unlike</string> 
+0

看到我的答案並接受正確的答案。 – 2012-07-27 07:13:52

回答

2

您可以使用getString方法

if(btn1.getText().toString().compareTo(getResources().getString(R.string.app_name)) == 0) 
    { 
     // do some code here 
    }  
+0

說按鈕ID是btn1&在字符串資源字符串名稱是像&不像然後 – napster 2012-07-27 07:01:40

2

下面的代碼使用

Button button = (Button)findViewById(R.id.btn1); 

if(button.getText().toString().equals(getString(R.string.like))) 
{ 
    button.setText(getString(R.string.unlike)); 
} 
else 
{ 
    button.setText(getString(R.string.like)); 
} 
0

嘗試爲:

String text = getResources().getString(R.string.texttest); 
Button button = (Button)this.findViewById(R.id.btntest); 
button.setOnClickListener(new OnClickListener() { 
    @Override 
    public void onClick(View v) { 
    if(button.getText().toString().equals(text)) 
    { 
     // do some code here 
    } 
    } 
}); 
0

您可以用這種方式檢索標籤(按鈕上的文本)。

Button button=(Button) findViewById(R.id.button1); 
Log.d("Text",""+button.getText()); 
0

你可以這樣做::

String value=buttonname.getText().toString 

//this Will Give the Text On the Button 

現在比較喜歡這種方式的價值,並更改名稱的按鈕::

if(value.equals("Like")) 
{ 
    buttonname.setText("UnLike"); 
} 
else 
{ 
    buttonname.setText("Like"); 
} 
4

中試試這個..

bt.setText(getString(R.string.txt1)); 
bt.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       myStr=bt.getText().toString(); 
       if((myStr.equals(getString(R.string.txt1)))){ 
        bt.setText(getString(R.string.txt2)); 
       }else if((myStr.equals(getString(R.string.txt2)))){ 
        bt.setText(getString(R.string.txt1)); 
       } 




      } 
     }); 

在string.xml中

<string name="txt1">11111111111</string> 
<string name="txt2">2222222222222222</string>