Как динамически установить маржу в Android?

В настоящее время я делаю приложение для 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);

person user1057197    schedule 16.06.2012    source источник


Ответы (4)


Напишите ниже код для установки маржи, это может вам помочь.

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 в соответствии с родительским макетом дочернего представления.

person Dipak Keshariya    schedule 16.06.2012
comment
нет не работает. он показывает ошибку добавления приведения к buttonlayoutparams в методе setMargin. - person user1057197; 16.06.2012
comment
Пожалуйста, импортируйте импорт android.widget.LinearLayout.LayoutParams; в вашей деятельности. - person Dipak Keshariya; 16.06.2012

Просто разделяю немного другой подход.

Вместо приведения к LinearLayout.LayoutParams, RelativeLayout.LayoutParams и т. д. вы можете просто приводить к MarginLayoutParams.

Приведение к MarginLayoutParams лучше, потому что вы можете позже обновить свой макет, и вам не нужно возвращаться к своему коду Java, чтобы изменить с LinearLayout на RelativeLayout или любой другой тип макета.

Вы можете сделать что-то вроде:

MarginLayoutParams layoutParams = (MarginLayoutParams) view.getLayoutParams();

// Set bottom margin
layoutParams.bottomMargin = x;

// Set top margin
layoutParams.topMargin = x;

// Set left margin
// This won't have effect if you set any relative margin (start) previously or in the layout.xml
layoutParams.leftMargin = x;

// Set left margin
// This won't have effect if you set any relative margin (end) previously or in the layout.xml
layoutParams.rightMargin = x;

// Set start margin
layoutParams.setMarginStart(x);

// Set end margin
layoutParams.setMarginStart(x);

// Set all left, top, right, bottom margins at once
// Note that here, left and right margins are set (not start/end).
// So, if you have used start/end margin before (or via layout.xml), 
// setting left/right here won't have any effect.
layoutParams.setMargins(left, top, end, bottom)

// Then re-apply the layout params again to force the view to be re-draw
// This step may not be necessary because depending where you set the margin, 
// view is already scheduled to be drawn
// For any case, to ensure the view will apply the new margin, call:
view.setLayoutParams(layoutParams);
person W0rmH0le    schedule 26.06.2019

buttonLayoutParams.bottomMargin
buttonLayoutParams.topMargin
buttonLayoutParams.leftMargin
buttonLayoutParams.rightMargin

можно использовать для установки полей

person user1458071    schedule 16.06.2012
comment
Вы устанавливаете параметры макета для своего LinearLayout? - person user1458071; 16.06.2012

Метод setMargin() доступен, если вы используете LinearLayout.LayoutParams, но не при использовании ViewGroup.LayoutParams. Дипак Кешария намекает на это, но не говорит об этом так много слов.

person Klepto    schedule 08.05.2014