如何使用EditText从自定义对话框窗口获取输入?我使用下面的代码得到一个空指针异常,editText为null,我尝试了这篇文章How to get data from a custom dialog box上的建议,但它没有用。这是我的代码:
package se315.journal;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MarkActivity extends AppCompatActivity
{
ArrayList<Item> items;
EditText editText;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mark);
DBHelper dbHelper = new DBHelper(this);
editText = new EditText(this);
Mark mark = (Mark) getIntent().getSerializableExtra("Mark");
Student student = dbHelper.getStudent(mark.getStudentRegister());
Subject subject = dbHelper.getSubject(mark.getSubjectId());
String title = student.getSurName().substring(0, 1) + ".\t" +student.getName() + ",\t" + subject.getName();
getSupportActionBar().setTitle(title);
items = dbHelper.getSubjectItems(subject);
ListView listView = (ListView) findViewById(R.id.mark_lv);
final ListAdapter listAdapter = new ListAdapter(this, R.layout.list_item, items);
listView.setAdapter(listAdapter);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l)
{
final Item item = items.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(MarkActivity.this);
LayoutInflater inflater = MarkActivity.this.getLayoutInflater();
builder.setView(inflater.inflate(R.layout.mark_dialog, null));
editText = (EditText) findViewById(R.id.mark_dialog_et);
builder.setMessage("Дүнгээ оруулна уу").setTitle("Сонгосон шалгалт/даалгаварын дүнг өөрчлөх");
builder.setPositiveButton("Өөрчлөх", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
item.setMark(Integer.valueOf(editText.getText().toString()));
}
});
builder.setNegativeButton("Болих", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
return false;
}
});
}
}
对话框窗口的xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="@+id/mark_dialog_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp"
android:hint="@string/mark_tv_mark"
android:inputType="number" />