Issue
I have a Layout with a ScrollView where I want to programatically insert another layout. So this
<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">
inserted into this
<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>
And I insert it like that
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);
}
But when I run the app the inserted layout is twice as wide as it should.
How it should look (How it looks in the Android Studio Editor)
Vs how it looks when inserted into the ScrollView
So far I have tried to use a ConstraintLayout which didn't work. Or using different layout weights.
I hope you can help me with this.
Solution
You can try use the Layout Parameters for setting view custom params for height and width
as
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
Or for better results, you can use the recycler view to achieve the same result in better handling and just to create a single instance of adapter, which will be completely dependent on you list you are passing to the recycler view. also less code work to handle and debug.
Answered By - amimic11
Answer Checked By - Clifford M. (JavaFixing Volunteer)