按钮和导航项的相同操作

Same action for button and an nav item

我有 3 个项目和 3 个按钮。对于按钮,我创建了一个号召性用语功能,并且该意图运行良好。我想将相同的操作添加到我的导航项中。我该怎么做?

说的很清楚。单击按钮和导航项时,我需要显示相同的 activity。我是 Android 的新手。所以我什至不知道这是否可能。或者我正在使用正确的方法来做到这一点。

这些是我用于按钮的意图:

public void exploreActivity(View view){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }

    public void packagesActivity(View view){
        Intent intent = new Intent(this,PackagesActivity.class);
        startActivity(intent);
    }

    public void dealsActivity(View view){
        Intent intent = new Intent(this,DealsActivity.class);
        startActivity(intent);
    }

这些是我的菜单项

<?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@id/explore"
        android:icon="@drawable/ic_menu_exp"
        android:title="@string/Explore" />
    <item
        android:id="@id/menuPack"
        android:icon="@drawable/ic_menu_pack"
        android:title="@string/packages" />
    <item android:id="@id/dealsMenu"
        android:icon="@drawable/ic_menu_deals"
        android:title="@string/deals" />
    </menu>

这是我现在拥有的三个按钮

<Button
                android:id="@+id/explore"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginStart="16dp"
                android:layout_marginLeft="16dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/explorebutton"
                android:onClick="exploreActivity"
                android:text="@string/Explore"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

            <Button
                android:id="@+id/packages"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginEnd="24dp"
                android:layout_marginStart="24dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/packagebutton"
                android:onClick="packagesActivity"
                android:text="@string/packages"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintEnd_toStartOf="@+id/deals"
                app:layout_constraintStart_toEndOf="@+id/explore"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

            <Button
                android:id="@+id/deals"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:layout_marginTop="40dp"
                android:background="@null"
                android:drawableTop="@drawable/dealsbutton"
                android:onClick="dealsActivity"
                android:text="@string/deals"
                android:textAllCaps="false"
                android:textColor="#838383"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/homelogo" />

我已经对 HomeActivity.Java

进行了更改
package com.example.windows81.travelspoc;

import android.content.Context;
import android.content.Intent;
import android.support.design.widget.NavigationView;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.util.Timer;
import java.util.TimerTask;

public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{


    ViewPager viewPager;
    LinearLayout sliderDotspanel;
    NavigationView mNavigationView;
    private int dotscount;
    private ImageView[] dots;
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mtoggle;

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

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        mtoggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
        mNavigationView.setNavigationItemSelectedListener(this);

        mDrawerLayout.addDrawerListener(mtoggle);
        mtoggle.syncState();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewPager);

        sliderDotspanel = (LinearLayout) findViewById(R.id.SliderDots);

        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(this);
        viewPager.setAdapter(viewPagerAdapter);

        Timer timer = new Timer();
        timer.scheduleAtFixedRate(new MyTimerTask(), 2000, 4000);

        dotscount = viewPagerAdapter.getCount();
        dots = new ImageView[dotscount];

        for (int i = 0; i < dotscount; i++){
            dots[i] = new ImageView(this);
            dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(),R.drawable.incative_dot));

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

            params.setMargins(8, 0, 8,0);

            sliderDotspanel.addView(dots[i], params);
        }
        dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_active));
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                for (int i = 0; i < dotscount; i++){
                    dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.incative_dot));
                }
                dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_active));

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(mtoggle.onOptionsItemSelected(item)){
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public class MyTimerTask extends TimerTask{

        @Override
        public void run() {

            HomeActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    if (viewPager.getCurrentItem() == 0){
                        viewPager.setCurrentItem(1);
                    }else if (viewPager.getCurrentItem() == 1){
                        viewPager.setCurrentItem(2);
                    }else{
                        viewPager.setCurrentItem(0);
                    }


                }
            });

        }
    }

    public void myMethod(){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }
    public void exploreActivity(View view){
        myMethod();
    }

    public void packagesActivity(View view){
        Intent intent = new Intent(this,PackagesActivity.class);
        startActivity(intent);
    }

    public void dealsActivity(View view){
        Intent intent = new Intent(this,DealsActivity.class);
        startActivity(intent);
    }
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.explore) {
            Log.d("Explore","Clicked");
            myMethod();
        }
        return false;
    }
   }

但是我得到以下错误

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.windows81.travelspoc, PID: 3485
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.windows81.travelspoc/com.example.windows81.travelspoc.HomeActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2625)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2691)
                      at android.app.ActivityThread.access00(ActivityThread.java:188)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1526)
                      at android.os.Handler.dispatchMessage(Handler.java:111)
                      at android.os.Looper.loop(Looper.java:207)
                      at android.app.ActivityThread.main(ActivityThread.java:5790)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1015)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.design.widget.NavigationView.setNavigationItemSelectedListener(android.support.design.widget.NavigationView$OnNavigationItemSelectedListener)' on a null object reference
                      at com.example.windows81.travelspoc.HomeActivity.onCreate(HomeActivity.java:40)
                      at android.app.Activity.performCreate(Activity.java:6275)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2578)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2691) 
                      at android.app.ActivityThread.access00(ActivityThread.java:188) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1526) 
                      at android.os.Handler.dispatchMessage(Handler.java:111) 
                      at android.os.Looper.loop(Looper.java:207) 
                      at android.app.ActivityThread.main(ActivityThread.java:5790) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1015) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:876) 

试试这个

像这样创建方法

public void myMethod(){
        Intent intent = new Intent(this,ExploreActivity.class);
        startActivity(intent);
    }

而不是在 Button like this

中调用您的方法
public void exploreActivity(View view){
        myMethod()
    }

现在在您的 Activity:

中实施 NavigationView.OnNavigationItemSelectedListener 侦听器
public class YourActivity extends AppCompatActivity implements 
              NavigationView.OnNavigationItemSelectedListene

比集

     NavigationView mNavigationView = (NavigationView) findViewById(R.id.account_navigation_view);
   `mNavigationView.setNavigationItemSelectedListener(this);`

覆盖方法

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

    if (id == R.id.explore) {
            Log.d("Explore","Clicked");
             myMethod()
        }
}

对于导航菜单 -> 使用 NavigationView 创建它

这里是正确的例子 link -> http://v4all123.blogspot.in/2016/02/navigationview-example-in-android.html

使用此方法,您可以从菜单选项创建导航菜单。

另一种方法是使用 Recyclerview -> 制作 Recyclerview 并通过适配器处理您的所有意图。(如果您有动态列表或长列表,那么我建议使用第二种方法。)