簡體   English   中英

如何動態地在scrollview中添加可滾動的水平Linearlayout

[英]How to add scrollable horizontal Linearlayout inside scrollview dynamically

我試圖在方法中動態地在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);
        }
    }

使用HorizontalScrollView而不是ScrollView作為要水平滾動的線性布局的父級

您可以嘗試嵌套滾動視圖。

閱讀此處的文檔: 嵌套滾動視圖

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM