2014-06-09 22 views
1

我是Android新手,并且在过去几年中没有编写任何程序。所以为了让自己开始,我尝试了简单的东西,其中之一就是实现一个SeekBar及其监听器。我曾尝试实现监听器作为一个单独的类,以及在我的ActionBarActivity类本身实现接口,但它导致NPE。我已经能够将其缩小到听众没有实例化而没有指示为什么。在Android中实现SeekBar Listener接口时出现空指针异常

这是我的代码片段。

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

更改这个..

setContentView(R.layout.activity_intense_torch); 

setContentView(R.layout.Fragment_xxx); 

因为SeekBarFragment_xxx.xml这样setContentView应该是指Fragment_xxx.xml

删除

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

谢谢,它现在正在工作。 –

+0

@KoushikB。很高兴帮助。快乐编码。 – Hariharan

相关问题