某些片段中的NavigationDrawer

时间:2018-08-07 02:58:01

标签: android android-fragments navigation-drawer drawerlayout

这是问题所在,我希望我的导航抽屉(汉堡图标)仅出现在某些片段中。就我而言,我有3个fragment,使用tab layoutview pagerfragment之间切换。我已经实现了一个我创建的interface。但是当我设置为true时,所有fragment中都会出现汉堡图标。我不知道我的代码在哪里。

mainactivity代码:

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.design.widget.TabLayout;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.Spannable;
import android.text.SpannableString;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import emptrack.toro.developer.com.emptrack.FastScroll.AlphabetItem;
import emptrack.toro.developer.com.emptrack.FastScroll.DataHelper;
import emptrack.toro.developer.com.emptrack.FastScroll.VendorAdapter;
import in.myinnos.alphabetsindexfastscrollrecycler.IndexFastScrollRecyclerView;

public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, DrawerLocker{

    private View view_menu, view_click, view_list;
    private ImageView btn_arrow_back;

    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ViewPagerAdapter adapter;
    private Bundle intentFragment;
    private String frag;
    private ArrayList<ListPegawai> dataBaru;
    private Bundle dapatData;
    String PREFERENCES_FILE_NAME = "preference_diri";
    SharedPreferences dataDiri, retrieveData;

    //Untuk filtering
    private List<String> mDataArray;

    //Side bar
    private DrawerLayout drawer;
    ActionBarDrawerToggle toggle;
    Toolbar toolbar;

    private List<AlphabetItem> mAlphabetItems;
    private IndexFastScrollRecyclerView mRecyclerView;

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

        //Filtering
        mRecyclerView = findViewById(R.id.fast_scroller_recycler);
        mDataArray = new ArrayList<String>();

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //ganti ActionBar font
        SpannableString s = new SpannableString("EmpTrack");
        s.setSpan(new TypefaceSpan(this, "raleway_semibold.ttf"), 0, s.length(),
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setElevation(0);
        actionBar.setTitle(s);

        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        adapter = new ViewPagerAdapter(getSupportFragmentManager());

        dataDiri = getSharedPreferences(PREFERENCES_FILE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = dataDiri.edit();

        adapter.addFragment(new FragmentNews(), "News");
        adapter.addFragment(new FragmentTracking(), "Tracking");
        adapter.addFragment(new FragmentSettings(), "Settings");
        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        //Init layout
        view_menu = (View) findViewById(R.id.menu_layout);
        view_list = (View) findViewById(R.id.list_vendor2);
        view_click = (View) findViewById(R.id.click_vendor);
        btn_arrow_back = (ImageView) findViewById(R.id.arrow_back);

        //Untuk sidebar
        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);

        toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);

        //Init filtering
        initialiseData();
        initialiseUI();

        tabLayout.getTabAt(0).setIcon(R.drawable.ic_news);
        tabLayout.getTabAt(1).setIcon(R.drawable.ic_tracking);
        tabLayout.getTabAt(2).setIcon(R.drawable.ic_settings);

        actionBar.setElevation(0);

        intentFragment = getIntent().getExtras();
        if (intentFragment != null) {
            frag = intentFragment.getString("LoadFragment");

            switch (frag) {
                case "tracking":
                    viewPager.setCurrentItem(1, true);
                    break;
                case "settings":
                    viewPager.setCurrentItem(2, true);
                    break;
            }
        }

        //Fungsi click untuk sidebar
        view_click.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view_menu.setVisibility(View.GONE);
                view_list.setVisibility(View.VISIBLE);
            }
        });

        btn_arrow_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                view_list.setVisibility(View.GONE);
                view_menu.setVisibility(View.VISIBLE);
            }
        });
    }

    public void setActionBarTitle(String title) {
        getSupportActionBar().setTitle(title);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {

            AlertDialog.Builder builder1 = new AlertDialog.Builder(MainActivity.this);
            builder1.setTitle("Exit application");
            builder1.setMessage("Are you sure you want to exit?");
            builder1.setCancelable(true);

            builder1.setPositiveButton(
                    "Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            finish();
                        }
                    });

            builder1.setNegativeButton(
                    "No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
            AlertDialog alert11 = builder1.create();
            alert11.show();
        }
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        return false;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if(toggle.onOptionsItemSelected(item)){
            return true;
        }
        else {
            return super.onOptionsItemSelected(item);
        }
    }

    protected void initialiseData() {
        //Recycler view data
        mDataArray = DataHelper.getAlphabetData();

        //Alphabet fast scroller data
        mAlphabetItems = new ArrayList<>();
        List<String> strAlphabets = new ArrayList<>();
        for (int i = 0; i < mDataArray.size(); i++) {
            String name = mDataArray.get(i);
            if (name == null || name.trim().isEmpty())
                continue;

            String word = name.substring(0, 1);
            if (!strAlphabets.contains(word)) {
                strAlphabets.add(word);
                mAlphabetItems.add(new AlphabetItem(i, word, false));
            }
        }
    }

    protected void initialiseUI() {

        Typeface typeface = Typeface.createFromAsset(this.getAssets(), "font/raleway_medium.ttf");
        mRecyclerView.setTypeface(typeface);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setAdapter(new VendorAdapter(mDataArray));

        mRecyclerView.setIndexTextSize(14);
        mRecyclerView.setIndexBarColor("#ffffff");
        mRecyclerView.setIndexBarCornerRadius(0);
        mRecyclerView.setIndexBarTransparentValue((float) 0.4);
        mRecyclerView.setIndexbarMargin(0);
        mRecyclerView.setIndexbarWidth(40);
        mRecyclerView.setPreviewPadding(0);
        mRecyclerView.setIndexBarTextColor("#000000");

//        mRecyclerView.setPreviewTextSize(60);
//        mRecyclerView.setPreviewColor("#33334c");
//        mRecyclerView.setPreviewTextColor("#FFFFFF");
//        mRecyclerView.setPreviewTransparentValue(0.6f);

        mRecyclerView.setIndexBarVisibility(true);
        mRecyclerView.setIndexbarHighLateTextColor("#000000");
        mRecyclerView.setIndexBarHighLateTextVisibility(true);
    }

    @Override
    public void setDrawerLocked(boolean shouldLock) {
        if(shouldLock) {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);

            toggle.setDrawerIndicatorEnabled(true);

            NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
            navigationView.setNavigationItemSelectedListener(this);
        }
        else {
            drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            toggle.setDrawerIndicatorEnabled(false);
        }
    }
}

