How to programmatically align a textview, a seekbar and another textview in the same line in android studio?
Textview seekbar textview
I have written the following code snippet:
LinearLayout.LayoutParams sblayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); sblayoutParams.setMargins(10, 100, 10, 10); tv1.setText("0"); tv1.setBackgroundResource(R.color.yellow); tv1.setLayoutParams(sblayoutParams); sb1.setLayoutParams(sblayoutParams); tv2.setText("100"); tv2.setBackgroundResource(R.color.green); tv2.setLayoutParams(sblayoutParams); LinearLayout sblinearLayout = findViewById(R.id.rootContainer); // Add SeekBar to LinearLayout if (sblinearLayout != null) { sblinearLayout.addView(sb1); sblinearLayout.addView(tv1); sblinearLayout.addView(tv2); }
The following is my XML file:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/rootContainer" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" android:orientation="vertical"> </LinearLayout>
Current scenario:
Advertisement
Answer
Currently the LinearLayout
has android:orientation="vertical"
, so the View
s appear one below the other.
If you want them to appear side by side, you should change the orientation to android:orientation="horizontal"
Or you can set the orientation programmatically:
sbLinearLayout.setOrientation(LinearLayout.HORIZONTAL)
Change the width to WRAP_CONTENT
and set a weight so all three View
s get a third of the available width:
LinearLayout.LayoutParams sblayoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); sblayoutParams.setMargins(10, 100, 10, 10); sbLayoutParams.setWeight(1.0f); tv1.setText("0"); tv1.setBackgroundResource(R.color.yellow); tv1.setLayoutParams(sblayoutParams); sb1.setLayoutParams(sblayoutParams); tv2.setText("100"); tv2.setBackgroundResource(R.color.green); tv2.setLayoutParams(sblayoutParams); LinearLayout sblinearLayout = findViewById(R.id.rootContainer); // Add SeekBar to LinearLayout if (sblinearLayout != null) { sblinearLayout.addView(tv1); sblinearLayout.addView(sb1); sblinearLayout.addView(tv2); }