Why it does not show the required fragment when nav drawer android menu option is selected?

拈花ヽ惹草 提交于 2020-01-05 06:22:15

问题


At me, in the program there are two fragments each of which is responsible for one kind of messages - entering or proceeding.

There is an adapter that implements the selection of these fragments. And I want to make sure that when selecting a menu item, I saw a certain fragment, here is my main class menu:

public class MessageCenter extends AppCompatActivity
        implements Sent.OnFragmentInteractionListener, Received.OnFragmentInteractionListener, OnNavigationItemSelectedListener {


    PagerAdapter mAdapter;
    FrameLayout mPager;
    FragmentManager fragmentManager;
    FragmentTransaction ft;
    TextView txt1, txt2;
    SharedPreferences sp;
    SharedPreferences.Editor editor;

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


        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MessageCenter.this, WriteResponseMess.class);
                startActivity(intent);
            }
        });

        txt1 = findViewById(R.id.id_app);
        txt2 = findViewById(R.id.name_app);

        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        /*mAdapter = new PagerAdapter(getSupportFragmentManager());
        mPager = findViewById(R.id.frame);*/


        navigationView.getMenu().findItem(R.id.received).setChecked(true);
        fragmentManager = getSupportFragmentManager();
        ft = fragmentManager.beginTransaction();
        ft.replace(R.id.frame, new Received());
        ft.commit();

        getPersonalData();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            Intent intent = new Intent(MessageCenter.this, MainScreen.class);
            startActivity(intent);
            super.onBackPressed();
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.home) {
            Intent intent = new Intent(getApplicationContext(), MainScreen.class);
            startActivity(intent);
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {


        int id = item.getItemId();
        Fragment fragment = null;

            if (id == R.id.received) {
                fragmentManager = getSupportFragmentManager();
                ft = fragmentManager.beginTransaction();
                ft.replace(R.id.frame, new Received());
                ft.commit();
            } else if (id == R.id.sended) {
                fragmentManager = getSupportFragmentManager();
                ft = fragmentManager.beginTransaction();
                ft.replace(R.id.frame, new Sent());
                ft.commit();
            }


        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

}

But, I have only one fragment - Incoming messages, but the outgoing messages do not show me. Maybe I did not finish something somewhere, or there's a mistake somewhere.

Any help will be much useful. Thanks.

UPDATE

my Sent fragment:

public class Sent extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private OnFragmentInteractionListener mListener;
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;

    ArrayList<Message> messageArrayList;
    SwipeRefreshLayout mSwipeRefreshLayout;

    private boolean isVisible;
    private boolean isStarted;


    SharedPreferences sp;
    private Context context;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_sent, container, false);
        recyclerView = rootView.findViewById(R.id.list_sen);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        mSwipeRefreshLayout = rootView.findViewById(R.id.refresh_1);
        mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        return rootView;
    }

    @Override
    public void onRefresh() {
        sent();
    }

    @Override
    public void onStart() {
        super.onStart();
        isStarted = true;
        if (isVisible) {
            sent();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        isStarted = false;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (isVisible && isStarted) {
            sent();
        }
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void sent() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://0000/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        adapter = null;

        sp = Objects.requireNonNull(context).getSharedPreferences("access_token", 0);


        String a_token = sp.getString("access_token", "");
        APIService mAPIService = retrofit.create(APIService.class);
        mAPIService.getInMess("Bearer " + a_token, 1, 1).enqueue(new Callback<MessageArray>() {
            @Override
            public void onResponse(@NonNull Call<MessageArray> call, @NonNull Response<MessageArray> response) {

                if (response.isSuccessful()) {
                    messageArrayList = (ArrayList<Message>) Objects.requireNonNull(response.body()).getMessages();
                    adapter = new MessageAdapter2(messageArrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    mSwipeRefreshLayout.setRefreshing(false);


                } else {
                    ResponseBody errorBody = response.errorBody();
                    try {

                        if (Objects.requireNonNull(errorBody).string().contains("access_token_expired")) {
                            updateToken();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<MessageArray> call, @NonNull Throwable t) {

            }
        });
    }

    public void updateToken() {

    }


    public void logOut() {


    }


    @Override
    public void onAttach(Context context) {

        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
        this.context = context;
    }


    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

my received fragent code:

public class Received extends Fragment implements SwipeRefreshLayout.OnRefreshListener {

    private OnFragmentInteractionListener mListener;
    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    ArrayList<Message> messageArrayList;
    SwipeRefreshLayout mSwipeRefreshLayout;
    SharedPreferences sp;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_received, container, false);
        recyclerView = rootView.findViewById(R.id.list_res);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        received();
        mSwipeRefreshLayout = rootView.findViewById(R.id.refresh_2);
        mSwipeRefreshLayout.setColorSchemeColors(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN);
        mSwipeRefreshLayout.setOnRefreshListener(this);
        return rootView;
    }

    @Override
    public void onRefresh() {
        received();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    public void received() {
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://0000/")
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        adapter = null;

        sp = Objects.requireNonNull(getActivity()).getSharedPreferences("access_token", 0);
        String a_token = sp.getString("access_token", "");

        final APIService mAPIService = retrofit.create(APIService.class);
        mAPIService.getInMess("Bearer " + a_token, 0, 1).enqueue(new Callback<MessageArray>() {

            @Override
            public void onResponse(@NonNull Call<MessageArray> call, @NonNull Response<MessageArray> response) {
                if (response.isSuccessful()) {
                    messageArrayList = (ArrayList<Message>) Objects.requireNonNull(response.body()).getMessages();
                    adapter = new MessageAdapter(messageArrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    mSwipeRefreshLayout.setRefreshing(false);

                } else {
                    ResponseBody errorBody = response.errorBody();
                    try {
                        if (Objects.requireNonNull(errorBody).string().contains("access_token_expired")) {
                            updateToken();

                        } else if (errorBody.string().contains("invalid_token")) {
                            updateToken();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(@NonNull Call<MessageArray> call, @NonNull Throwable t) {


            }
        });
    }

    public void updateToken() {


    }


    public void logOut() {

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

回答1:


Solution:

First, declare two Global Classes:

public Class fragmentClass;
public Fragment fragment;  // v4.Fragment not the app.Fragment

Secondly,

fragmentClass = VendorDriverFragment.class;
try {
    fragment = (Fragment) fragmentClass.newInstance();
} catch (Exception e) {
    e.printStackTrace();
}
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();

So, depending on the above strategy, modify as shown:

    int id = item.getItemId();

    if (id == R.id.received) {

        fragmentClass = Recieved.class;
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();

    } 
    else if (id == R.id.sended) {

        fragmentClass = Sent.class;
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
    }

Don't forget to declare those two classes as public.

This works for me, Try it and if any problem comes, please comment.



来源:https://stackoverflow.com/questions/52115783/why-it-does-not-show-the-required-fragment-when-nav-drawer-android-menu-option-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!