0

Получается я ссылаюсь на несуществующий объект? Как исправить?

RelativeLayout relativeLayout;
Switch switch1;
Toolbar toolbar;
RecyclerView recyclerView;
RecyclerAdapter recyclerAdapter2;
String[] _category = {"society", "science", "technics"};
int[] img_res = {R.drawable.man_black, R.drawable.category_add, R.drawable.televisor};
ArrayList<MenuItem> arrayList = new ArrayList<MenuItem>();

@Override
protected void onCreate (Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
    recyclerView.setLayoutManager(gridLayoutManager);
    recyclerAdapter2 = new RecyclerAdapter(arrayList);
    recyclerView.setAdapter(recyclerAdapter2);

    int i = 0;
    for (int img : img_res) {
        MenuItem menuItem = new MenuItem(img, _category[i]);
        arrayList.add(menuItem);
        i++;
    }
}

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

    // Switch switch1= (Switch)menu.findItem(R.id.action_switch).getActionView().findViewById(R.id.action_switch);
    // switch1.setOnCheckedChangeListener(this);
    android.view.MenuItem item = menu.findItem(R.id.switch_toolbar);
    item.setActionView(R.layout.switcher);
    View actionView = item.getActionView();
    Switch mySwitch = (Switch) actionView.findViewById(R.id.switch_toolbar);
    mySwitch.setOnCheckedChangeListener(this);

    return true;
}

@Override
public boolean onOptionsItemSelected (android.view.MenuItem item) {
    int option_id = item.getItemId();
    if (option_id == R.id.add_word) {
        Intent intent = new Intent(this, AddActivity.class);
        startActivity(intent);
    }
    if (option_id == R.id.delete_word) {
    }
    if (option_id == R.id.add_category) {
    }
    if (option_id == R.id.remove_category) {
    }
    if (option_id == R.id.switch_toolbar) {
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onCheckedChanged (CompoundButton compoundButton,boolean b) {
    if (switch1.isChecked()) {
        relativeLayout.setBackgroundColor(Color.BLUE);
    } else {
        relativeLayout.setBackgroundColor(Color.RED);
    }
}

Switch xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.SwitchCompat
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:textOff="Ru"
    android:textOn="En"
    android:id="@+id/switch_layout"
    app:showText="true"
    android:theme="@style/SCBSwitch"
>
</android.support.v7.widget.SwitchCompat>

Menu 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/add_word"
        android:title="Add Word"
        android:icon="@drawable/plus_circle_black_on_white"
        app:showAsAction="always"
        android:orderInCategory="100"
    />
    <item
        android:id="@+id/delete_word"
        android:title="Delete Word"
        android:icon="@drawable/rounded_delete_button_with_minus"
        app:showAsAction="ifRoom"
        android:orderInCategory="200"
    />
    <item
        android:id="@+id/remove_category"
        android:title="Remove Category"
        android:icon="@drawable/category_remove"
        app:showAsAction="ifRoom"
        android:orderInCategory="400"
    />
    <item
        android:id="@+id/add_category"
        android:title="Add Category"
        android:icon="@drawable/category_add"
        app:showAsAction="ifRoom"
        android:orderInCategory="300"
    />
    <item
        android:id="@+id/switch_toolbar"
        android:title="switcher"
        app:actionLayout="@layout/switcher"
        app:showAsAction="ifRoom"
        android:orderInCategory="500"
    />
</menu>
2
  • Перенесите инициализацию в onPrepareOptionsMenu
    – ЮрийСПб
    17 авг 2016 в 7:52
  • Та же ошибка. NullPointerExeption при попытке вызвать setOnCheckedChangeListener. Если убрать строку mySwitch.setOnCheckedChangeListener(this); - приложение запускается
    – xebeche
    17 авг 2016 в 13:20

1 ответ 1

1
Switch mySwitch = (Switch)actionView.findViewById(R.id.switch_toolbar);
mySwitch.setOnCheckedChangeListener(this);

Попробуйте вынести это в onCreate(), сразу после

 toolbar = (Toolbar)findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);
1
  • В любых вариациях выдает NullPointerExeption ссылаясь на эту строчку android.view.MenuItem item=menu.findItem(R.id.switch_toolbar);
    – xebeche
    17 авг 2016 в 13:30

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.