2011-02-17 38 views
6

Tôi đang viết một ứng dụng Android đơn giản có một văn bản và một nút. Nhấp vào nút sẽ hiển thị một hộp thoại cảnh báo với văn bản được nhập trong văn bản. Cho rằng tôi có đoạn mã sau:Đọc văn bản của EditText trong android

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

    Button b=(Button)findViewById(R.id.ok); 

    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setMessage("Text in edit box: " + txt) 
     .setCancelable(false) 
     .setTitle("Info") 
     .setPositiveButton("Done", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) {} 
    }); 

    final AlertDialog alert = builder.create(); 

    // set click listener on the flag to show the dialog box 
    b.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      EditText et=(EditText)findViewById(R.id.entry); 
      txt=et.getText().toString(); 
      alert.show(); 
     } 
    }); 

} 

Đoạn mã trên đang chạy tốt nhưng hộp thoại cảnh báo cho thấy văn bản trong hộp soạn thảo: null Nó sẽ hiển thị nội dung của hộp chỉnh sửa.

Trả lời

3

Thời gian báo cáo kết quả

builder.setMessage("Text in edit box: " + txt) 

đã thực hiện txt biến có null trong nó. lý do này.

Cố gắng đưa câu lệnh này được thực hiện sau khi nhấp vào nút. Chắc chắn sẽ xóa 100% vấn đề

1

Vì bạn xây dựng cảnh báo, txt trong cảnh báo là rỗng, khi bạn bấm nút hiển thị cảnh báo txt của hộp thoại là rỗng, bạn nên cảnh báo sau khi bạn nhấp vào nút

+1

không bạn nghĩ rằng bạn nên bỏ phiếu lên câu trả lời nếu ai đó đã đăng nó. thay vì sau đó đăng một câu trả lời seprate. Guys làm cho cộng đồng này trở thành một lợi ích cho tất cả thay vì sau đó làm cho một thị trường cá – Javanator

6

ghi dòng này ở bên ngoài nút bấm

EditText et=(EditText)findViewById(R.id.entry); 
txt=et.getText().toString(); 
1
Use as following: 

    public void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 

      Button b = (Button) findViewById(R.id.button1); 


      builder = new AlertDialog.Builder(this); 

      b.setOnClickListener(new View.OnClickListener() { 
       public void onClick(View v) { 
        EditText et = (EditText) findViewById(R.id.editText1); 
        txt = et.getText().toString(); 
        builder.setMessage("Text in edit box: " + txt) 
        .setCancelable(false) 
        .setTitle("Info") 
        .setPositiveButton("Done", 
          new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
         } 
        }); 
        final AlertDialog alert = builder.create(); 
        alert.show(); 
       } 
      }); 

     } 
Các vấn đề liên quan