我试图根据我的seekbar的进度使4个不同的文本视图可见(一次可见一个)。我将文本视图设置为不可见,而seekbar的最大值为100。对于低于24的值,它工作得很好,但是当seekbar超过25时,应用程序就会崩溃。
我是一个绝对的初学者,我想自学,我想过用while循环来代替,但我也不能让它工作。
我将非常感激任何帮助。
程式碼
public class MainActivity extends AppCompatActivity {
SeekBar seekBar;
TextView textView;
TextView textView2;
TextView textView3;
TextView textView4;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
seekBar = findViewById(R.id.seekBar);
seekBar.setMax(100);
textView = (TextView)findViewById(R.id.textView);
button = (Button)findViewById(R.id.button);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (seekBar.getProgress() < 24) {
textView.setVisibility(View.VISIBLE);
} else if (seekBar.getProgress() >= 25 && seekBar.getProgress() < 49) {
textView2.setVisibility(View.VISIBLE);
} else if (seekBar.getProgress() >= 50 && seekBar.getProgress() < 74) {
textView3.setVisibility(View.VISIBLE);
} else if (seekBar.getProgress() >= 75) {
textView4.setVisibility(View.VISIBLE);
}
activity_main:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<include layout="@layout/content_main" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:srcCompat="@android:drawable/ic_dialog_email" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
你已经使用了 findViewById
将资源链接到您的 textView
对象。你需要对 textView2
, textView3
和 textView4
. 我想你得到的是 NullPointerException
当你试图调用 textView2
.