0
我想對齊在RelativeLayout片段中的for循環中動態生成的按鈕,但按鈕在相同的位置重疊,我查看了很多其他的帖子和我仍然不知道如何解決它,我知道使用linearLayout將解決問題,但按鈕是錯誤的大小和位置,並出於某種原因,我不能將linearLayout添加到RelativeLayout的。我粘貼了2個代碼示例,我需要一個解決方案。提前致謝。Android Align按鈕動態地在RelativeLayout中片段
下面是我的代碼(嘗試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;
你可以更具體地在哪裏添加它們請。我得到了NullPointerException:佈局參數不能爲null爲RelativeLayout.LayoutParams params =(RelativeLayout.LayoutParams)button.getLayoutParams(); –