OnOptionsItemSelected方法没有在点击后退按钮android时调用.R.id.home



我有一个带有单个活动(HomeActivity(和3片段的应用程序。当我从Home Fragment遍历到Second Fragment时,我用(setDisplayHomeAsUpEnabled(true)(将Hammburger图标替换为Back按钮。但当我按下Back按钮时,它什么也不做,甚至不调用onOptionsItemSelected()方法。我花了一整天的时间来处理这个错误。请帮助

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.propelbit.jaydeepsaress">
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Include following permission if you want to cache images on SD card -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:name="com.propelbit.jaydeepsaress.JaydeepSarees"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".ui.activity.HomeActivity"
            android:parentActivityName=".ui.activity.HomeActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.propelbit.jaydeepsaress.ui.activity.HomeActivity"/>
        </activity>
    </application>
</manifest>

主页活动

package com.propelbit.jaydeepsaress.ui.activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.fragment.HomeFragment;
public class HomeActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    public ActionBarDrawerToggle toggle;
    Toolbar toolbar;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
         toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();
        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        if (savedInstanceState == null) {
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            toggle.setDrawerIndicatorEnabled(true);
            ft.replace(R.id.content_frame, new HomeFragment());
            ft.commit();
        }
    }


    @Override
    public void onBackPressed() {
       super.onBackPressed();
        FragmentManager fm = getSupportFragmentManager();
        int backStackEntryCount = fm.getBackStackEntryCount();
        Log.d("BSEC",backStackEntryCount+"");
        if (backStackEntryCount > 0) {
            fm.popBackStack();
            if (fm.getBackStackEntryCount() > 0) {
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                toggle.setDrawerIndicatorEnabled(false);
            } else {
                //drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                // Display the Drawer Icon
                toggle.setDrawerIndicatorEnabled(true);
            }
        } else {
            //drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
            getSupportActionBar().setDisplayHomeAsUpEnabled(false);
            // Display the Drawer Icon
            toggle.setDrawerIndicatorEnabled(true);
        }
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        toggle.onConfigurationChanged(newConfig);
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        toggle.syncState();
    }

    @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);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d("TAG",item.getItemId()+"");
        switch (item.getItemId()) {
            case android.R.id.home:
                 // Do nothing handled by fragment.
                return false;
        }
        return super.onOptionsItemSelected(item);
    }
    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }
}

主页片段

package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
/**
 * Created by ankit on 05/09/16.
 */
public class HomeFragment extends Fragment implements View.OnClickListener {

    private Button btnDyedWork, btnFancyPrint, btnBridalcollection, btnBlouse;
    private LinearLayout linearTypeDyedWork, linearTypeFancyPrint;
    private boolean flagDyedWork = false;
    private boolean flagFancyPrint = false;

    private Button btnDyedWorkCatalogue;
    CoordinatorLayout.Behavior behavior;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View vi = inflater.inflate(R.layout.fragment_home, container, false);
        btnDyedWork = (Button) vi.findViewById(R.id.btn_dyed_work);
        btnFancyPrint = (Button) vi.findViewById(R.id.btn_fancy_print);
        btnDyedWork.setOnClickListener(this);
        linearTypeDyedWork = (LinearLayout) vi.findViewById(R.id.type_dyed_work);
        linearTypeFancyPrint = (LinearLayout) vi.findViewById(R.id.type_fancy_print);
        btnDyedWorkCatalogue = (Button) vi.findViewById(R.id.btn_dyed_work_catalogue);
        btnDyedWorkCatalogue.setOnClickListener(this);

        return vi;    }

    public void onClick (View v){
        switch (v. getId()){
            case R.id.btn_dyed_work:
                 if(!flagDyedWork){
                    linearTypeDyedWork.setVisibility(View.VISIBLE);
                    linearTypeFancyPrint.setVisibility(View.GONE);
                    flagDyedWork=true;
                    flagFancyPrint=false;
                    btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
                  }else{
                    linearTypeDyedWork.setVisibility(View.GONE);
                    linearTypeFancyPrint.setVisibility(View.GONE);
                    flagDyedWork=false;
                    flagFancyPrint=false;
                    btnDyedWork.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
                }
                break;
            case R.id.btn_fancy_print:
                 if(!flagFancyPrint){
                    linearTypeDyedWork.setVisibility(View.VISIBLE);
                    linearTypeFancyPrint.setVisibility(View.GONE);
                    flagFancyPrint=true;
                    flagDyedWork=false;
                    btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_up),null);
                  }else{
                    linearTypeDyedWork.setVisibility(View.GONE);
                    linearTypeFancyPrint.setVisibility(View.GONE);
                    flagFancyPrint=false;
                    flagDyedWork=false;
                    btnFancyPrint.setCompoundDrawablesWithIntrinsicBounds(null,null,getResources().getDrawable(R.drawable.ic_keyboard_arrow_down),null);
                }
                break;
            case R.id.btn_dyed_work_catalogue:
                Bundle  bundle=new Bundle();
                bundle.putString("category_id","1");
                CatalogueFragment cf=new CatalogueFragment();
                cf.setArguments(bundle);
                FragmentManager fm=getActivity().getSupportFragmentManager();
                FragmentTransaction ft=fm.beginTransaction();
                ft.replace(R.id.content_frame,cf,"catalogue_fragment");
                //ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                ft.addToBackStack(null);
                ft.commit();
                break;
        }
    }
}

目录片段

package com.propelbit.jaydeepsaress.ui.fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.TextView;
import com.propelbit.jaydeepsaress.R;
import com.propelbit.jaydeepsaress.core.cons.Constants;
import com.propelbit.jaydeepsaress.core.parser.JsonParser;
import com.propelbit.jaydeepsaress.core.pojo.CatalogueDetails;
import com.propelbit.jaydeepsaress.ui.activity.HomeActivity;
import com.propelbit.jaydeepsaress.ui.adapter.AdapterCatalogue;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
/**
 * Created by ankit on 07/09/16.
 */
