2016-08-21 237 views
-5

我想在Toast中顯示7 EditText的信息,所以我把編輯文本信息放在7個字符串變量中,但我不知道如何。 這裏是我寫的東西:在Toast中顯示字符串變量

public class MainActivity extends Activity { 
     EditText ed1; 
     EditText ed2; 
     EditText ed3; 
     EditText ed4; 
     EditText ed5; 
     EditText ed6; 
     EditText ed7; 
     Button btn; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.main2); 
      showinfo(); 
     } 

     private void showinfo() { 
      ed1= (EditText) findViewById(R.id.editText1); 
      ed2= (EditText) findViewById(R.id.editText2); 
      ed3= (EditText) findViewById(R.id.editText3); 
      ed4= (EditText) findViewById(R.id.editText4); 
      ed5= (EditText) findViewById(R.id.editText5); 
      ed6= (EditText) findViewById(R.id.editText6); 
      ed7= (EditText) findViewById(R.id.editText7); 
      btn= (Button) findViewById(R.id.button1); 
      /////// 
      btn.setOnClickListener(new OnClickListener() { 

       @Override 
       public void onClick(View arg0) { 
        // TODO Auto-generated method stub 
        String str1 = ed1.getText().toString(); 
        String str2 = ed2.getText().toString(); 
        String str3 = ed3.getText().toString(); 
        String str4 = ed4.getText().toString(); 
        String str5 = ed5.getText().toString(); 
        String str6 = ed6.getText().toString(); 
        String str7 = ed7.getText().toString(); 
        //////////// 
        Toast.makeText(getApplicationContext(), ,Toast.LENGTH_LONG).show(); 
       } 
      }); 
     } 

如何顯示在Toast的所有字符串變量?

+1

您是否在尋找'Concatination'?只需使用StringBuilder。 – Enzokie

回答

3

如果你想顯示的EditText所有內容在一個Toast,那麼就使用串聯

String concatenatedText = str1 + str2 + str3 + ... 

StringBuilder類:

StringBuilder sb = new StringBuilder(); 
sb.append(str1); 
sb.append(str2); 
sb.append(str3); 
String concatenatedText = sb.toString(); 

,並簡單地將結果作爲第二個參數,如下:

Toast toast = Toast.makeText(context, concatenatedText, duration); 
0

這就是android建議

Context context = getApplicationContext(); 
CharSequence text = "Hello toast!"; 
int duration = Toast.LENGTH_SHORT; 

Toast toast = Toast.makeText(context, text, duration); 
toast.show(); 

,你可以肯定這樣做:

上下文的背景下= getApplicationContext(); 字符串文本= STR1 + STR2 + STR3 + ...

StringBuilder sb = new StringBuilder(); 
sb.append(str1); 
sb.append(str2); 
sb.append(str3); 
String finalMsgText = sb.toString(); 

Toast toast = Toast.makeText(context, finalMsgText , Toast.LENGTH_SHORT); 
toast.show(); 

與路要走一點是,

當 STR1 = 「你好」; str2 =「Xoce」; str3 =「你好嗎?」;

然後在敬酒的味精會像:

「HelloXoceHow是你嗎?」;

所以一切融合在一起是沒有SENCE爲應用程序的用戶...

解決方法:

StringBuilder sb = new StringBuilder(); 
sb.append(str1).append(", ");; 
sb.append(str2).append(", ");; 
sb.append(str3); 
String finalMsgText = sb.toString(); 

Toast toast = Toast.makeText(context, finalMsgText , Toast.LENGTH_SHORT); 
toast.show();