5

(Wi-Fi 설정에서와 같이) 액션 바 내부에 스위치를 넣을 수있었습니다. 다음과 같이 내가 활동의 onCreateOptionsMenu() 방법을 오버라이드 그 후ActionBar에서 Switch 인스턴스 가져 오기

<?xml version="1.0" encoding="utf-8"?> 
<menu xmlns:android="http://schemas.android.com/apk/res/android" > 
<item android:id="@+id/item1" 
     android:titleCondensed="Service" 
     android:title="Service" 
     android:actionViewClass="android.widget.Switch" 
     android:showAsAction="always|withText"> 
</item> 

:

은 내가/메뉴 폴더 안에 다음 mainmenu.xml 파일을 넣어

@Override 
public boolean onCreateOptionsMenu(Menu menu) 
{ 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.mainmenu, menu); 

    // Get widget's instance 
    swtService = (Switch)menu.findItem(R.id.item1).getActionView(); 
    swtService.setOnCheckedChangeListener(this); 

    return super.onCreateOptionsMenu(menu); 
} 

불행히도이 메서드가 호출 될 때 나는 이해할 수 없습니다. 여기에 문제가있다 : onCreateOptionsMenu는 전에도 onResume()를 호출되지 않습니다 그래서 NullPointerException가 슬로우 것 같다 :

@Override 
public void onResume() 
{ 
    super.onResume(); 

    // Synchronize the switch with service's status 
    swtService.setChecked(ServiceHelper.isServiceStarted(this, MySystemService.class.getName())); 
} 

내가 뭔가를 놓치고 있습니까? 작업 표시 줄에보기를 배치하는 다른 방법이 있습니까?

편집

내 목표 API는 17이고, 나는 낮은 것들에 대해 걱정하지 않는다. :)

다음은 응용 프로그램의 샷라는 라이프 사이클 방법을 보여주는입니다 : Lifecycle methods

감사

답변

1

이 시도 :

@Override 
    public void onPrepareOptionsMenu(Menu menu){ 
     super.onPrepareOptionsMenu(menu); 
     swtService.setChecked(ServiceHelper.isServiceStarted(this, MySystemService.class.getName())); 

    } 

@Override 
public void onResume() 
{ 
    super.onResume(); 
    this.getActivity().invalidateOptionsMenu(); // If you are using fragment 
    invalidateOptionsMenu(); // If you are using activity 
} 
+1

안녕을 마법처럼 일이! 고맙습니다! :디 – XDnl

관련 문제