gpt4 book ai didi

java - 以编程方式为 Android 按钮添加边距

转载 作者:行者123 更新时间:2023-12-01 13:28:51 25 4
gpt4 key购买 nike

我有这两个按钮,我想动态添加到可能的布局中。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com