我是一个android新手,作为一个测试,我想创建一个在EditText中插入文本并显示它的程序。当EditText中没有值时,我希望我的程序显示一个对话框,指出“请先插入注释”。但是获取EditText字段的值
comments.getText().toString()==null
会产生错误。这里是我的代码:
package android.insertcomments;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class InsertCommentsActivity extends Activity {
/** Called when the activity is first created. */
public Button insertcom;
public Button displaycom;
public EditText comments;
public Button savecom;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Insert Comments App");
setContentView(R.layout.home);
insertcom = (Button) findViewById(R.id.insertcom);
displaycom = (Button) findViewById(R.id.displaycom);
insertcom.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
addListenerOnButton();
}
});
displaycom.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
if (comments.getText().toString()==null)
noCommentsErrormessage();
else
// Display comments
}
});
}
public void addListenerOnButton() {
setContentView(R.layout.comments_adder);
savecom = (Button) findViewById(R.id.savecom);
savecom.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
comments = (EditText) findViewById(R.id.commentsEditText);
Toast.makeText(InsertCommentsActivity.this, comments.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
}
public void noCommentsErrormessage() {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error!")
.setMessage("Please insert comments first")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
我的代码应该如下方式工作: 1.当你点击“插入注释”按钮,文本编辑字段显示了,你可以输入你的意见 2.当你点击“显示注释”按钮,程序检查EditText字段中是否存在某个值 -if不显示对话框,显示“请先插入注释” -if yes显示TextEdit字段的内容。
任何帮助将不胜感激。 提前感谢您。