我试图垂直对齐在RelativeLayout片段中的for循环中动态生成的按钮,但按钮在同一位置重叠,我已经查看了很多其他帖子,我仍然不知道如何修复它,helpppppp
我知道使用linearLayout会解决问题,但是按钮的大小和位置都是错误的,由于某些原因我无法将linearLayout添加到relativeLayout。我已经粘贴了2个代码示例,我需要一个解决方案。提前谢谢。
以下是我的代码(尝试1:相对布局中的对齐按钮):
View view = inflater.inflate(R.layout.home, container, false);
RelativeLayout relativeLayout = new RelativeLayout(getActivity().getApplicationContext());
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
List<String> test_list = Arrays.asList("sup1", "sup2", "sup3");
for (int i = 0; i < test_list.size(); i++) {
final String test_name = test_list.get(i);
Button button = new Button(getActivity());
button.setText("Test" + test_name + " " + i);
button.setId(i);
if(i > 0){
lp.addRule(RelativeLayout.RIGHT_OF, (i-1));
}
relativeLayout.addView(button, lp);
button.setOnClickListener(new View.OnClickListener() {@Override
public void onClick(View v) {
FragmentManager fragmentmanager = getFragmentManager();
FragmentTransaction transaction = fragmentmanager.beginTransaction(); // allows attach,detach,etc
transaction.replace(R.id.DB2Home, newFragment, "ChooseCategory").addToBackStack(null).commit();
}
});
}
((ViewGroup) view).addView(relativeLayout);
return view;
(尝试2:在线性布局中对齐按钮并添加到相对布局)
View view = inflater.inflate(R.layout.home, container, false);
LinearLayout linearLayout = new LinearLayout(getActivity().getApplicationContext());
linearLayout.setOrientation(LinearLayout.VERTICAL);
List<String> test_list = Arrays.asList("sup1", "sup2", "sup3");
for (int i = 0; i < test_list.size(); i++) {
final String test_name = test_list.get(i);
Button button = new Button(getActivity());
button.setText(test_name);
button.setId(i);
linearLayout.addView(button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
FragmentManager fragmentmanager = getFragmentManager();
FragmentTransaction transaction = fragmentmanager.beginTransaction(); // allows attach,detach,etc
transaction.replace(R.id.DB2Home, newFragment,"ChooseCategory").addToBackStack(null).commit();
}
});
}
// Doesn't work for relative layout
// RelativeLayout relativeLayout = (RelativeLayout) view.findViewById(R.id.homescreen);
//relativeLayout.addView(linearLayout);
//((ViewGroup) view).addView(relativeLayout);
((ViewGroup) view).addView(linearLayout);
return view;
答案 0 :(得分:0)
您可以通过以下代码访问它:
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)button.getLayoutParams();
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
params.addRule(RelativeLayout.LEFT_OF, R.id.id_to_be_left_of);
button.setLayoutParams(params); //causes layout update