public class CatalogueFragment extends Fragment {

    String categoryId;
    String serverResponse;
    GridView gridview;
    TextView noDataFound;
    ArrayList<CatalogueDetails> listCatalogue;
    AdapterCatalogue adapter;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
        ((HomeActivity) getActivity()).toggle.setDrawerIndicatorEnabled(false);
        ((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View vi = inflater.inflate(R.layout.fragment_catalogue, container, false);
        if (this.getArguments() != null) {
            categoryId = this.getArguments().getString("category_id");
        }
        listCatalogue=new ArrayList<CatalogueDetails>();
        adapter=new AdapterCatalogue(getActivity(),listCatalogue);
        gridview = (GridView) vi.findViewById(R.id.gridview);
        noDataFound = (TextView) vi.findViewById(R.id.no_data_found);
        gridview.setAdapter(adapter);
        new GetCatalogueDetails().execute(Constants.BASE_URL+"getCatalogueDetails");
        return vi;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Log.d("TAG",item.getItemId()+"");
        switch (item.getItemId()) {
            case android.R.id.home:
                Log.d("Called","Back Button");
                getActivity().onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private class GetCatalogueDetails extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            try {
                OkHttpClient.Builder builder = new OkHttpClient.Builder();
                builder.readTimeout(60, TimeUnit.SECONDS);
                Log.d("CatalogueF",categoryId);
                OkHttpClient client = builder.build();
                RequestBody formBody = new FormBody.Builder()
                        .add("category_id", categoryId)
                        .build();
                Request request = new Request.Builder()
                        .url(params[0])
                        .post(formBody)
                        .build();
                Response response = null;
                response = client.newCall(request).execute();
                serverResponse = response.body().string();
                Log.d("response", serverResponse);
                return JsonParser.parseResponseCode(serverResponse);
            } catch (IOException e) {
                e.printStackTrace();
                return "102";
            } catch (JSONException e) {
                e.printStackTrace();
                return "103";
            }
        }
        @Override
        protected void onPostExecute(String responseCode) {
            try {
                if (responseCode.equals("100")) {
                    ArrayList<CatalogueDetails> temp= JsonParser.parseCatalogueDetails(serverResponse);
                    int size=temp.size();
                    Log.d("size",size+""+temp.get(0).getCatalogueName());
                    if(size>0){
                        listCatalogue.addAll(temp);
                        Log.d("listCatalogue",listCatalogue.size()+"");
                        gridview.setVisibility(View.VISIBLE);
                        noDataFound.setVisibility(View.GONE);
                        adapter.notifyDataSetChanged();
                    }else{
                        gridview.setVisibility(View.GONE);
                        noDataFound.setVisibility(View.VISIBLE);
                        noDataFound.setText("No data found");
                    }
                }else if(responseCode.equals("101")){
                    gridview.setVisibility(View.GONE);
                    noDataFound.setVisibility(View.VISIBLE);
                    noDataFound.setText("SQL Exception.Please try again");
                }else if(responseCode.equals("102")){
                    gridview.setVisibility(View.GONE);
                    noDataFound.setVisibility(View.VISIBLE);
                    noDataFound.setText("IO Exception.Please try again");
                }else if(responseCode.equals("103")){
                    gridview.setVisibility(View.GONE);
                    noDataFound.setVisibility(View.VISIBLE);
                    noDataFound.setText("JSON Exception.Please try again.");
                }

            } catch (JSONException e) {
                e.printStackTrace();
                gridview.setVisibility(View.GONE);
                noDataFound.setVisibility(View.VISIBLE);
                noDataFound.setText("JSON Exception..Please try again.");
            }
        }
    }
}
setHasOptionsMenu(true);

将其包含在片段中,以便可以调用onOptionItemSelected()

最终解决。

现在,如果你想收听自定义工具栏中任何类型NavigationIcon的点击(无论是汉堡、上插入符号还是一些花哨的图标(,请使用setToolbarNavigationClickListener((。无需使用onOptionsItemSelected方法。感谢Protino的建议

// Add the backstack listener
getSupportFragmentManager().addOnBackStackChangedListener(this);
// Handle clicks on the up arrow since this isnt handled by the
        toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentManager fm = getSupportFragmentManager();
                // Pop the backstack all the way back to the initial fragment. Customize if needed
                //fm.popBackStack(fm.getBackStackEntryAt(0).getName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
                if(fm.getBackStackEntryCount() > 0) {
                    fm.popBackStack();
                    toggle.setDrawerIndicatorEnabled(false);
                    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                    drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
                } else {
                    getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                    toggle.setDrawerIndicatorEnabled(true);
                    drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
                }
            }
        });

/**
 * Called everytime we add or remove something from the backstack
 */
@Override
public void onBackStackChanged() {
    if(getSupportFragmentManager().getBackStackEntryCount() > 0) {
        Log.d("Called >0","false");
        toggle.setDrawerIndicatorEnabled(false);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
    } else {
        Log.d("Called <0","true");
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        toggle.setDrawerIndicatorEnabled(true);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
    }
}
/**
 * If you need to move backwards inside the app using the back button, and want to override the
 * the default behaviour which could take you outside the app before you've popped the entire stack
 */
@Override
public void onBackPressed() {
    if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
        getSupportFragmentManager().popBackStackImmediate();
    } else {
        super.onBackPressed();
    }
}

要调用activity方法,应该使用类似于的东西

((YourActivityName)getActivity()).onBackPressed();

要使日志工作,还需要包含标签。

Log.d(TAG, "Your message");

最新更新