gpt4 book ai didi

android - 如何在 scrollview 中动态添加可滚动的水平 Linearlayout

转载 作者:行者123 更新时间:2023-11-29 16:39:22 25 4
gpt4 key购买 nike

我试图在 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);
}
}

最佳答案

使用 Horizo​​ntalScrollView 而不是 ScrollView 作为要水平滚动的线性布局的父级

关于android - 如何在 scrollview 中动态添加可滚动的水平 Linearlayout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51588603/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com