2016-07-25 206 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