Szukałem rozwiązania problemu przez wiele godzin. Chcę tylko dodać przełącznik pod paskiem akcji (jak w ustawieniach Bluetooth). Znalazłem podobne pytanie tutaj, ale prawdopodobnie było stare. W każdym razie oto mój kod:Dlaczego funkcja getActionView() zwraca wartość null
główną działalność:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
MenuItem item = menu.findItem(R.id.myswitch);
switchButton = (Switch) item.getActionView();
return super.onCreateOptionsMenu(menu);
}
menu_main.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<item
android:id="@+id/menu_switch"
android:title="off/on"
app:showAsAction="always"
app:actionLayout="@layout/switchlayout"
app:actionViewClass="android.support.v7.widget.Switch" />
</menu>
switchlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Switch
android:id="@+id/myswitch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#1E88E5" />
</RelativeLayout>
Ale bez względu na to, co robię, zawsze otrzymujemy:
Próba invode ... getActionView() na null odniesienia obiektu
jestem zdezorientowany, bo po prostu zdefiniowany przedmiot przed R.id.myswitch
linia jest zdefiniowana, zrobiłem bałagan, który się?
że ustalił, dzięki! – Plays2