2015-11-23 249 views
1

此刻,我正在編寫提交按鈕以從EditText獲取文本。我已經實施了檢測空文本的必要條件。然而,當我運行模擬器時,我插入了一串隨機字符並點擊提交,我得到了Toast消息 - 請在框中填寫一些東西?獲取文本無法正常工作

請參閱代碼和截圖

Diary_Entry:

package com.example.ali.googleandroid; 

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Toast; 

public class Diary_Entry extends AppCompatActivity { 

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

     EditText entryBox = (EditText) findViewById(R.id.diaryentry_box); 
     Button submitEntry = (Button) findViewById(R.id.submit); 

     final String writtenText = entryBox.getText().toString().trim(); 

     submitEntry.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       // check for empty text if submit button is pressed 
       if (writtenText.isEmpty() || writtenText.length() == 0 || writtenText.equals("") || writtenText == null) { 

        Toast.makeText(getApplicationContext(), "Please write something in the box!", 
          Toast.LENGTH_LONG).show(); 
       } else { 
        // pass the text to display entry box and close activity 
        Intent i = new Intent(Diary_Entry.this, Entry_Dislplay.class); 
        i.putExtra("Submitted Entry", writtenText); 
        startActivity(i); 
        finish(); 
       } 
      } 
     }); 

    } 


    public void GoBack(View v) { 
     // close current activity and go back to previous activity 
     onBackPressed(); 
     finish(); 
    } 


} 

回答

6

您需要檢索Edittext的文字,當你按下按鈕,不是之前

移動此行

final String writtenText = entryBox.getText().toString().trim(); 

的onClick回調中:

public void onClick(View v) { 
    String writtenText = entryBox.getText().toString().trim(); 
    .... 
} 
+0

對不起原諒我的失誤 –

+0

不客氣:) –