用于文本输入的 Android Studio 警报对话框块空间
Posted
技术标签:
【中文标题】用于文本输入的 Android Studio 警报对话框块空间【英文标题】:Android studio Alert dialog block spaces for input in text 【发布时间】:2021-09-21 23:50:42 【问题描述】:我发现这比处理 XML 文件更困难。如何在警报对话框的文本输入中阻止空格?例如,它是如何工作的,因为我在互联网上没有找到太多关于此的信息。谢谢
private void RequestNewGroup()
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialog);
builder.setTitle("Enter Group Name ");
final EditText groupNameField = new EditText(MainActivity.this);
groupNameField.setHint("");
groupNameField.setFilters(new InputFilter[]new InputFilter.LengthFilter(25));
builder.setView(groupNameField);
builder.setPositiveButton("Create", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialogInterface, int i)
String groupName = groupNameField.getText().toString();
if (TextUtils.isEmpty(groupName))
Toast.makeText(MainActivity.this, "Please write Group Name...", Toast.LENGTH_SHORT).show();
else
CreateNewGroup(groupName);
);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
@Override
public void onClick(DialogInterface dialogInterface, int i)
dialogInterface.cancel();
);
builder.show();
【问题讨论】:
【参考方案1】:I find this more difficult than working on an XML file.
您可以(并且可能应该)创建具有自己的视图/XML 文件的自定义对话框。
为此,扩展 DialogFragment:
public class MyDialog extends DialogFragment
EditText editText;
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState)
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// get your custom layout
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.my_custom_layout, null);
builder.setView(view).setCancelable(false);
editText = view.findViewById(R.id.editText);
// add your code here
XML (R.layout.my_custom_layout):
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_
android:layout_>
<EditText
android:id="@+id/editText"
android:layout_
android:layout_
android:text="foo"
android:digits="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
android:inputType="textFilter" />
</androidx.constraintlayout.widget.ConstraintLayout>
在 MainActivity 中:
public void openDialog(Context context)
MyDialog dialog = new MyDialog();
dialog.show(getSupportFragmentManager(), "myDialog");
还要检查Android disable space only for Edittext 以禁用 XML 中的空格和
https://www.youtube.com/watch?v=ARezg1D9Zd0&t=446s&ab_channel=CodinginFlow 获取有关自定义对话框以及如何发送和接收信息的更深入教程。
【讨论】:
非常感谢!以上是关于用于文本输入的 Android Studio 警报对话框块空间的主要内容,如果未能解决你的问题,请参考以下文章