我正在尝试在方法中动态地在scrollview内部实现可滚动的水平Linearlayout,但是视图(LinearLayout)无法滚动!
此方法从服务器获取一些结果,然后动态创建视图。 “ layout_services”是一个垂直的LinearLayout,它在xml文件中实现。
Voila代码:
for (ServiceResult serviceResult : response.getResult()) {
LinearLayout.LayoutParams textViewParams = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textViewParams.setMargins(15, 15, 15, 15);
textViewParams.gravity = Gravity.RIGHT;
TextView textView = new TextView(getActivity());
textView.setPadding(5, 5, 5, 5);
textView.setText(serviceResult.getCategory());
textView.setLayoutParams(textViewParams);
textView.setTextColor(Color.WHITE);
textView.setBackgroundColor(Color.LTGRAY);
if (!serviceResult.getServices().isEmpty()) {
layout_services.addView(textView);
LinearLayout.LayoutParams scrollLayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
ScrollView scrollView = new ScrollView(getActivity());
scrollView.setLayoutParams(scrollLayoutParams);
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setPadding(5, 5, 5, 5);
LinearLayout.LayoutParams horizontalLayoutParams =
new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
horizontalLayoutParams.gravity = Gravity.RIGHT;
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
linearLayout.setLayoutParams(horizontalLayoutParams);
scrollView.addView(linearLayout);
for (int i = 0; i < serviceResult.getServices().size(); i++) {
int finalI = i;
Button btn = new Button(getActivity());
btn.setText(serviceResult.getServices().get(finalI).getName());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300, 200);
params.setMargins(15, 15, 15, 15);
params.gravity = Gravity.LEFT;
btn.setLayoutParams(params);
btn.setTextColor(Color.BLACK);
btn.setOnClickListener(view -> {
});
linearLayout.addView(btn);
}
layout_services.addView(scrollView);
}
}
答案 0 :(得分:3)
使用HorizontalScrollView
代替ScrollView
作为要水平滚动的线性布局的父级
答案 1 :(得分:0)
您可以尝试嵌套滚动视图。
在此处阅读文档:Nested Scroll View