onBackpressed()在marshmallow版本中无法正常工作

时间:2016-05-19 05:38:04

标签: android

目前我正在使用 Android工作室2.1 编译sdk marshmallow 6.0 构建工具版本23.0.3
在我的项目中,当我使用onBackpressed()从AppCompatActivity返回Fragment时,我使用了导航抽屉,它在棒棒糖版本上正常工作但在marshmallow版本中无法正常工作。

这是 Fragment_Subjects 类,你可以看到我想进入下一个屏幕的ActionbarSearchSubjects Activity类 enter image description here 这是活动 ActionbarSearchSubjects enter image description here 现在,当我点击 ActionbarSearchSubjects 操作栏中的“返回”按钮时,它将转到MainActivity而不是 FragmentSubject 此问题仅发生在marshmallow而不是其他Android操作系统中。

FragmentSubject

 public class Fragment_Subjects extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
    // Connection detector
    ConnectionDetector cd;
    // Alert dialog manager
    AlertDialogManager alert = new AlertDialogManager();
    ListView userList;
    public static ZipListCustomAdapter userAdapter = null;
    public static ArrayList<PDF> SubjectArray = new ArrayList<PDF>();
    TextView tv_empty;
    View rootView;
    private SwipeRefreshLayout swipeRefreshLayout;
    // URL to get contacts JSON
    private static String url;

    public Fragment_Subjects() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    //checking internet connections
    private void CheckInternetConnections() {
        cd = new ConnectionDetector(getActivity());
        // Check for internet connection
        if (!cd.isConnectingToInternet()) {
            // Internet Connection is not present
            alert.showAlertDialog(getActivity(), "Internet Connection Error",
                    "Please connect to working Internet connection", false);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        CheckInternetConnections();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_subject, container, false);
        cd = new ConnectionDetector(getActivity());


        LoadUIelements();
        LOAdLisners();

        // Inflate the layout for this fragment
        return rootView;
    }

    private void LOAdLisners() {


        //         set item into adapter
        userAdapter = new ZipListCustomAdapter(getActivity(), R.layout.row_item,
                SubjectArray);
        userList.setAdapter(userAdapter);

        swipeRefreshLayout.setOnRefreshListener(this);
        /**
         * Showing Swipe Refresh animation on activity create
         * As animation won't start on onCreate, post runnable is used
         */
        swipeRefreshLayout.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        swipeRefreshLayout.setRefreshing(true);

                                        Log.d("Runnable method ", "");
                                        new GetPapers().execute();
                                    }
                                }
        );

        /**
         * get on item click listener
         */
        userList.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View v,
                                    final int position, long id) {

                TextView tv_paper_name = (TextView) v.findViewById(R.id.tv_paper_name);
                String subject_name = tv_paper_name.getText().toString();
                File extStore = Environment.getExternalStorageDirectory();
                File myFile = new File(extStore.getAbsolutePath() + "/Exam Papers/" + subject_name + ".pdf");

                if (myFile.exists()) {

                    File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Exam Papers/" + subject_name + ".pdf");  // -> filename
                    Uri path = Uri.fromFile(pdfFile);
                    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                    pdfIntent.setDataAndType(path, "application/pdf");
                    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    try {
                        startActivity(pdfIntent);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(getActivity(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getActivity(), "Download file first", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }

    private void LoadUIelements() {


        swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipe_refresh_layout);
        userList = (ListView) rootView.findViewById(R.id.listView);
        tv_empty = (TextView) rootView.findViewById(R.id.tv_empty);


    }

    /**
     * This method is called when swipe refresh is pulled down
     */
    @Override
    public void onRefresh() {
        Log.d("onRefresh()", "");
        new GetPapers().execute();
    }


    //For fetch the all pdf file in one Directory
    List<String> textFiles(String directory) {
        List<String> textFiles = new ArrayList<String>();
        File dir = new File(directory);
        for (File file : dir.listFiles()) {
            if (file.getName().endsWith((".pdf"))) {
                textFiles.add(file.getName());
            }
        }
        return textFiles;
    }

    /**
     * Async task class to get json by making HTTP call
     */
    private class GetPapers extends AsyncTask<Void, Void, Void> {

        String Response;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // showing refresh animation before making http call
            swipeRefreshLayout.setRefreshing(true);

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            JSONParser sh = new JSONParser();


            url = "http://gcm_chat/subjectzip.php";

            // Making a request to url and getting response
            Response = sh.makeServiceCall(url);
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);

            if (Response != null) {
                SubjectArray.clear();
                try {

                    JSONObject objresponse = new JSONObject(Response);
                    JSONArray jarray = objresponse.getJSONArray("Data");

                    for (int i = 0; i < jarray.length(); i++) {

                        JSONObject jsonObject = jarray.getJSONObject(i);

                        String subject_name = jsonObject.getString("subject_name");
                        String subjectPath = jsonObject.getString("subject_upload");
                        /**
                         * add item in arraylist
                         */
                        SubjectArray.add(new PDF(subject_name, subjectPath));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            } else {
                // stopping swipe refresh
                swipeRefreshLayout.setRefreshing(false);
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

//            userAdapter.notifyDataSetChanged();
            // stopping swipe refresh
            if (getActivity() != null) {
                userAdapter = new ZipListCustomAdapter(getActivity(), R.layout.row_item,
                        SubjectArray);
                userList.setAdapter(userAdapter);
                // stopping swipe refresh
                swipeRefreshLayout.setRefreshing(false);
            }
        }

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();


        if (id == R.id.action_search) {
            if (!cd.isConnectingToInternet()) {
                // Internet Connection is not present
                alert.showAlertDialog(getActivity(), "Internet Connection Error",
                        "Please connect to working Internet connection", false);
                // stop executing code by return
                //  return;
            } else {
                Intent i = new Intent(getActivity(), ActionbarSearchSubjects.class);
                startActivity(i);
            }

            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

ActionbarSearchSubjects

public class ActionbarSearchSubjects extends Activity {
    //object of DownloadTask
    static DownloadTask downloadTask;
    //custom row for list view
    static View row;
    //image button for actionbar back activity
    private ImageButton img_bt;
    //edit text for
    private EditText et;
    //list view for populating subject list
    private ListView SubjectLIst;
    // String array for static list from fragment_Subjects
    private String[] Subject_names = new String[Fragment_Subjects.SubjectArray.size()];
    //array list
    private ArrayList<String> array_sort;
    // text length
    int textlength = 0;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.actionbar_search_subjects);

        // load all elements and widgets
        LOaduiElements();
        //load all listners
        LoAdUIlisners();


    }

    // loading elements
    private void LoAdUIlisners() {

        array_sort = new ArrayList<String>(Arrays.asList(Subject_names));
        //  setListAdapter(new bsAdapter(this));
        SubjectLIst.setAdapter(new bsAdapter(this));
//action bar back button and back activity
        img_bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        //text watcher for action bar search
        et.addTextChangedListener(new TextWatcher() {
            public void afterTextChanged(Editable s) {
                // Abstract Method of TextWatcher Interface.
            }

            public void beforeTextChanged(CharSequence s,
                                          int start, int count, int after) {
                // Abstract Method of TextWatcher Interface.
            }

            public void onTextChanged(CharSequence s,
                                      int start, int before, int count) {
                //getting text length
                textlength = et.getText().length();
                //clear array list
                array_sort.clear();
                //for loop for cnverting text into lower case and adding into array list of array_sort
                for (int i = 0; i < Subject_names.length; i++) {
                    if (textlength <= Subject_names[i].length()) {


                        if (Subject_names[i].toLowerCase().contains(
                                et.getText().toString().toLowerCase().trim())) {
                            array_sort.add(Subject_names[i]);
                        }
                    }
                }
                //called Appendlist method wit parameter of array list
                AppendList(array_sort);
            }
        });

        //list view listener for subject list
        SubjectLIst.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> arg0,
                                    View arg1, int position, long arg3) {

                TextView tv_paper_name = (TextView) findViewById(R.id.tv_paper_name);
                String subject_name = tv_paper_name.getText().toString();
                File extStore = Environment.getExternalStorageDirectory();
                File myFile = new File(extStore.getAbsolutePath() + "/Exam Papers/" + subject_name + ".pdf");
//checking file already present or not?
                if (myFile.exists()) {

                    // pdf file path physical
                    File pdfFile = new File(Environment.getExternalStorageDirectory() + "/Exam Papers/" + subject_name + ".pdf");  // -> filename
                    Uri path = Uri.fromFile(pdfFile);
                    Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
                    pdfIntent.setDataAndType(path, "application/pdf");
                    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

                    try {
                        startActivity(pdfIntent);
                    } catch (ActivityNotFoundException e) {
                        Toast.makeText(getApplicationContext(), "No Application available to view PDF", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "Download file first", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //loading elements
    private void LOaduiElements() {
        img_bt = (ImageButton) findViewById(R.id.img_bt);
        et = (EditText) findViewById(R.id.EditText01);
        SubjectLIst = (ListView) findViewById(android.R.id.list);
        //for loop for to converting array list to String array
        for (int i = 0; i < Fragment_Subjects.SubjectArray.size(); i++) {
            try {
                Subject_names[i] = Fragment_Subjects.SubjectArray.get(i).getName();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //setting uo base adapter
    public void AppendList(ArrayList<String> str) {
        SubjectLIst.setAdapter(new bsAdapter(this));
    }

    public class bsAdapter extends BaseAdapter {
        Activity cntx;

        public bsAdapter(Activity context) {
            // TODO Auto-generated constructor stub
            this.cntx = context;
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return array_sort.size();
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return array_sort.get(position);
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return array_sort.size();
        }

        public View getView(final int position, View convertView, ViewGroup parent) {

            //setting up custom row for listview
            row = convertView;
            UserHolder holder = null;

            if (row == null) {
                LayoutInflater inflater = cntx.getLayoutInflater();
                row = inflater.inflate(R.layout.row_item, parent, false);
                holder = new UserHolder();
                holder.tv_paper_name = (TextView) row.findViewById(R.id.tv_paper_name);
                holder.bt_download = (Button) row.findViewById(R.id.bt_download);
                row.setTag(holder);
            } else {
                holder = (UserHolder) row.getTag();
            }
            // getting subjects names
            final PDF user = Fragment_Subjects.SubjectArray.get(position);
            holder.tv_paper_name.setText(user.getName());
            holder.tv_paper_name.setText(array_sort.get(position));
            final UserHolder finalHolder = holder;

            holder.bt_download.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    Log.i("Download Button Clicked", "**********");
//                Toast.makeText(context, "Download  "+ finalHolder.tv_paper_name.getText().toString()+"  " + position,
//                        Toast.LENGTH_LONG).show();
                    File extStore = Environment.getExternalStorageDirectory();
                    File myFile = new File(extStore.getAbsolutePath() + "/Exam Papers/" + finalHolder.tv_paper_name.getText().toString() + ".pdf");


                    //checking file already present or not?
                    if (!myFile.exists()) {

                        // execute this when the downloader must be fired
                        downloadTask = new DownloadTask(cntx);
                  /*  downloadTask.execute("http://upload/uploads/five-point-someone-chetan-bhagat_ebook.pdf",""+finalHolder.tv_paper_name.getText().toString()+".pdf");*/
                        downloadTask.execute(user.getSubjectPath(), "" + finalHolder.tv_paper_name.getText().toString() + ".pdf");

                    } else {

                        Toast.makeText(getApplicationContext(), "File already Exists in " + myFile, Toast.LENGTH_SHORT).show();
                    }
                }
            });

            return row;
        }
    }

    // holder class for get view method of base adapter
    static class UserHolder {
        TextView tv_paper_name;
        //TextView tv_paper_desc;
        Button bt_download;
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        int count = getFragmentManager().getBackStackEntryCount();

        if (count == 0) {
            super.onBackPressed();
            Intent in = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(in);
        } else {
            getFragmentManager().popBackStack();
        }

    }
}

MainActivity

public class MainActivity extends AppCompatActivity implements FragmentDrawer.FragmentDrawerListener {

    private static String TAG = MainActivity.class.getSimpleName();
    public static MainActivity mainActivity;

    private Toolbar mToolbar;
    private FragmentDrawer drawerFragment;
    public Dialog dialog;
    public Button Yes, No;
    public TextView tv_username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mainActivity = this;
        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        tv_username = (TextView) findViewById(R.id.tv_username);
        tv_username.setText(SharedPreferenceManager.getDefaults("username", getApplicationContext()).toString().toUpperCase());
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        drawerFragment = (FragmentDrawer)
                getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
        drawerFragment.setUp(R.id.fragment_navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout), mToolbar);
        drawerFragment.setDrawerListener(this);

        displayView(0);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


    @Override
    public void onDrawerItemSelected(View view, int position) {
        displayView(position);
    }

    public void displayView(int position) {
        Fragment fragment = null;
        String title = getString(R.string.app_name);

        switch (position) {
            case 0:
                fragment = new Fragment_Home();
                title = getString(R.string.home);
                break;
            case 1:
                fragment = new Fragment_Subjects();
                title = getString(R.string.subject);
                break;
            case 2:
                fragment = new Fragment_Download();
                title = getString(R.string.download);
                break;
            case 3:
                fragment = new Fragment_Notification();
                title = getString(R.string.title_notification);
                break;
            case 4:
                fragment = new Fragment_Chat();
                title = getString(R.string.chat);
                break;
            case 5:
                fragment = new Fragment_EditProfile();
                title = getString(R.string.editprofile);
                break;
            case 6:
                fragment = new Fragment_Aboutus();
                title = getString(R.string.aboutus);
                break;
            case 7:

                title = getString(R.string.action_logout);

                dialog = new Dialog(MainActivity.this, R.style.PauseDialog);
                dialog.setContentView(R.layout.custom_dialog);
                dialog.setTitle("Quit");

                TextView text = (TextView) dialog.findViewById(R.id.textDialog);
                text.setText("ARE YOU SURE WANT TO LOG OUT?");
                dialog.show();

                Yes = (Button) dialog.findViewById(R.id.btn_dialog_Yes);
                Yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        try {
                            dialog.dismiss();
                            //for notifiactiion
                            SharedPreferenceManager.setDefaults_boolean("notification", false, getApplicationContext());
                            LoginActivity.settings.edit().clear().commit();
                            SharedPreferenceManager.ClearAllPreferences(getApplicationContext());
                            Intent intent = new Intent(getApplicationContext(),
                                    LoginActivity.class);
                            // Here we start the next activity, and then call finish()
                            // so that our own will stop running and be removed from the
                            // history stack
                            // set the new task and clear flags
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            startActivity(intent);
                            finish();

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }


                });

                No = (Button) dialog.findViewById(R.id.btn_dialog_no);
                No.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });


                break;
            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getSupportFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.container_body, fragment);
            fragmentTransaction.commit();

            // set the toolbar title
//            getSupportActionBar().setTitle(title);

            getSupportActionBar().setTitle(Html.fromHtml("<font color='#E1E1E1'>" + title + "</font>"));
        }
    }

    @Override
    public void onBackPressed() {


        int count = getFragmentManager().getBackStackEntryCount();

        if (count == 0) {
            super.onBackPressed();
            Intent in = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(in);
        } else {
            getFragmentManager().popBackStack();
        }

    }
}

这是我的 gradle 文件

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.3'

    defaultConfig {
        applicationId "info.exampapers.gtu"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:support-v4:+'
    compile 'com.android.support:design:+'
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.firebase:firebase-client-android:2.5.0'
    compile 'com.firebaseui:firebase-ui:0.3.1'
    compile "com.google.android.gms:play-services-gcm:8.4.0"
}

1 个答案:

答案 0 :(得分:0)

我假设您从活动 Fragment_Subjects 开始活动 ActionbarSearchSubjects 。现在来自活动 ActionbarSearchSubjects 您希望返回活动<按下操作栏上的左上方后退按钮,选择strong> Fragment_Subjects 。只需从那里调用this.finish()或ActivityName.this.finish():

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        this.finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

如果不存在,请在onCreate中添加以下代码:

getActionBar().setDisplayHomeAsUpEnabled(true);