Android development-PullToRefresh Click event monitoring implementation long-pressed delete Item, androidrefresh

Source: Internet
Author: User

Android development-PullToRefresh Click event monitoring implementation long-pressed delete Item, androidrefresh

This article is the original blog, from http://blog.csdn.net/minimicall

So far, the seller version of search has been basically completed, and it is difficult to solve the problem all the way. The speed is also well controlled.

Project Process progress





In terms of task allocation, I am still a hero. This will not work. However, there is no way at the moment, and the younger brother still needs a learning process. Good intelligence and good attitude. I believe that the buyer will be able to undertake more development tasks.


Next, let's go to the topic and talk about the PullToRefresh click event. In fact, I want to press it to delete it.

See. Of course, this is what I did, but it is not easy.

First



In this case, you can press an item to delete the selected item.


At this time, the menu on the ActionBar changes to a full selection and deletion.


You can also select all items by clicking ActionBar.


Of course, you can cancel all the items on a single machine.

Select, and then press the delete menu, which is the recycle bin icon. It will be deleted and synchronized to the server.

The problem arises first. The click is invalid ..!

Troubleshooting

There are many methods on the Internet.

The first useful thing is: http://www.tuicool.com/articles/ria6Zf


Record your own errors. When writing the ListView Click Event, the OnItemClickListener and onItemClick methods are not executed, leading to the failure of the ListView entry click event. Check that Baidu has many different answers, however, the essence is that the ListView Item obtains focus or the Item does not obtain focus, and even does not bind the OnItemClickListener to listen to the event. The error I made is that a Style is introduced in the Item layout of the ListView, there is a <item name = "android: clickable"> true </item> Item in the Style, which leads to all items to seize the focus, so the click event of ListView is invalid, after I remove this item, the ListView does work normally. What should be taken as a precaution is that in androidl application development, the focus is not obtained or other components often occupy the focus. In code, in xml layout, in general, this setting does not cause any exceptions, but I need to note that important components must get the focus at the right time, otherwise, unexpected consequences will occur, such as my ListView. You can use the following method to obtain the focus of a component:

[Java]View plain copy
  1. View. setFocusable (true), corresponding to xml: android: focusable = "true ".
  2. View. setFocusableInTouchMode (true), corresponding to xml: android: focusableInTouchMode = "true ".

Note: These two attributes must be used at the same time.

The two mean that the component can gain focus. However, there are some differences. After the former executes the false condition and the former executes the true condition, the Focus cannot be obtained. The latter executes the above process and can still obtain the focus.
After you add the preceding code, call requestFocus () of the corresponding view when creating the activity. (requestFocus () needs to be executed after setContentView) to obtain the focus. When editText loses focus, there will be no soft keyboard.

However, for ListView, you can also use the android: descendantFocusability attribute. Let's take a look at the usage of android: descendantFocusability.

From: http://www.cnblogs.com/eyu8874521/archive/2012/10/17/2727882.html

A common problem in development is that the listview in a project is not just a simple text, but you often need to define your own listview, and your own Adapter will inherit the BaseAdapter and write it as needed, the problem may occur. When you click an item, the system does not respond and cannot obtain the focus. Most of the reasons are that sub-controls such as ImageButton, Button, and CheckBox exist in your own defined items (also called the sub-Control of Button or Checkable ), at this time, these child controls will get the focus, so when you click an item, the Child control is changed, and the click of the item itself has no response.

In this case, descendantFocusability can be used to solve the problem. The API description is as follows:

Android: descendantFocusability

Defines the relationship between the ViewGroup and its descendants when looking for a View to take focus.

Must be one of the following constant values.

This attribute defines the relationship between the viewGroup and its child controls when the view gets the focus.

There are three types of attribute values:

BeforeDescendants: viewgroup takes precedence over its subclass control and obtains the focus.

AfterDescendants: viewgroup obtains the focus only when its subclass control does not need to obtain the focus.

BlocksDescendants: viewgroup overwrites the subclass control and directly obtains the focus.

We usually use the third type, that is, adding the android: descendantFocusability = "blocksDescendants" attribute to the root layout of the Item layout. So far, the spirit event clicked by listview has come to an end. Experience: In addition to querying materials on the Internet, you can also try the functions of each attribute, read more official documents (I always think it is better to read the original documents than to translate them)

The second one is intentionally:

Http://blog.csdn.net/kankankankan2222/article/details/7693190

If the view of a single Item in ListView contains a view such as checkbox and button, the ListView. setOnItemClickListener is invalid,

The event is captured by the View, and ListView cannot capture and process the event.

Solution:

Add android: focusable = "false" to the view corresponding to the checkbox and button"
Android: clickable = "false" android: focusableInTouchMode = "false"

Focusable is the key

 

Call getSelectedItemPosition () from OnClickListener. Click and selection are irrelevant. Selection is operated through D-pad or trackball. Click is usually a Click operation.

I made a mistake because I accidentally set the Click listener in getView. It has been commented out by me.

//    private class ClickListner implements OnClickListener {//        private int position;////        private ClickListner(int position) {//            this.position = position;//        }////        @Override//        public void onClick(View v) {//        Log.d(TAG,"xxxxxxxxxxx");//            MCloth cloth = mCloths.get(position);//            if (!isEnabled(position)) {//                return;//            }//            Context context = v.getContext();//            //DetailActivity.launch(context, movie, Referer.NEW_ARRIVIAL);//        }//    }
Next, let's talk about how to implement PullToRefresh to enable long-pressed access to delete selected mode.

Long press to enter the deletion Mode

First, open a function where you need to initialize various views. As follows,

