如何从另一个片段android关闭动作模式

时间:2016-04-04 10:46:43

标签: android android-fragments

我创建了三个片段。动作模式在一个片段中实现。如果我滑动到下一个片段,则应隐藏动作模式。

我尝试过使用mode.finish()方法,但没有关闭。如何在另一个片段中关闭动作模式。

public class Event_notification extends Fragment {

    List<String> myList;
    private List<FeedItem> feedsList= new ArrayList<FeedItem>();
    ListView listView;
    RelativeLayout emptyview;
    EventNotification_adapter adapter;
    String LiveUrl,userID;
    CheckBox check;
    ArrayList list = new ArrayList();
    String EventStatus,date;
    Context mcontext;
    Dialog dialog;
    private JSONObject EventJsonObject;
    protected static final String TAG = "NOTIFICATION";

    public static final String MY_PREFS_NAME = "MyPrefsFile";
    public Event_notification() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *

     * @return A new instance of fragment Event_notification.
     */
    // TODO: Rename and change types and number of parameters
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getActivity().getActionBar().hide();

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getContext());
        LiveUrl = sharedPreferences.getString("liveurl2", null);
        System.out.println("Liveurl1" + LiveUrl);



        SharedPreferences prefs1 = getContext().getSharedPreferences(MY_PREFS_NAME, getContext().MODE_PRIVATE);
        userID= prefs1.getString("userid", null);
        System.out.println("userid" + userID);

//        actionBar.hide();
        // setHasOptionsMenu(false);

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        System.out.println("Notification Fragment");
        View v=inflater.inflate(R.layout.fragment_event_notification, container, false);
        //return inflater.inflate(R.layout.row_eventnotification, container, false);
        FontChangeCrawler fontChanger = new FontChangeCrawler(getContext().getAssets(), "arial.ttf");
        fontChanger.replaceFonts((ViewGroup) v);
        emptyview=(RelativeLayout)v.findViewById(R.id.empty_view);
        listView=(ListView)v.findViewById(R.id.recycler_view);
        check=(CheckBox)v.findViewById(R.id.check1);
        getnotification();
        adapter=new EventNotification_adapter(getContext(),feedsList,Event_notification.this);

        //adapter = new EventNotification_adapter(getContext(),android.R.layout.simple_list_item_multiple_choice, Event_notification.this);
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

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

                // ListView Clicked item
                FeedItem movie = feedsList.get(position);
                Intent display = new Intent(getContext(),Display_event.class);
                display.putExtra("currentdate", movie.getEventdate());
                display.putExtra("eventid", movie.getEventid());
                display.putExtra("otheruser", movie.getUserid());
                display.putExtra("test", "test");


                System.out.println("date---" + movie.getEventdate()+"event---"+movie.getEventid()+"user--"+movie.getUserid()+"eventname--"+movie.getEventname());
                startActivity(display);

            }
        });


