我是Android新手,当我按下特定按钮时,我需要创建一个AlertDialog。 AlertDialog有一个Seekbar,seekBar用于更改我的应用程序的音量。但我不能让它发挥作用。你能帮我么?谢谢。
我收到此错误:
java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.SeekBar.setMax(int)'
我的代码如下:
public class Setting extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
public AlertDialog AlarmVolume(View view) {
/*
This part of code creates a dialog which has a seekbar for volume.
*/
AlertDialog.Builder builder = new AlertDialog.Builder(this);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.volume_dialog, (ViewGroup) findViewById(R.id.settingsItem));
builder.setView(v).setTitle("Adjust Alarm Volume").setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//TODO save new volume amount
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
SeekBar seekbarVolume = (SeekBar)findViewById(R.id.volumeSeekBar);
final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
seekbarVolume.setMax(audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM));
seekbarVolume.setProgress(audioManager.getStreamVolume(AudioManager.STREAM_ALARM));
seekbarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, progress, 0);
}
});
return builder.create();
}
}
这是我的volum_dialog.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SeekBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/volumeSeekBar"
android:layout_marginTop="15sp"
android:layout_weight="1" />
</LinearLayout>
答案 0 :(得分:1)
您正试图在您的contextView(R.layout.activity_setting)中找到您的搜索栏:
SeekBar seekbarVolume = (SeekBar)findViewById(R.id.volumeSeekBar);
它返回null,因为您为AlertDialog动态创建了SeekBar:
View v = inflater.inflate(R.layout.volume_dialog, (ViewGroup) findViewById(R.id.settingsItem));
要解决此问题,请将此行(SeekBar)findViewById(R.id.volumeSeekBar);
更改为:
(SeekBar) v.findViewById(R.id.volumeSeekBar);
它试图在View v
而不是ContextView中找到你的Seekbar,它应该可以正常工作。