这是fragment代码:

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LayoutAnimationController;
import android.view.animation.TranslateAnimation;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import com.daimajia.swipe.util.Attributes;

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

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static android.content.Context.MODE_PRIVATE;

public class FragmentTracking extends Fragment implements Serializable, SearchView.OnQueryTextListener, SwipeRefreshLayout.OnRefreshListener, PegawaiItemClickListener {


    private final String url = "https://opensource.petra.ac.id/~m26415177/getPegawai.php";
    private JsonArrayRequest request;
    private RequestQueue queue;
    View v;
    SwipeRefreshLayout swipeLayout;
    private RecyclerView mRecyclerView;
    private List<ListPegawai> pegawaiList;
    FloatingActionButton buttonAdd;
    SwipeRecyclerViewAdapter mAdapter;
    SearchView search_view_bawah;
    public static final String PREFERENCES_FILE_NAME = "preference_diri";
    SharedPreferences dataDiri, retrieveData;

    @SuppressLint("ResourceAsColor")
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        v = inflater.inflate(R.layout.tracking_fragment,container,false);
        setHasOptionsMenu(true);
        retrieveData = this.getActivity().getSharedPreferences(PREFERENCES_FILE_NAME, MODE_PRIVATE);
        dataDiri = this.getActivity().getSharedPreferences(PREFERENCES_FILE_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = dataDiri.edit();

        //((MainActivity) getActivity()).setDrawerLocked(true);

        swipeLayout = (SwipeRefreshLayout) v.findViewById(R.id.container2);
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(android.R.color.holo_green_dark,
                android.R.color.holo_red_dark,
                android.R.color.holo_blue_dark,
                android.R.color.holo_orange_dark);

        mRecyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
        mAdapter = new SwipeRecyclerViewAdapter(getContext(), this);
        mAdapter.setMode(Attributes.Mode.Single);

        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                Log.e("RecyclerView", "onScrollStateChanged");
            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });

        pegawaiList = new ArrayList<ListPegawai>();

        buttonAdd = (FloatingActionButton)v.findViewById(R.id.buttonAdd);
        buttonAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intentAdd = new Intent(getContext(), InsertEmployeeActivity.class);
                startActivity(intentAdd);
                getActivity().overridePendingTransition(R.anim.fadein,R.anim.fadeout);
                getActivity().finish();
            }
        });

        jsonRequest();

        if (!isViewShown) {
            animasiOn();
        }
        else {
        }



        return v;
    }

    private void animasiOn() {
        mRecyclerView.setVisibility(View.INVISIBLE);
        AnimationSet set = new AnimationSet(true);

        Animation animation = new AlphaAnimation(0.0f, 1.0f);
        animation.setDuration(500);
        set.addAnimation(animation);

        animation = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f
        );
        animation.setDuration(100);
        set.addAnimation(animation);

        LayoutAnimationController controller = new LayoutAnimationController(set, 0.5f);
        mRecyclerView.setLayoutAnimation(controller);
        set.start();
        mRecyclerView.setVisibility(View.VISIBLE);

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        pegawaiList = new ArrayList<ListPegawai>();
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.search_icon,menu);

        MenuItem item = menu.findItem(R.id.search_all);
        SearchView searchView = (SearchView) item.getActionView();
        searchView.setOnQueryTextListener(this);
    }

    @Override
    public boolean onQueryTextSubmit(String s) {
        return false;
    }

    @Override
    public boolean onQueryTextChange(String s) {

//        String userInput = s.toLowerCase();
//        List<ListPegawai> newList = new ArrayList<ListPegawai>();
//
//        for(ListPegawai name:mDataSet){
//            if(name.getNama().toLowerCase().contains(userInput)){
//                newList.add(name);
//            }
//        }
//
//        mAdapter.updateList(newList);

        return true;
    }

    private boolean isViewShown = false;

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getView() != null) {
            isViewShown = true;
            // fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
            if (isVisibleToUser) {
                animasiOn();
            }
            else {
                mRecyclerView.setVisibility(View.INVISIBLE);
            }
        } else {
            isViewShown = false;
        }
    }

    @Override
    public void onRefresh() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                animasiOn();
                mAdapter.setPegawaiList(pegawaiList);
                swipeLayout.setRefreshing(false);
                pegawaiList = new ArrayList<ListPegawai>();
                jsonRequest();
            }
        }, 750);
    }

    private void jsonRequest() {

        request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {

                JSONObject jsonObject = null;

                for (int i = 0; i < response.length(); i++) {

                    try {
                        Log.d("LENGTH",String.valueOf(response.length()));
                        jsonObject = response.getJSONObject(i);
                        ListPegawai pegawai = new ListPegawai();
                        pegawai.setNama(jsonObject.getString("nama"));
                        pegawai.setNik(jsonObject.getString("nik"));
                        pegawai.setAlamat(jsonObject.getString("alamat"));
                        pegawai.setTanggal(jsonObject.getString("tanggal_kejadian"));
                        pegawai.setJenisKelamin(jsonObject.getString("jenis_kelamin"));
                        pegawai.setKeluhanPegawai(jsonObject.getString("keluhan"));
                        pegawaiList.add(pegawai);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
                setuprecyclerview(pegawaiList);
                mAdapter.setPegawaiList(pegawaiList);

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }
        );

        queue = Volley.newRequestQueue(getContext());
        queue.add(request);
    }

    private void setuprecyclerview(List<ListPegawai> pegawaiList) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(mRecyclerView.getContext(), LinearLayoutManager.VERTICAL));
        mRecyclerView.setAdapter(mAdapter);
        Log.d("KUDA","KUDANS");
    }

    @Override
    public void onPegawaiItemClick(int pos, ListPegawai pegawaiList) {

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ((MainActivity) getActivity()).setDrawerLocked(false);
    }
}