//        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
//            @Override
//            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
//                                           final int pos, long id) {
//
//                check.setVisibility(View.VISIBLE);
//                return true;
//            }
//        });
        this.listView.setSelector(R.drawable.listitem_selector);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);

        listView.setMultiChoiceModeListener(new  MultiChoiceModeListener() {

            @Override

            public boolean  onPrepareActionMode(ActionMode mode, Menu menu) {

                // TODO  Auto-generated method stub

                return false;

            }

           @Override

            public void  onDestroyActionMode(ActionMode mode) {

                // TODO  Auto-generated method stub
            mode.finish();
            }



            @Override

            public boolean  onCreateActionMode(ActionMode mode, Menu menu) {

                // TODO  Auto-generated method stub
               mode.getMenuInflater().inflate(R.menu.multiple_delete, menu);

                return true;

           }

           @Override

            public boolean  onActionItemClicked(final ActionMode mode,

                                               final MenuItem item) {

                // TODO  Auto-generated method stub

                switch  (item.getItemId()) {

                    case R.id.selectAll:

                        final int checkedCount  = feedsList.size();

                        // If item  is already selected or checked then remove or
                        // unchecked  and again select all

                        adapter.removeSelection();

                        for (int i = 0; i <  checkedCount; i++) {

                            listView.setItemChecked(i, true);
                            //  listviewadapter.toggleSelection(i);
                        }

                        mode.setTitle(checkedCount  + "  Selected");

                        return true;

                    case R.id.delete:

                        // Add  dialog for confirmation to delete selected item
                        // record.
                        android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(getContext(), R.style.AppCompatAlertDialogStyle);
                        builder.setMessage("Do you  want to delete selected record(s)?");
                       builder.setNegativeButton("No", new  DialogInterface.OnClickListener() {



                            @Override

                            public void  onClick(DialogInterface dialog, int which) {

                                // TODO  Auto-generated method stub
                            }

                        });

                           builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {


                                @Override

                                public void onClick(DialogInterface dialog, int which) {

                                    // TODO  Auto-generated method stub

                                    SparseBooleanArray selected = adapter

                                            .getSelectedIds();


                                    for (int i = (selected.size() - 1); i >= 0; i--) {

                                        if (selected.valueAt(i)) {
//                                        String selecteditem=Integer.parseInt(selected.keyAt(i));
//

                                            int  selecteditem = selected.keyAt(i);
                                           // String selecteditem1=Integer.toString(item.getItemId());
                                            int selecteditem1=item.getItemId();

                                            System.out.println("idd"+selecteditem1);
                                            EventDelete(selecteditem1);

                                            // Remove  selected items following the ids

                                            adapter.remove(selecteditem);

                                        }

                                    }
                                    // Close CAB
                                mode.finish();
                               selected.clear();
                            }

                        });

                        AlertDialog alert =  builder.create();
                        //alert.setIcon(R.drawable.questionicon);// dialog  Icon
                        alert.setTitle("Confirmation"); // dialog  Title
                        alert.show();
                        return true;
                    default:
                        return false;

                }
            }

           @Override

            public void  onItemCheckedStateChanged(ActionMode mode,

                                                   int position, long id, boolean checked) {

                // TODO  Auto-generated method stub

                final int checkedCount  = listView.getCheckedItemCount();
                // Set the  CAB title according to total checked items
                mode.setTitle(checkedCount  + "  Selected");
               // Calls  toggleSelection method from ListViewAdapter Class
                adapter.toggleSelection(position);

            }
        });

        return v;
    }
    @Override
    public void onDestroyView() {

        super.onDestroyView();
    }

    public void EventDelete(int selecteditem1) {
        //http://demo.cogzideltemplates.com/client/hotfuse_web/mobile/post/deleted_event?event_id=2
        String url = LiveUrl+"block_message?user_id=" + userID+"message_id="+selecteditem1;


        System.out.println("URL IS" + url);
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                EventJsonObject = response.getJSONObject(i);
                                EventStatus = EventJsonObject.getString("status");
                                Log.d("OUTPUT IS", EventStatus);
                                if (EventStatus.matches("blocked")) {
                                    System.out.println("Event Deleted Successfull");
                                    Toast.makeText(mcontext, "Notification Deleted", Toast.LENGTH_SHORT).show();
                                    dialog.dismiss();
                                    adapter.notifyDataSetChanged();
                                }


                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            //pw.setVisibility(View.INVISIBLE);

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //protected static final String TAG = null;
                if (error instanceof NoConnectionError) {
                    Toast.makeText(mcontext, "Sorry we couldn't complete your request.Please try again in a moment", Toast.LENGTH_SHORT).show();
                }

                VolleyLog.d("Error: " + error.getMessage());

            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
        movieReq.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }


    public void getnotification()
    {

       // http://demo.cogzideltemplates.com/client/hotfuse_web/mobile/post/get_event_notify?user_id=1
        String url=LiveUrl+"get_event_notify?user_id="+userID;
        System.out.println("URL IS" + url);
        JsonArrayRequest movieReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject suggested_jsonobj = response.getJSONObject(i);
                                FeedItem movie = new FeedItem();
                                movie.setStatus(suggested_jsonobj.optString("status"));
                                movie.setEventid(suggested_jsonobj.optString("event_id"));
                                movie.setUserid(suggested_jsonobj.optString("user_id"));
                                movie.setThumbnail(suggested_jsonobj.optString("prof_pic"));
                                movie.setMessage(suggested_jsonobj.optString("message"));
                                movie.setTitle1(suggested_jsonobj.optString("username"));

                                movie.setEventname(suggested_jsonobj.optString("event_name"));
                                movie.setEventdate(suggested_jsonobj.optString("event_date"));
                                movie.setEventtime(suggested_jsonobj.optString("created"));
                                movie.setEventdesc(suggested_jsonobj.optString("event_desc"));
                                movie.setEventlocation(suggested_jsonobj.optString("event_location"));
                                feedsList.add(movie);
                                System.out.println("movie list" + feedsList);

                                listView.setAdapter(adapter);
                                adapter.notifyDataSetChanged();

                                if(suggested_jsonobj.optString("status").matches("success"))
                                {

                                    listView.setVisibility(View.VISIBLE);
                                    emptyview.setVisibility(View.GONE);
                                }
                                else
                                {
                                    listView.setVisibility(View.GONE);
                                    emptyview.setVisibility(View.VISIBLE);
                                }


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

                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if(error instanceof NoConnectionError) {
                    Toast.makeText(getContext(), "Sorry we couldn't complete your request.Please try again in a moment", Toast.LENGTH_SHORT).show();
                }

                VolleyLog.d(TAG, "Error: " + error.getMessage());


            }
        });

        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(movieReq);
        movieReq.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }}

0 个答案:

没有答案