如何使用具有多个片段

时间:2016-09-11 06:25:19

标签: android android-fragments android-fragmentactivity

我面临的问题是当我设置setDisplayHomeUpAsEnabled(true)时,点击后退按钮onOptionsItemSelected dosent not get called.I怀疑我的清单文件是否正确。我正在把我的清单文件。请建议。谢谢。

清单文件

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

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;

        }
    }

}

目录片段

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

        }
    }
}

2 个答案:

答案 0 :(得分:1)

首先,您需要从清单中删除父级元数据。这是不正确的。

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

现在,如果您想收听自定义工具栏中任何类型的NavigationIcon的点击(无论是汉堡包还是向上插图或某些花哨的图标),请使用setToolbarNavigationClickListener()

在您的HomeActivity中执行此操作:

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

我也有这个问题。检查此主题:Cannot listen clicks on up caret

答案 1 :(得分:0)

最好的方法是在活动中处理背压。在片段中,make或者完全删除onOptionsItemSelected方法:

case android.R.id.home:
return false;

在您的活动中:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {

        Log.d("TAG",item.getItemId()+"");

        switch (item.getItemId()) {
            case android.R.id.home:
                 onBackPressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }