Navigationview onitem click слушатель не работает - PullRequest
0 голосов
/ 01 февраля 2019

Я хочу открыть фрагмент по щелчку элемента навигации, но он не работает в моем коде. Я установил navigationView.setNavigationItemSelectedListener(MainActivity.this) слишком

Это мой код.

MainActivity.java

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


        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.frame
                        , new DashboardFragment())
                .commit();

        initView();
        onClick();


        listData = new ArrayList<>();
        parentIdList = new ArrayList<>();
        reportIdList = new ArrayList<>();
        listSubData = new ArrayList<>();
        reportSubList = new ArrayList<>();

        toolbar.setTitle("Dashboard");
        toolbar.setBackgroundColor(getResources().getColor(R.color.colorLightBlue));
        toolbar.setTitleTextColor(getResources().getColor(R.color.colorWhite));
        setSupportActionBar(toolbar);


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

        drawerLayout.addDrawerListener(toggle);
        toggle.syncState();

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

//        ActionBar bar = getSupportActionBar();
//        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0059b3")));


        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
        loginid = sp.getInt("loginId", 0);
        userrole = sp.getInt("userrole", 0);
        clientid = sp.getInt("clientid", 0);
        username = sp.getString("username", "");


        Log.e(" prefs loginId", String.valueOf(loginid));
        Log.e("prefs userrole", String.valueOf(userrole));
        Log.e(" prefs clientid", String.valueOf(clientid));

        if (userrole == 99) {
            tvUserRole.setText("CLIENT");
            tvUserName.setText(username);
        } else {
            tvUserRole.setText("PARTNER");
            tvUserName.setText(username);
        }


        NavigationOptionsData(String.valueOf(userrole), String.valueOf(loginid), "A");

        for(int i=0;i<reportIdList.size();i++)
        {
            if(MenuItemId == reportIdList.get(i))
            {

                Log.e("Menuitemid=", String.valueOf(MenuItemId));

//                fragToCall = listDatSSa.get(i);
//                ReportFragment fragment = new ReportFragment();
//                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
//                fragmentTransaction.replace(R.id.frame, fragment, fragToCall);
//                fragmentTransaction.add(R.id.test_fragment, fragment, "testtag");
//
//                fragmentTransaction.addToBackStack(fragToCall);
//                fragmentTransaction.commitAllowingStateLoss();
            }
            else
            {
                Log.e("Not equal", "");
            }
        }
        navigationView.bringToFront();
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {


                return true;
            }
        });

    }

    private void initView() {

        navigationView = findViewById(R.id.nav_view);
        drawerLayout = findViewById(R.id.drawer_layout);
        toolbar = findViewById(R.id.toolbar);
        rvNavOptions = (ListView) findViewById(R.id.rv_nav_data);
        rvNavSubOptions = (ListView) findViewById(R.id.rv_nav_sub_data);

        header = navigationView.getHeaderView(0);
        tvUserName = (TextView) header.findViewById(R.id.tv_user_name_drawer);
        tvUserRole = (TextView) header.findViewById(R.id.tv_user_role_drawer);
        tvOptionsId = (TextView) findViewById(R.id.tv_option_id);


    }




    private void NavigationOptionsData(String roleid, String loginId, String device) {

        final APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
        final NavigationDrawerModel navigationDrawerModel = new NavigationDrawerModel(roleid, loginId, device);
        Call<NavigationDrawerModel> call1 = apiInterface.createNavigationOption(navigationDrawerModel);
        call1.enqueue(new Callback<NavigationDrawerModel>() {
            @Override
            public void onResponse(Call<NavigationDrawerModel> call, Response<NavigationDrawerModel> response) {
                user1 = response.body();

                Log.e("Navigation data===", user1.getT0().get(0).getReportText());
                Log.e("Length of t0====", String.valueOf(user1.getT0().size()));
                Log.e("Length of t1====", String.valueOf(user1.getT1().size()));

                for (int i = 0; i < user1.getT0().size(); i++) {


                    String reportText = user1.getT0().get(i).getReportText();
                    Integer reportId = user1.getT0().get(i).getReportId();
                    reportIdList.add(reportId);
                    listData.add(reportText);

                }

                for (int i = 0; i < user1.getT1().size(); i++) {

                    Integer reportParentId = user1.getT1().get(i).getParentId();
                    String reportSubName = user1.getT1().get(i).getReportText();
                    parentIdList.add(reportParentId);
                    listSubData.add(reportSubName);
                }

                Log.e("Size of parentid list==", String.valueOf(parentIdList.size()));
                Log.e("Size of reportid list==", String.valueOf(reportIdList.size()));


                navigationDrawerMenu = new NavigationDrawerMenu(listData, parentIdList, getApplicationContext());
                rvNavOptions.setAdapter(navigationDrawerMenu);


            }

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

                Log.e("Error is==", t.getMessage());
            }


        });
    }


    private void onClick() {

        rvNavOptions.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {


                navigationDrawerMenu.onClick(view);
                MenuItemId = (int) id;
                Log.e("id of item click", String.valueOf(id));


            }
        });

    }


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

        int id = menuItem.getItemId();
        Log.e("Menu item id is=", String.valueOf(id));
        return true;
    }

и это мой 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"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

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


    <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"
        app:headerLayout="@layout/nav_header_main">


        <ListView
            android:id="@+id/rv_nav_data"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginTop="@dimen/dp150"></ListView>


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

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

Я также установил navigationView.bringToFront(), но он все еще не работает.

Я настраиваю просмотр списка в навигационном представлениипотому что я устанавливаю динамические данные из API.

Ответы [ 2 ]

0 голосов
/ 01 февраля 2019

см. Следующий шаг для реализации NavigationView

1.Implement the listener in your Activity:

    public class HomeActivity extends AppCompatActivity implements 
                  NavigationView.OnNavigationItemSelectedListener

2.setNavigationItemSelectedListener in onCreate of Activity

NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);

if (mNavigationView != null) {
        mNavigationView.setNavigationItemSelectedListener(this);
}


3.Override the method

public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_account) {//DO your stuff }
    ...
}
0 голосов
/ 01 февраля 2019
//Use Navigation Callback listener as follows 
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(createOnNavigationItemClickListener());code here

// Implementation of Navigation Listener
private NavigationView.OnNavigationItemSelectedListener createOnNavigationItemClickListener() {
    return new NavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.menu_1:
                    return true;
                case R.id.menu_2:
                    return true;
                default:
                    return CheckerDelegate.getCheckerNavigator().onNavigationItemSelected(MainActivity.this, item);
            }
        }
    };
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...