我有一个带有简单自定义布局的DialogFragment(TextView和EditView)。
当用户单击Dialog的Positive Button时,应用程序应将EditText字段中的用户输入保存到变量“playerName”中。无论我在尝试什么,Toast-output总是显示一个空字符串“”,或者更确切地说,当我将文本硬编码到EditText中时(如XML中所示),它始终显示该文本。
用户对键盘输入所做的更改不会在代码中得到处理,任何想法都有什么问题?
DialogFragment
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.addplayer_fragment, null);
// declare the text input field
EditText playerNameEdit = (EditText)view.findViewById(R.id.playerNameEdit);
//read text into String
String playerName = playerNameEdit.getText().toString();
// make toast with input of the edit text field
Toast.makeText(getActivity().getApplicationContext(), playerName, Toast.LENGTH_SHORT).show();
}
布局(addplayer_fragment.xml)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding= "10dip" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TestText"
android:id="@+id/playerNameEdit"/>
</LinearLayout>
</RelativeLayout>
答案 0 :(得分:0)
您还可以在片段
中使用以下方法void showDialog()
{
View view=getActivity().getLayoutInflater().inflate(R.layout.addplayer_fragment,null);
final EditText playerNameEdit = (EditText)view.findViewById(R.id.playerNameEdit);
new AlertDialog.Builder(getActivity())
.setTitle("Title here")
.setMessage("Message here")
.setView(view)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String name=playerNameEdit.getText().toString();
Toast.makeText(getActivity(), name, Toast.LENGTH_SHORT).show();
}
})
.create().show();
}
答案 1 :(得分:0)
试试这段代码:
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Your Title");
LayoutInflater inflater = getActivity().getLayoutInflater();
View dialogView = inflater.inflate(R.layout.addplayer_fragment, null);
builder.setView(dialogView)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
EditText valueView = (EditText) dialogView.findViewById(R.id.playerNameEdit);
if(valueView == null) Log.d("VIEW", "NULL");
else{
String playerName = playerNameEdit.getText().toString();
Toast.makeText(getActivity(),playerName , Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return builder.create();
}