在Android中实现SeekBar Listener接口时出现空指针异常

时间:2014-06-09 15:03:08

标签: android seekbar implements

我是Android新手,过去几年没有编程。 所以为了让自己开始,我正在尝试简单的东西,其中一个是实现SeekBar及其监听器。我已经尝试将侦听器实现为一个单独的类,以及在我的ActionBarActivity类本身中实现接口,但它会导致NPE。我已经能够将它缩小到听众没有实例化而没有指示为什么。

这是我的代码段。

Fragment_xxx.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.SunShineCorp.intensetorch.IntenseTorchActivity$PlaceholderFragment" >

<SeekBar
        android:id="@+id/seekBar1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="14dp" />

</RelativeLayout>

实际Java代码

public class IntenseTorchActivity extends ActionBarActivity 
                implements SeekBar.OnSeekBarChangeListener {

private static int seekValue = 10;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_intense_torch);

     final SeekBar seekbar =  (SeekBar) findViewById(R.id.seekBar1);

     seekbar.setOnSeekBarChangeListener(this);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
}

@Override
    public void onProgressChanged(SeekBar seekBar, int progress,
            boolean fromUser) {
       seekValue = progress;
    }

   @Override
   public void onStartTrackingTouch(SeekBar arg0) {
       // TODO Auto-generated method stub
   }

   @Override
   public void onStopTrackingTouch(SeekBar arg0) {
       // TODO Auto-generated method stub
   }


@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.intense_torch, menu);
    return true;
}

真正感谢任何帮助或指针。

1 个答案:

答案 0 :(得分:1)

改变这个..

setContentView(R.layout.activity_intense_torch);

setContentView(R.layout.Fragment_xxx);

因为SeekBar位于Fragment_xxx.xml,所以setContentView应该引用Fragment_xxx.xml

删除

if (savedInstanceState == null) {
    getSupportFragmentManager().beginTransaction()
            .add(R.id.container, new PlaceholderFragment()).commit();
}