以编程方式定义android SeekBar

时间:2017-06-24 18:22:52

标签: android android-seekbar

我在我的应用程序中使用了SeekBar。目前,此SeekBar在xml文件中定义:

<SeekBar
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/Base.Widget.AppCompat.SeekBar.Discrete"/>

它看起来不错,但我想以编程方式定义此元素,所以我已经添加了这个:

SeekBar seekBar = new SeekBar(getContext(), null, R.style.Widget_AppCompat_SeekBar_Discrete);

然后seekBar是不可见的。有谁知道什么是错的? 如果我只使用它,它就可见:

SeekBar seekBar = new SeekBar(getContext();

但我需要打勾。

2 个答案:

答案 0 :(得分:0)

尝试将可见性设置为可见:

seekBar.setVisibility(VISIBLE);

并且请记住将其添加到布局(线性,相对等)

以编程方式添加视图时,必须将其添加到布局。否则它是不可见的,因为它没有添加到视图

答案 1 :(得分:0)

这对我有用:

首先,创建一个布局(例如layout_seekbar.xml):

<?xml version="1.0" encoding="utf-8"?>
<SeekBar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/Widget.AppCompat.SeekBar.Discrete" />

然后,您可以以编程方式在代码中添加搜索栏:

SeekBar bar = (SeekBar)LayoutInflater.from(this).inflate(R.layout.layout_seekbar, null);
bar.setMax(10);
...
bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
    ...
    }
    public void onStartTrackingTouch(SeekBar seekBar) {}
    public void onStopTrackingTouch(SeekBar seekBar) {}
});

myLinearLayout.addView(bar);

打招呼,​​希望有帮助

相关问题