Home > Mobile >  Create discrete SeekBar programmatically in Android
Create discrete SeekBar programmatically in Android

Time:11-30

Creating a discrete SeekBar in Android in a layout file works fine, SeekBar object is visible and can be used programmatically after having been inflated from the layout file:

<SeekBar
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@ id/seekbar"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:theme="@style/Base.Widget.AppCompat.SeekBar.Discrete"/>

But I need to create the discrete SeekBar programmatically, WITHOUT inflating it from a layout file.

So I tried:

AppCompatSeekBar seekBar = new AppCompatSeekBar(context, null, R.style.Base_Widget_AppCompat_SeekBar_Discrete);

This does NOT work. seekBar does not show and keeps invisible, whatever I try and whatever LayoutParameters I use.

Creating a non discrete SeekBar, however, works fine, seekBar is visible and can be used:

AppCompatSeekBar seekBar = new AppCompatSeekBar(context);

What am I doing wrong when creating a discrete SeekBar programmatically?

CodePudding user response:

You need to use a ContextThemeWrapper and apply the style as a Theme. Then you have to pass this into the AppCompatSeekBar constructor with the defStyleAttr to be 0.

Example:

//get your parent View Group
RelativeLayout parent = findViewById(R.id.parentRoot);
//Use a ContextThemeWrapper and setup your style as a Theme
ContextThemeWrapper wrappedContext = new ContextThemeWrapper(this, com.google.android.material.R.style.Base_Widget_AppCompat_SeekBar_Discrete);
//initialize AppCompatSeekBar using the above ContextThemeWrapper
AppCompatSeekBar seekBar = new AppCompatSeekBar(wrappedContext, null, 0);
//set to the seekBar your LayoutParams eg: (ConstraintLayout.LayoutParams, RelativeLayout.LayoutParams, LinearLayout.LayoutParams)
seekBar.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
seekBar.setMax(10);
//finally add it to your parent View Group
parent.addView(seekBar);

Result:

seekbar

  • Related