Ankit Ostwal Ankit Ostwal - 2 months ago 20
Android Question

How to use onOptionsItemSelected with Single Activity having multiple fragments

The problem i am facing is as i set setDisplayHomeUpAsEnabled(true), on clicking back button onOptionsItemSelected dosent not get called.I doubt if my manifest file is correct.Below i am putting my manifest file.Please suggest .Thank you.

MANIFEST FILE

<?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>


Home Activity

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;
}
}


Home Fragment

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;

}
}

}


Catalogue Fragment

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.");
}

}
}
}

Answer

First, you need to remove parenting metadata from the manifest. It's incorrect.

 <activity
        android:name=".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>
    </activity>

Now, if you want to listen to clicks on any type of NavigationIcon in your custom toolbar (be it a Hamburger or up-caret or some fancy icon) then use setToolbarNavigationClickListener().

In your HomeActivity do this :

toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            /* do whatever you want like popping the fragment from backstack
            getSupportFragmentManager().popBackStackImmediate(); */
        }
    });

I had this problem too. Check this thread : Cannot listen clicks on up caret