android - 如何在滚动视图中动态添加可滚动的水平线性布局
问题描述
我正在尝试在动态方法中在滚动视图内实现可滚动的水平线性布局,但视图(线性布局)不滚动!
此方法从服务器获取一些结果,然后动态创建视图。“layout_services”是在 xml 文件中实现的垂直线性布局。
瞧,代码:
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
作为要水平滚动的线性布局的父级
推荐阅读
- github - 如何从私有仓库 GitHub 获取信息
- azure - 尝试通过 terraform 添加 LinuxDiagnostic Azure VM Extension 并出现错误
- python - 我如何制作这样的“订购”产品应用程序
- php - 访问 Webroot 之外的文件/目录 - PHP
- excel - Excel中基于下拉值的条件格式
- python - 如何在 Python 上转换为匈牙利语
- ios - Swift 将运算符与 RxSwift 框架中的 `withLatestFrom` 等功能相结合
- php - PHP:合并数组并添加键值
- java - 将持久化实体保留在事务之外
- angular - 读取刚刚写入的文件与 Ionic4 文件插件没有相同的数据