2014-06-09 45 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

相關問題