作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图在 ScrollView 中动态地实现一个可滚动的水平线性布局,但 View (LinearLayout) 不滚动!
此方法从服务器获取一些结果,然后动态创建 View 。 “layout_services”是在 xml 文件中实现的垂直 LinearLayout。
瞧,代码:
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);
}
}
最佳答案
使用 HorizontalScrollView
而不是 ScrollView
作为要水平滚动的线性布局的父级
关于android - 如何在 scrollview 中动态添加可滚动的水平 Linearlayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51588603/
我是一名优秀的程序员,十分优秀!