我有这两个按钮,我想动态添加到可能的布局中。
Button settingsButton = new Button(this);
settingsButton.setText("Settings");
View view = findViewById(R.id.content_frame);
int width = view.getWidth() / 5;
int height = view.getHeight() / 5;
settingsButton.setLayoutParams(new LinearLayout.LayoutParams(Math.max(width, height), Math.min(width, height)));
((ViewGroup) view).addView(settingsButton);
Button entryButton = new Button(this);
entryButton.setText("add Entry");
entryButton.setLayoutParams(new LinearLayout.LayoutParams(Math.max(width, height), Math.min(width, height)));
((ViewGroup) view).addView(entryButton);
现在为了使按钮不会出现在彼此之上,我尝试给第二个按钮留出边距,例如:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Math.max(width, height), Math.min(width, height));
params.setMargins(Math.max(width, height), 0, 0, 0);
然后或者
((ViewGroup) view).addView(entryButton, params);
或
entryButton.setLayoutParams(params);
((ViewGroup) view).addView(entryButton);
两者都没有改变任何东西。有任何想法吗? 谢谢!
最佳答案
你可能必须使用
ViewGroup.MarginLayoutParams.setMargins
做这样的事情就可以了:
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10, 10, 10, 10);
Button button = new Button(getActivity());
button.setText("My Button");
linearLayout.addView(button, layoutParams);
关于java - 以编程方式为 Android 按钮添加边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21672211/