将EditText的文本显示到TextView中

时间:2011-06-30 22:28:16

标签: android

描述我的应用程序的功能:我已经在相对布局中添加了TextView,EditText和一个按钮。我要做的就是:当用户在EditText中写入内容并按下按钮时,EditText的内容出现在TextView中(就像聊天虚拟聊天一样)。一切都很完美,但是当EditText为空,按下按钮时,TextView中会出现一个空行(我不想......)。虽然我试图使用如果空行仍然出现在TextView中来解决它。如果你能提供帮助我真的很棒!比你提前!

这是我的代码:

package teiath.android.appliacation;

import android.app.Activity; 
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class M_chat extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /**Code for the scroll bars in the TextView. */
        final TextView tv = (TextView)findViewById(R.id.TEXT_VIEW);
        tv.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars

        /** Code for the scroll bars in the EditText. */
        final EditText wr = (EditText)findViewById(R.id.EDIT_TEXT);
        wr.setMovementMethod(new ScrollingMovementMethod());//for the scroll bars

        final Button button = (Button) findViewById(R.id.btn1);//find the button by id in main.xml
        button.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // Perform action on click


                String wrcontent = wr.getText().toString();//gets the text of the EditText and put it in "tvcontent" variable. 
                String tvcontent = tv.getText().toString();//gets the text of the textView and put it in "tvcontent" variable. 


                if (wrcontent!="")//if the EditText is not empty
                {
                    //check if the TextView is empty or not
                    if (tvcontent!="")//If it is not empty... 
                    {
                        tv.setText(tvcontent + "\n" + wrcontent);//add its current(TextView's text) text, new line and the text of the EditText as the new text of TextView.
                        //tv.setVisibility(0);//makes visible the textView with the cloud1.png background
                        wr.setText("");//set the text of the Edit Text as empty
                        //wrcontent = "";
                    }
                    else//if the TextView is empty...
                    {
                        tv.setText(wrcontent);//add the text of the editText as the new text of the TextView
                        wr.setText("");
                    }
                }
                /**if (wrcontent=="")
                {

                }*/
                //finish();
            }
        });


    }
}

1 个答案:

答案 0 :(得分:1)

不要使用!=“”进行字符串比较。要检查空文本,请使用

之类的内容
if ( wrcontent != null && wrcontent.trim().length() == 0 ) {

更好的是,在代码中加入Guava libraries