当我设置此代码((MainActivity) getActivity()).setDrawerLocked(true);时,所有fragment中都会出现汉堡图标。但是,当我对其进行评论时,该图标并未出现在所有fragment

这里是XML代码,以防万一我的错误:

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:fitsSystemWindows="true"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main2"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical"
        tools:context="emptrack.toro.developer.com.emptrack.MainActivity">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="@color/colorPrimary"
            app:tabGravity="fill"
            app:tabIconTint="#FFFFFF"
            app:tabIndicatorColor="#FFFFFF"
            app:tabMode="fixed"
            app:tabTextAppearance="@style/tab_text"
            app:tabTextColor="#FFFFFF"></android.support.design.widget.TabLayout>

        <android.support.v4.view.ViewPager
            android:id="@+id/viewPager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@id/tabLayout" />
    </RelativeLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:animateLayoutChanges="true"
            android:orientation="vertical"
            android:paddingTop="0dp">

            <include
                android:id="@+id/menu_layout"
                layout="@layout/list_menu" />

            <include
                android:id="@+id/list_vendor2"
                layout="@layout/list_vendor"
                android:visibility="gone" />

        </LinearLayout>

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

请要求更详细,谢谢

2 个答案:

答案 0 :(得分:0)

只需添加标签Layout即可更改监听器,并根据需要隐藏和显示图标。

答案 1 :(得分:0)

导航处于隐藏模式,将其更改为可见。.它将起作用