【发布时间】:2015-09-08 17:42:38
【问题描述】:
问题:
- 我们如何通过 LayoutParams 限制 AlertDialog 中包含的 EditText 的宽度?
假设:
- 我有一个 AlertDialog,它的宽度设置得相当大;
- 在此对话框中存在一个 EditText,其宽度应为其容器的 ~1/3;
小细节:
-
EditText 有以下类型:
- TYPE_CLASS_TEXT
- TYPE_TEXT_FLAG_CAP_CHARACTERS
- TYPE_TEXT_FLAG_NO_SUGGESTIONS
AlertDialog 的高度/宽度以像素为单位,通过密度进行缩放(参见代码);
混乱:
- 鉴于以下代码,为什么 EditText 最终会跨越 AlertDialog 的整个宽度?
守则:
- 请注意,EditText 通过 LayoutParams 设置为 {100,100},而 AlertDialog 设置为 {900,500}
private void show_activation_prompt()
{
// =============================================================
// ======== create EditText which filters text =================
// =============================================================
// filter for alphanumerics, insert dashes during entry, capitalize, and turn off suggestions
final TextWatcher textEditorWatcher = new SafeTextWatcher(); //custom
final LayoutParams lparams = new LayoutParams(100,100);
final EditText edittext= new EditTextPersist(mContext);
edittext.addTextChangedListener(textEditorWatcher);
edittext.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS |
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
);
edittext.setLayoutParams(lparams);
//edittext.setEms(10); //doesn't work either
// =============================================================
// ======== create alert dlg, set btn callbacks ================
// =============================================================
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setPositiveButton("Upgrade", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
String activationKey = edittext.getText().toString();
on_key_entered(activationKey);
}
} );
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton)
{
post_activation_result(QlmLicense.ACTIVATION_INVALID);
}
} );
// =============================================================
// ======== configure the AlertDialog/EditText =================
// =============================================================
int nWidth, nHeight;
final float scale = mContext.getResources().getDisplayMetrics().density;
nWidth = (int) (900 * scale + 0.5f);
nHeight = (int) (500 * scale + 0.5f);
builder.setView(edittext)
.setMessage("Enter an Activation Key:")
.setTitle("Upgrade From Trial Version")
.setCancelable(false)
.show()
.getWindow()
.setLayout(nWidth,nHeight);
}
【问题讨论】:
-
在为
layout添加dialog的视图之前,尝试将您的edittext设置为LinearLayout并为此margin设置layout。希望这个答案可以帮助你:stackoverflow.com/questions/9345735/… -
啊,是的。非常感谢。这回答了限制 AlertDialog 宽度的“如何完成”的问题。一个更有用和直接的问题是“为什么 LayoutParams 在应用于 AlertDialog 中的 EditText 时不起作用”。我会进行编辑!感谢您提供方法:)
-
鉴于更具体的问题,如果您找到一种将您找到的解决方案与使用 LayoutParams 相结合的方法,如果您发布一个答案,我将很乐意接受您的答案!
-
如果它可以帮助你很好。我现在不在家,所以我回家时会发布答案^^。谢谢你:)
标签: android android-edittext android-alertdialog