如果在Android中EditText为空,如何更改TextView的背景颜色?

时间:2015-05-21 13:06:18

标签: android background android-edittext textview textchanged

我正在使用Fragment类,我希望在更改文本后更改TextViewEditText为空的颜色。我可以在文本更改时更改TextView的颜色,但是当文本清除时,TextView背景颜色不会更改为前一个颜色。在文本更改后TextView为空时,EditText更改背景颜色的可能方法有哪些?我的代码如下所示:

public class Fragment_AboutUs extends android.app.Fragment {
TextView about_btn_call_customer;
TextView about_btn_Submit;
EditText about_feedback;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.layout_fragment_about_us, container, false);
    //reference section
    about_btn_call_customer= (TextView) rootView.findViewById(R.id.about_btn_call_customer);
    about_btn_Submit=(TextView)rootView.findViewById(R.id.about_btn_Submit);
    about_feedback=(EditText)rootView.findViewById(R.id.about_feedback);


        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {




            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {


            }

            @Override
            public void afterTextChanged(Editable s) {

                String textinEdit=  about_feedback.getText().toString().trim();
                if (textinEdit != null) {
                    about_btn_Submit.setBackgroundColor(getResources().getColor(R.color.light_green));

                }else if (textinEdit ==""){
                    about_feedback.setBackgroundColor(getResources().getColor(R.color.grayColor));
                }

            }
        };

    about_feedback.addTextChangedListener(textWatcher);






    return rootView;
}

}

提前感谢...任何形式的帮助都将受到赞赏......

2 个答案:

答案 0 :(得分:1)

选中count onTextChanged并选择颜色:

@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
   int color = count == 0 ? R.color.light_green : R.color.grayColor;
   about_btn_Submit.setBackgroundColor(getResources().getColor(color));
 }

你可以为其他TextView

做同样的事情

答案 1 :(得分:0)

试试这个,

   TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.length() == 0) {
                // for empty text color
                about_btn_Submit.setBackgroundColor(getResources().getColor(R.color.grayColor));
            } else { 
                // for non empty field color
                about_btn_Submit.setBackgroundColor("change your color");
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

        @Override
        public void afterTextChanged(Editable s) {}
    };