private void setupViews(View rootView) {mListView = (PullToRefreshListView) rootView.findViewById(R.id.cloths_lv);mListView.setMode(PullToRefreshBase.Mode.BOTH);((ViewGroup) mListView.getParent()).addView(mErrorView);mListView.setEmptyView(mErrorView);mClothManageAdapter = new ClothManageAdapter(getActivity(),getImageFetcher());mListView.setAdapter(mClothManageAdapter);((MainActivity) getActivity()).getIndicator().setOnTabSelectedListener(mTabSelectdListener);mProgressBar = (ProgressBar) rootView.findViewById(R.id.pb_progress);setListViewRefresh();setLongClickListener();}

We put our attention on setLongClickListener, which is a private method of my seal, as follows:

Private void setLongClickListener () {Log. d (TAG, "setLongClick"); mListView. getRefreshableView (). setOnItemClickListener (mOnItemClickListener); // click the event listening mListView. getRefreshableView (). setChoiceMode (ListView. CHOICE_MODE_MULTIPLE_MODAL); // select multiple mListView modes. getRefreshableView (). setMultiChoiceModeListener (mMutilChoiceListener); // multiple-choice listener}
Okay. Let's look at the monitoring of the click Time.

Private final OnItemClickListener mOnItemClickListener = new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView <?> Parent, View view, int position, long id) {if (mActionMode = null) {// when you have not pressed the length, go here. Log. d (TAG, "onItemClick, mActionMode is null");} else {// after a long press, enter the selection mode. Log here. d (TAG, "onItemClick, mActionMode is not null, select item" + position + "to select"); mListView. getRefreshableView (). setItemChecked (position, true );}}};
Okay. Let's look at our key multi-choice listener. Directly Add code

Private final MultiChoiceModeListener mMutilChoiceListener = new MultiChoiceModeListener () {@ Overridepublic boolean onCreateActionMode (ActionMode mode, Menu menu) {Log. d (TAG, "onCreateActionMode, mode:" + mode + ", menu:" + menu); mActionMode = mode; getActivity (). getMenuInflater (). inflate (R. menu. menu_favorite_delete, menu); // load the menu to the ActionBar and return true;} @ Overridepublic boolean onPrepareActionMode (Acti OnMode mode, Menu menu) {return false ;}@ Overridepublic void onDestroyActionMode (ActionMode mode) {mActionMode = null ;}@ Overridepublic boolean onActionItemClicked (ActionMode mode, MenuItem item) {switch (item. getItemId () {// menu Click Event case R. id. menu_delete: // Delete Log. d (TAG, "delete menu"); List <MCloth> deleted = new ArrayList <MCloth> (); SparseBooleanArray checked = mListView. getRefreshableView (). getChecked ItemPositions (); for (int I = 0; I <checked. size (); I ++) {Log. d (TAG, "get from Adapter (" + checked. keyAt (I) + "," + checked. valueAt (I) + ")"); if (checked. valueAt (I) {deleted. add (mClothManageAdapter. getItem (checked. keyAt (I); }}// for (MCloth cloth: deleted) {// if (cloth! = Null) {// Log. d (TAG, "deleting the cloth id =" + cloth. id + "in remote server now"); // WEBInterface1.DelCloth (cloth. id); //} new deleteclothtask(cmd.exe cuteOnExecutor (AsyncTask. THREAD_POOL_EXECUTOR, deleted); mClothManageAdapter. remove (deleted); mode. finish (); loadData (true); break; case R. id. menu_selectall: // select all if (mIsSelectAll) {item. setTitle ("cancel all"); mIsSelectAll = false;} else {item. setTitle ("select all"); mIsS ElectAll = true;} for (int I = 0; I <mListView. getRefreshableView (). getCount (); I ++) {mListView. getRefreshableView (). setItemChecked (I ,! MIsSelectAll);} break;} return true;} @ Overridepublic void onItemCheckedStateChanged (ActionMode mode, int position, long id, boolean checked) {setActionModeTitle (mode, mListView. getRefreshableView (). getCheckedItemCount () ;}}; private void setActionModeTitle (ActionMode mode, int count) {Log. d (TAG, "setActionModeTitile, mode:" + mode + ", count:" + count); mActionMode. setTitle ("selected" + count + "cloth ");}
This way
The core code is the above, which achieves the deletion of Long-pressed data. The effect is good. Contact me if you do not understand. We hope that our search products will grow into big trees day by day. Good night. If you want to join our team, contact me. I will help you as much as possible and look forward to your pleasant cooperation.











Click Delete to delete the corresponding file.

ListView. setOnItemLongClickListener (new OnItemLongClickListener (){

@ Override
Public boolean onItemLongClick (AdapterView <?> Arg0, View view,
Int position, long id ){
DeleteDialog ();
Return false;
}
});
/**
* Exit system confirmation box
*/
Private void DeleteDialog (){
AlertDialog. Builder builder = new Builder (ShowActivity. this );

Builder. setMessage ("are you sure you want to delete the file? ");
Builder. setTitle ("prompt ");

Builder. setPositiveButton ("OK", new DialogInterface. OnClickListener (){

@ Override
Public void onClick (DialogInterface dialog, int which ){
// Here, the File constructor parameter is the File path read from your list.
File file = new File (listItem. get (index ));
File. delete ();
// Notify the adapter to update
Adapter = new AAAdapter (this, list );
ListView. setAdapter (adapter );
}
});

Builder. setNegativeButton ("cancel", new DialogInterface. OnClickListener (){

@ Override
Public void onClick (DialogInterface dialog, int which ){

}
});
Builder. create (). show ();
}

// You are not saving the file path in the list. You can use positon to directly obtain the file path ....

Android: how to set the button to click the listener event, first disable the current xml layout, and then load a New xml Layout

You can try activitygroup, or use viewflliper or viewpager in an activity to switch tags.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.