【问题标题】:Layout stretched after inserting it into a ScrollView将布局插入 ScrollView 后拉伸
【发布时间】:2022-02-01 13:51:56
【问题描述】:

我有一个带有 ScrollView 的布局,我想在其中以编程方式插入另一个布局。所以这个

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="96dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#56565A"
    android:orientation="vertical">

插入此

<HorizontalScrollView
        android:id="@+id/live_scroll_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:id="@+id/live_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal" />
    </HorizontalScrollView>

然后我就这样插入

for (int i = 0; i < exercise.targetSets; i++) {
            LayoutInflater factory = LayoutInflater.from(getContext());
            View myView = factory.inflate(R.layout.live_set_item, null);
            TextView setName = (TextView) myView.findViewById(R.id.current_set);
            setName.setText(String.format("SET %d", i+1));

            scrollView.addView(myView);
        }

但是当我运行应用程序时,插入的布局是它应该宽的两倍。

How it should look (How it looks in the Android Studio Editor)

Vs how it looks when inserted into the ScrollView

到目前为止,我尝试使用无效的 ConstraintLayout。或者使用不同的布局权重。

希望你能帮我解决这个问题。

【问题讨论】:

    标签: java android user-interface layout


    【解决方案1】:

    您可以尝试使用布局参数来设置视图自定义参数的高度和宽度

    作为

    val linearLayout = LinearLayout(requireActivity())
            val lp: LinearLayout.LayoutParams = (ParentView)findViewById(R.id.parent_view);
            val left_margin: Int = 3 //e.g
            val top_margin = 0
            val right_margin: Int = 3 //e.g
            val bottom_margin = 0
            lp.setMargins(left_margin, top_margin, right_margin, bottom_margin)
            val size = Point()
            val w = requireActivity().windowManager
            w.defaultDisplay.getSize(size)
            lp.width = size.x - 40
            lp.height = size.y
            linearLayout.layoutParams = lp
    

    或者为了获得更好的结果,您可以使用recycler view 来实现更好的处理效果,并且只需创建一个适配器实例,这将完全取决于您传递给回收器视图的列表。处理和调试的代码工作量也更少。

    【讨论】:

    • 有效!谢谢你。感谢您提供有关 Recycler View 的提示。我会调查的。
    • 嗨,FritzK,欢迎您……:)。
    猜你喜欢
    • 1970-01-01
    • 2011-02-12
    • 1970-01-01
    • 2012-02-17
    • 2013-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多