2016-07-25 203 views
7

我在Android应用程序中创建了一个带有EditText的AlertDialog,但默认边距看起来确实关闭。我试图指定页边距如下:在AlertDialog中设置EditText的边距

android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(SpinActivity.this); 
      builder.setTitle("Edit Spin Tags"); 
      builder.setMessage("(separate tags with commas)"); 

      // set input 
      int margin = 10; 
      final EditText input = new EditText(SpinActivity.this); 
      input.setSingleLine(); 
      input.setText(spinTags.toString().replace("[", "").replace("]", "")); 
      builder.setView(input, margin, 0, margin, 0); 

但是,从下图中可以看出,它没有应用所需的效果。

enter image description here

其他选项我试过包括将在LinearLayout中输入和设置使用的LayoutParams设置AlertDialog欣赏到的LinearLayout前的利润。

如何在AlertDialog中设置EditText的边距?

+0

尝试从这个答案http://stackoverflow.com/questions/20761611/how-to-set-解决方案编辑文本-topmargins-in-dp-programatically – wanpanman

+0

@wanpanman刚试过​​这个,很不幸 – scientiffic

回答

6

其实您的解决方案可以正常使用,但builder.setView(input, margin, 0, margin, 0);发生在“像素”值的参数。所以20的值非常小。要么使用较高的余量值,例如在100年代。或使用此功能从DP转换为像素

public static int dpToPx(int dp) 
{ 
    return (int) (dp * Resources.getSystem().getDisplayMetrics().density); 
} 

然后,

int margin = dpToPx(20); 
+0

完美!谢谢你为我解决这个难题。 – scientiffic

0

在不同的布局文件中定义您的Edittext,同时在该布局中设置适当的边距。膨胀该布局,然后将其设置为对话框视图。

2

您可以将LinearLayout作为EditText的父项。然后向EditText提供保证金。

private void createDialog() { 
    AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    builder.setTitle("Demo"); 
    builder.setMessage("Some demo message"); 
    LinearLayout parentLayout = new LinearLayout(this); 
    EditText editText = new EditText(this); 
    editText.setHint("Some text"); 
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
      LinearLayout.LayoutParams.MATCH_PARENT, 
      LinearLayout.LayoutParams.MATCH_PARENT); 

    // call the dimen resource having value in dp: 16dp 
    int left = getPixelValue((int)getResources().getDimension(R.dimen.activity_horizontal_margin)); 
    int top = getPixelValue((int)getResources().getDimension(R.dimen.activity_horizontal_margin)); 
    int right = getPixelValue((int)getResources().getDimension(R.dimen.activity_horizontal_margin)); 
    int bottom = getPixelValue((int)getResources().getDimension(R.dimen.activity_horizontal_margin)); 

    // this will set the margins 
    layoutParams.setMargins(left, top, right, bottom); 

    editText.setLayoutParams(layoutParams); 
    parentLayout.addView(editText); 
    builder.setView(parentLayout); 
    builder.setPositiveButton("OK", null); 
    builder.create().show(); 
} 

private int getPixelValue(int dp) { 
    Resources resources = getResources(); 
    return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 
      dp, resources.getDisplayMetrics()); 
} 

欲了解更多,您可以访问http://www.pcsalt.com/android/set-margins-in-dp-programmatically-android/

+0

谢谢你的建议,但是这个没有效果 – scientiffic

+0

它适用于我。谢谢。 – ACAkgul