2012-06-16 51 views
25

Tôi hiện đang thực hiện một ứng dụng Android có chứa hộp thoại cảnh báo tùy chỉnh. Nó chứa một nút, nhưng tôi không thể đặt lề cho nút. mã được đưa ra dưới đây. phương pháp setmargin không được làm việcLàm cách nào để đặt ký tự động trong Android?

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); 

Trả lời

44

Viết Sau Mã để thiết lập Margin, nó có thể giúp bạn.

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(); 

Sử dụng LinearLayout.LayoutParams hoặc RelativeLayout.LayoutParams theo bố trí cha mẹ của đứa trẻ xem

+0

nó không hoạt động. nút bên trong alertdialog – user1057197

+0

Vui lòng xem Câu trả lời đã chỉnh sửa của tôi, nó đang hoạt động cho tôi. –

+1

không, nó không hoạt động. nó cho thấy một lỗi thêm cast vào buttonlayoutparams trong phương thức setMargin. – user1057197

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

có thể được sử dụng để thiết lập lề

+0

không hoạt động – user1057197

+1

Bạn có đang đặt tham số bố cục cho 'LinearLayout' của mình không? – user1458071

2

Phương pháp setMargin() có sẵn nếu bạn đang sử dụng LinearLayout.LayoutParams nhưng không nếu bạn đang sử dụng ViewGroup.LayoutParams. Dipak Keshariya ám chỉ điều này nhưng không nói điều đó bằng nhiều từ.

0
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); 
Các vấn đề liên quan