2014-02-27 22 views
1

我想知道當某個特定的edittext爲空或非空時是否可以更改按鈕的顏色。就像edittext爲空時,按鈕顯示「ADD」,當它不爲空時,顯示「CHANGE」。有人能幫我嗎?先謝謝你。EditText爲空時更改按鈕顏色 - android

+0

你想改變按鈕顏色或按鈕的文字? –

+0

按鈕文本和顏色。謝謝。 – jajaja

+0

按照我的回答 –

回答

3

關於Button Text集,如:

if(editText.getText().toString.length()>0){ 
yourbutton.setText("Change"); 
}else{ 
yourbutton.setText("Add"); 
} 

而且如果實現EditText addTextChangedListener然後

editText.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence str, int start, int count, int after) { 

     } 

     @Override 
     public void onTextChanged(CharSequence str, int start, int before, int count) { 

     } 

     @Override 
     public void afterTextChanged(Editable str) { 
      if(str.toString().trim().length()>0){ 
       yourbutton.setText("Change"); 
      }else{ 
       yourbutton.setText("Add"); 
      } 
     } 
    }); 

而且你還可以設置Button Text Color動態,如:

yourbutton.setTextColor(Color.BLUE); 

,並瞭解更多信息,請訪問到:http://developer.android.com/reference/android/content/res/ColorStateList.html

+0

謝謝,但是當我輸入一個文本到edittext,按鈕不會改變,它只會改變,當我刷新它。是否有可能在不刷新頁面的情況下自動變化? – jajaja

+0

@jajaja您嘗試以編程方式更改它,按照我yourbutton.setTextColor(Color.BLUE); –

+0

謝謝!它正在工作!投票並檢查你!謝謝! :) – jajaja

2
// try this way 

**activity_main.xml** 
<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical"> 

    <EditText 
     android:id="@+id/edtValue" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" /> 

    <Button 
     android:id="@+id/btnAddOrChange" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginTop="5dp" 
     android:text="Add"/> 
</LinearLayout> 


**MyActivity.java** 
public class MyActivity extends Activity{ 

    private EditText edtvalue; 
    private Button btnAddOrChange; 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     edtvalue = (EditText) findViewById(R.id.edtValue); 
     btnAddOrChange = (Button) findViewById(R.id.btnAddOrChange); 

     edtvalue.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

      } 

      @Override 
      public void onTextChanged(CharSequence s, int start, int before, int count) { 

      } 

      @Override 
      public void afterTextChanged(Editable s) { 
       if(s.toString().trim().length()>0){ 
        btnAddOrChange.setText("Change"); 
       }else{ 
        btnAddOrChange.setText("Add"); 
       } 
      } 
     }); 
    } 

} 
2

要更改Button's文字和background color做這樣的事情

​​