Основная панель инструментов деятельности не отображается после скрытия при прикреплении фрагмента - PullRequest
0 голосов
/ 20 января 2020

Я прикрепляю фрагмент из фрагмента, который прикреплен к действию, а затем внутри фрагмента я установил свою пользовательскую панель инструментов с параметром setDisplayHomeUpEnabled, равным true. Когда я прикрепляю фрагмент, я установил панель инструментов «Основная активность» скрытой, единственная проблема заключается в том, что он не скрывается при возвращении к родительскому фрагменту из дочернего фрагмента


package manu.apps.cartv6.Activities;


import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.material.navigation.NavigationView;
import com.google.android.material.snackbar.Snackbar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import manu.apps.cartv6.Classes.CartCounterConverter;
import manu.apps.cartv6.Classes.Config;
import manu.apps.cartv6.Classes.Product;
import manu.apps.cartv6.Classes.UserSessionManager;
import manu.apps.cartv6.Fragments.UserProfileFragment;
import manu.apps.cartv6.Fragments.ViewProductsFragment;
import manu.apps.cartv6.Interfaces.AddRemoveCallbacks;
import manu.apps.cartv6.R;
import manu.apps.cartv6.Tests.CartFragment;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, NavigationView.OnNavigationItemSelectedListener, AddRemoveCallbacks {


    /** Lists*/
    public static List<Product> cartList = new ArrayList<>();


    /** Variables*/
    // Counter for Cart
    public static int cart_count = 0;

    // Get Id for users
    String getId;

    // Time Interval for back button press
    private static final int TIME_INTERVAL = 2000; // # milliseconds, desired time passed between two back presses.

    // How long the back button has been pressed
    private long backPressed;

    //Getting Class Info
    private static final String TAG = MainActivity.class.getSimpleName();

    /** Views*/
    // Toolbars
    Toolbar toolbar;


    // TextViews
    TextView navHeaderUsername;

    // ImageViews
    ImageView navHeaderProfileImage;


    /** Session Managing*/
    UserSessionManager userSessionManager;


    /** Navigation Drawer*/
    //Declaring ActionBarDrawerToggle
    private ActionBarDrawerToggle actionBarDrawerToggle;

    //Declaring Navigation View
    NavigationView navigationView;

    //Declaring Drawer Layout
    DrawerLayout drawerLayout;



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

        //Creating a Session Manager for the Users
        userSessionManager = new UserSessionManager(this);
        userSessionManager.checkUserLogin();

        //Finding Drawer Layout
        drawerLayout = findViewById(R.id.drawer_layout);

        //Finding Navigation View
        navigationView = findViewById(R.id.navigation_view);

        //Finding Toolbar
        toolbar = findViewById(R.id.main_tool_bar);

        //Toolbar Workings
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Home");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        // Setting View Products Fragment
        Fragment fragment = new ViewProductsFragment();
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();


        //Setting ActionBarDrawerToggle to Open and Close
        actionBarDrawerToggle = new ActionBarDrawerToggle(this,drawerLayout,R.string.open,R.string.close);
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();

        // Setting Navigation Item Selected Listener for Items in Navigation View
        navigationView.setNavigationItemSelectedListener(this);


        /**
         * app:headerLayout="@layout/layout_nav_header"
         *
         * Remove the above line in NavigationView because we are inflating programmatically
         *
         * */
        View navView = navigationView.inflateHeaderView(R.layout.layout_nav_header);

        //Finding Views in Navigation Header which is inside Navigation View
        navHeaderUsername = navView.findViewById(R.id.nav_header_username);
        navHeaderProfileImage = navView.findViewById(R.id.nav_header_profile_image);

        // Parsing Username and Email
        HashMap<String, String> user = userSessionManager.getUserDetails();
        getId = user.get(userSessionManager.ID);

    }


    // Fetch User Details
    private void fetchUserDetails(){

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Loading...");
        //progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Config.FETCH_USER_DETAILS,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        progressDialog.dismiss();
                        Log.i(TAG, response.toString());
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            String success = jsonObject.getString("success");
                            JSONArray jsonArray = jsonObject.getJSONArray("fetch");

                            if (success.equals("1")) {

                                for (int i = 0; i < jsonArray.length();i++) {
                                    JSONObject object = jsonArray.getJSONObject(i);

                                    String username = object.getString("username").trim();
                                    String email = object.getString("email").trim();


                                    // Set Details for the Navigation Header
                                    navHeaderUsername.setText(username);


                                    //etProfileUsername.setText(username);
                                    //etProfileEmail.setText(email);

                                }
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            progressDialog.dismiss();
                            Toast.makeText(MainActivity.this, "JSON Error fetching Details", Toast.LENGTH_SHORT).show();
                            Snackbar.make(getWindow().getDecorView().getRootView(),e.toString(),Snackbar.LENGTH_LONG).show();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Toast.makeText(MainActivity.this, "Volley Error fetching Details", Toast.LENGTH_SHORT).show();
                        Snackbar.make(getWindow().getDecorView().getRootView(),error.toString(),Snackbar.LENGTH_LONG).show();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String > params = new HashMap<>();
                params.put("id", getId);
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }


    public static String numberFormatter(double d) {
        DecimalFormat decimalFormat = new DecimalFormat("#,###.##");
        return decimalFormat.format(d);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.user_toolbar_menu_items, menu);

        MenuItem cartItem = menu.findItem(R.id.cart_action);

        cartItem.setIcon(CartCounterConverter.convertLayoutToImage(MainActivity.this,cart_count,R.drawable.view_cart_icon));

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // Check if Action Bar Drawer Toggle has been selected
        if(actionBarDrawerToggle.onOptionsItemSelected(item)){
            return true;
        }


        switch (item.getItemId()) {
            case R.id.cart_action:
                //startActivity(new Intent(MainActivity.this,CartActivity.class));
                Fragment fragment = new CartFragment();
                getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();
                getSupportActionBar().hide();
                break;
            case R.id.logout_action:
                userSessionManager.logOutUser();
                finish();
                default:
                    break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {

        Fragment fragment = null;

        /*switch (item.getItemId()) {
            case R.id.action_category_one:
                Toast.makeText(this, "Under Development", Toast.LENGTH_SHORT).show();
                break;
            case R.id.action_profile:
                fragment = new UserProfileFragment();
                break;
        }*/

        int id = item.getItemId();

        if (id == R.id.action_view_products) {
            fragment = new ViewProductsFragment();
        }
//        else if (id == R.id.action_receipts) {
//        }

        else if (id == R.id.action_profile) {
            //startActivity(new Intent(MainActivity.this,UserProfileActivity.class));
            fragment = new UserProfileFragment();
        }
        if (fragment !=null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction ft = fragmentManager.beginTransaction();
            //R.id."  " will be found in content_main.xml from the Frame Layout
            ft.replace(R.id.frame_layout,fragment);
            ft.commit();
        }

        drawerLayout.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onClick(View v) {

    }

    // When back button is pressed method
    @Override
    public void onBackPressed() {

        //Check if navigation drawer is opened or closed
        if (drawerLayout.isDrawerOpen(GravityCompat.START)){
            drawerLayout.closeDrawer(GravityCompat.START);
        }else {

            if (backPressed + TIME_INTERVAL > System.currentTimeMillis()) {
                super.onBackPressed();
                return;
            } else {
                Toast.makeText(getBaseContext(), "Press back button again to exit", Toast.LENGTH_SHORT).show();
            }

            backPressed = System.currentTimeMillis();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        fetchUserDetails();

    }

    // Remember to implement AddRemoveCallback Interface
    @Override
    public void onAddProduct() {
        cart_count++;
        invalidateOptionsMenu();
    }

    // Remember to implement AddRemoveCallback Interface
    @Override
    public void onRemoveProduct() {
        cart_count--;
        invalidateOptionsMenu();
    }
}

Мой дочерний фрагмент


package manu.apps.cartv6.Tests;


import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import manu.apps.cartv6.Activities.MainActivity;
import manu.apps.cartv6.Fragments.ViewProductsFragment;
import manu.apps.cartv6.R;

/**
 * A simple {@link Fragment} subclass.
 */
public class CartFragment extends Fragment {

    Toolbar fragmentCartToolbar;


    public CartFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //((MainActivity) getActivity()).getSupportActionBar().hide();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_cart, container, false);
    }

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

        fragmentCartToolbar = view.findViewById(R.id.fragment_cart_tool_bar);

        ((MainActivity) getActivity()).setSupportActionBar(fragmentCartToolbar);

        ((MainActivity) getActivity()).getSupportActionBar().setTitle("Blank Fragment");

        ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ((MainActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

        final Toolbar bar = (Toolbar) getActivity().findViewById(R.id.main_tool_bar);

        fragmentCartToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                ((MainActivity) getActivity()).setSupportActionBar(bar);

                //((MainActivity) getActivity()).getSupportActionBar().show();

                Fragment fragment = new ViewProductsFragment();
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();

            }
        });

    }

}

Проблема в том, что как только я добавляю setNavigationOnClickListener, главная панель инструментов «Активность» больше не отображается, когда я ее удаляю, она прекрасно показывает


 @Override
    public void onResume() {
        super.onResume();

        ((MainActivity)getActivity()).getSupportActionBar().hide();

        ((MainActivity) getActivity()).setSupportActionBar(fragmentCartToolbar);

        ((MainActivity) getActivity()).getSupportActionBar().setTitle("Blank Fragment");

        ((MainActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        //((MainActivity) getActivity()).getSupportActionBar().setDisplayShowHomeEnabled(true);

        fragmentCartToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Fragment fragment = new ViewProductsFragment();
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout,fragment).commit();

            }
        });


    }

1 Ответ

0 голосов
/ 20 января 2020

Пожалуйста, попробуйте добавить ниже в onResume() вашего родительского фрагмента, я думаю, это ViewProductsFragment из предоставленного кода.

Это позволит вам скрыть панель действий от самого фрагмента, а не от действия.

@Override
public void onResume() {
    super.onResume();
    ((AppCompatActivity)getActivity()).getSupportActionBar().hide();
}
...