我想要添加的这两个按钮可以动态布局。
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);
两者都没有改变任何东西。有任何想法吗? 谢谢!
答案 0 :(得分:1)
您可能必须使用
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);
答案 1 :(得分:0)
我尝试使用LinearLayout。它工作正常。
您的布局文件将类似于
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="@+id/rlParent">
</LinearLayout>
</RelativeLayout>
在oncreate里面,我们需要像
一样 Button settingsButton = new Button(this);
settingsButton.setText("Settings");
settingsButton.setTextColor(Color.BLACK);
settingsButton.setHeight(LayoutParams.WRAP_CONTENT);
settingsButton.setWidth(LayoutParams.WRAP_CONTENT);
View view = findViewById(R.id.rlParent);
((ViewGroup) view).addView(settingsButton,0);
Button entryButton = new Button(this);
entryButton.setText("add Entry");
entryButton.setTextColor(Color.BLACK);
entryButton.setHeight(LayoutParams.WRAP_CONTENT);
entryButton.setWidth(LayoutParams.WRAP_CONTENT);
((ViewGroup) view).addView(entryButton,1);