How to temporarily stop the clicking effect before changing adapter data?
background
When I select an item from the ListView, I change its data and call notifyDataSetChanged.
Problem
Since it is the same listView, when I click the item, the effect remains for the view to be used after notifyDataSetChanged.
This is especially noticeable on Android Lollipop, where the ripple can continue after the listView is updated with new data.
Code
Here is some sample code showing the problem:
public class MainActivity extends ActionBarActivity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=(ListView)findViewById(R.id.listView);
listView.setAdapter(new BaseAdapter()
{
int pressCount=0;
@Override
public int getCount()
{
return 100;
}
@Override
public Object getItem(int position)
{
return null;
}
@Override
public long getItemId(int position)
{
return 0;
}
@Override
public View getView(int position,View convertView,ViewGroup parent)
{
View rootView=convertView;
if(rootView==null)
{
rootView=LayoutInflater.from(MainActivity.this).inflate(android.R.layout.simple_list_item_1,parent,false);
rootView.setBackgroundResource(getResIdFromAttribute(MainActivity.this,android.R.attr.selectableItemBackground));
rootView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
pressCount++;
notifyDataSetChanged();
}
});
}
TextView tv=(TextView)rootView;
tv.setText("text:"+(pressCount+position));
return rootView;
}
});
}
public static int getResIdFromAttribute(final Activity activity,final int attr)
{
if(attr==0)
return 0;
final TypedValue typedvalueattr=new TypedValue();
activity.getTheme().resolveAttribute(attr,typedvalueattr,true);
return typedvalueattr.resourceId;
}
}
Question
How can I temporarily pause the selection effect until the next click on the ListView (but also resume it the next time the user clicks the item)?
source to share
Ok I found the answer. This seems to be a known issue and the solution is quite simple (shown here ):
ViewCompat.jumpDrawablesToCurrentState(view);
Strange, this only works for me when I call it via Handler.post (...).
I wonder why (since the view is already during animation) and if there is a better solution.
source to share