我目前在做一个包含自定义警告对话框一个Android应用程序。 它包含一个按钮,但我不能设置按钮的保证金。 的代码如下所示。 setmargin方法是行不通的
AlertDialog.Builder myDialog = new AlertDialog.Builder(Login.this);
Button button = new Button(Login.this);
button.setText("Send");
LayoutParams buttonLayoutParams
= new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
button.setLayoutParams(buttonLayoutParams);
resetPassword=editText.getText().toString();
LinearLayout layout = new LinearLayout(Login.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(textView);
layout.addView(editText);
layout.addView(button);
myDialog.setView(layout);
Answer 1:
写下面的代码来设置保证金,它可以帮助你。
AlertDialog.Builder myDialog = new AlertDialog.Builder(Login.this);
Button button = new Button(Login.this);
EditText editText = new EditText(Login.this);
TextView textView = new TextView(Login.this);
button.setText("Send");
LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buttonLayoutParams.setMargins(50, 10, 0, 0);
button.setLayoutParams(buttonLayoutParams);
String resetPassword = editText.getText().toString();
LinearLayout layout = new LinearLayout(Login.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(textView);
layout.addView(editText);
layout.addView(button);
myDialog.setView(layout);
myDialog.show();
使用LinearLayout.LayoutParams或RelativeLayout.LayoutParams根据子视图父布局
Answer 2:
buttonLayoutParams.bottomMargin
buttonLayoutParams.topMargin
buttonLayoutParams.leftMargin
buttonLayoutParams.rightMargin
可用于设置边距
Answer 3:
如果你使用LinearLayout.LayoutParams但如果你使用ViewGroup.LayoutParams的setMargin()方法是可用的。 迪帕克·Keshariya提到了这一点,但并不表示它在这么多的话。
Answer 4:
You can set in LinearLayout margin
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);
文章来源: How to set margin dynamically in Android?