2017-12-20 17 views
3

사용자에게 언어를 변경할 수있는 옵션을 제공하기 위해 툴바에 스위치가 있습니다. onCheckedChangedListner가 도구 모음 메뉴의 클릭 수를 등록하지 않습니다.

app toolbar

I 스위치를 사용하고

의 onCheckedChanged 방법은 작동하지 않습니다. 또한, 화면에 로그 메시지가 표시되지 않기 때문에 onOptionsItemSelected도 적중하지 않는 것으로 보입니다.

스위치를 사용할 때 앱이 충돌하지 않음에 유의하십시오.

오버플로 메뉴에있는 옵션의 클릭이 제대로 작동하고 있습니다. 나는 그 사건들을 기록하고있다.

Switch aSwitch; 
RelativeLayout langSwitch; 

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

    Toolbar toolbar = findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

context = this; 

// Removed non relevant code here. 
} 


@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    int id = item.getItemId(); 
    Log.d("tag_id",String.valueOf(id)); 
    langSwitch = findViewById(R.id.app_bar_switch); 

    aSwitch = langSwitch.findViewById(R.id.langSwitch); 

    aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton compoundButton, boolean b) { 
      if (!b){ 
       //Language1 code 
       Toast.makeText(context,"Language1 Selected",Toast.LENGTH_SHORT).show(); 
      }else{ 
       //Language2 code 
       Toast.makeText(context,"Language2 Selected",Toast.LENGTH_SHORT).show(); 
      } 
     } 
    }); 

    if (id == R.id.action_settings) { 
     return true; 
    } 

    if (id == R.id.savedPost){ 
     Intent intent = new Intent(this,SavedPost.class); 
     startActivity(intent); 
    } 


    return super.onOptionsItemSelected(item); 
} 

다음은 내 menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:app="http://schemas.android.com/apk/res-auto" 
xmlns:tools="http://schemas.android.com/tools" 
tools:context="com.app_name.android.app_name.MainActivity"> 
<item 
    android:id="@+id/app_bar_switch" 
    android:orderInCategory="2" 
    android:title="" 
    app:actionLayout="@layout/switch_item" 
    app:showAsAction="always" /> 
<item 
    android:id="@+id/action_settings" 
    android:orderInCategory="100" 
    android:title="@string/action_settings" 
    app:showAsAction="never" /> 
<item 
    android:id="@+id/savedPost" 
    android:checkable="false" 
    android:orderInCategory="4" 
    android:title="@string/saved_post" /> 

</menu> 

입니다 이것은 스위치 항목에 대한 내 레이아웃 파일입니다.

<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent"> 

<Switch 
    android:id="@+id/langSwitch" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_centerHorizontal="true" 
    android:layout_centerVertical="true" 
    android:textOff="@string/switch_text_off" 
    android:textOn="@string/switch_text_on" 
    android:focusable="true" 
    android:clickable="true"/> 

</RelativeLayout> 

추가 정보.

showAsAction이 'always'인 다른 메뉴 항목 (아래 코드)을 작성하고 이것을 한 번 클릭하면 스위치를 사용할 때 토스트 메시지가 나타납니다. 나는 처음으로 그런 일이 일어나지 않는 이유에 관해서는 여기에서 단서가 없다. 또한이 메뉴 항목 없이는 어떻게 작동합니까? inflate 외부에

aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){@Override public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if (!compoundButton.isSelected()) { Log.i("Yeah" , "Is Not Selected"); invertLock(-1); } else { if (Utilities.isLockEnabled(context)) { Log.i("Yeah" , "Is Locked"); Utilities.showLockEnabled(context); } else { Log.i("Yeah" , "Is Not Locked"); invertLock(1); } } } 
+0

전체'aSwitch 이동 'onCreate()'메소드 내부의 코드 .. find ID에서 checklistener까지 –

+0

@AbhishekSingh 응용 프로그램이이 오류로 인해 충돌합니다. java.lang.RuntimeException : 활동을 시작할 수 없습니다. ComponentInfo : java.lang.NullPointerException : null 객체 참조에 'android.view.View android.widget.RelativeLayout.findViewById (int)'가상 메서드를 호출하려고합니다. – user3884753

+0

이 스레드를 참조하십시오 https://stackoverflow.com/questions/31400870/add-toggle-button-to-the-menu-to-stop-and-start-service/34760443#34760443 –

답변

3

:

<item 
    android:id="@+id/english" 
    android:orderInCategory="3" 
    android:title="@string/switch_text_on" 
    app:showAsAction="always" /> 
0

(compoundButton.isChecked()) 

In boolean 

또는

그냥 setonCheckedChangedListner

예의 다른 버전을 사용해보십시오 먼저 ChildView 당신의 layout

예와 같은

RelativeLayout item = (RelativeLayout)findViewById(R.id.item); 
View child = getLayoutInflater().inflate(R.layout.child, null); 
item.addView(child); 

에 대한 코드에서이 시도 보유 view를 만드는 것 ActionBar 이상의 레이아웃은

Switch aSwitch; 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 

    getMenuInflater().inflate(R.menu.menu_main, menu); 
    View sw = menu.findItem(R.id.app_bar_switch).getActionView(); 
    aSwitch = (Switch) sw.findViewById(R.id.langSwitch); 

    aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

    @Override 
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) { 
     if (!b){ 
      //Language1 code 
      Toast.makeText(context,"Language1 Selected",Toast.LENGTH_SHORT).show(); 
     }else{ 
      //Language2 code 
      Toast.makeText(context,"Language2 Selected",Toast.LENGTH_SHORT).show(); 
     } 
    } 
}); 

    return true; 
} 
관련 문제