2011-06-30 47 views
0

描述我的应用程序的功能:我已经将相对布局放入TextView,EditText和一个按钮中。我想要做的是:当用户在EditText中写入内容并按下按钮时,EditText的内容出现在TextView中(就像聊天虚拟聊天一样)。一切都很完美,但是当EditText为空时,按钮被按下时,TextView中出现一条空行(我不想......)。尽管我试图用一个如果空行仍然出现在TextView中的方法来解决它。如果你能帮忙,我会非常棒!比你提前!将EditText的文本显示为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

不要使用= “” 的字符串比较!要检查空文本,使用类似

if (wrcontent != null && wrcontent.trim().length() == 0) { 

更重要的是,包括Guava libraries在你的代码。

+0

您还可以检查“”.equals(wrcontent),但修剪选项也可以帮助检查空白 – Spidy

+0

谢谢soooooooo你们俩很多!!!!我刚刚解决了它!对不起,我的愚蠢问题。我可能会回来更多! :) – anna