This question has already been answered:
There is a layout file that acts as a container:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/frameLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.test.test.MainActivity"> </FrameLayout> There is also a java-class in which the method is called from another class:
import android.support.v7.app.AppCompatActivity; import android.os.Bundle; public class MainActivity extends AppCompatActivity { List fragList; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Иницилизация второго java-класса fragList = (List) getSupportFragmentManager().findFragmentById(R.id.frameLayout); } @Override public void onBackPressed() { //Вызов метода из другого класса fragList.enterBackButton(); } } Finally, there is a class that must handle the method from the first class (MainActivity):
import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; public class List extends android.support.v4.app.ListFragment { ArrayAdapter<CharSequence> adapter1, adapter2, adapter3; @Override public void onAttach(Context context) { super.onAttach(context); //Инициализация адаптеров adapter1 = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.test1)); adapter2 = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.test2)); adapter3 = new ArrayAdapter<CharSequence>(getActivity(), android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.test3)); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); //Установка начального адаптера setListAdapter(adapter1); } @Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); //При выборе пункта списка адаптер меняется на другой if (getListAdapter() == adapter1) { switch (position) { case 0: setListAdapter(adapter2); break; case 1: break; } } else if (getListAdapter() == adapter2) { switch (position) { case 0: setListAdapter(adapter3); break; case 1: break; } } } //Этот метод должен заменить onBackPressed(), объявленный в другом классе public void enterBackButton () { if (getListAdapter() == adapter2) { setListAdapter(adapter1); } else if (getListAdapter() == adapter3) { setListAdapter(adapter2); } } } When you start the application, a list should appear, but this does not happen. In addition, when you press the "back" button, the program ends with an NPE error.