【问题标题】:How to add scrollable horizontal Linearlayout inside scrollview dynamically如何在滚动视图中动态添加可滚动的水平线性布局
【发布时间】:2018-07-30 15:15:47
【问题描述】:

我正在尝试在动态方法中在滚动视图内实现可滚动的水平线性布局,但视图(线性布局)不滚动!

此方法从服务器获取一些结果,然后动态创建视图。 "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);
        }
    }

【问题讨论】:

    标签: android


    【解决方案1】:

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

    【讨论】:

    • 总是使用水平滚动视图来水平滚动
    【解决方案2】:

    您可以尝试嵌套滚动视图。

    在此处阅读文档:Nested Scroll View

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 2016-11-17
      • 1970-01-01
      • 2013-06-29
      相关资源
      最近更新 更多