Omerixe Omerixe - 3 months ago 22
Android Question

TextView.post Runnable not always working

I have a ListView where Items can be removed by a click on a label. This ListView is in my own Adapter that inherit from BaseAdapter. After the click on this label I’m calling a method that removes the element from the data array stored in my Adapter.

Each element contains some Layout stuff and in one Layout a TextView. Sometimes this view should be visible. But i only know if it should be visible, after the Listview ist layoutet! (I’m asking if it is ellipsized) So i used the post method with a Runnable.

In my

getView
Method i have the following Runnable statement:

holder.llMyItem.post(new Runnable() {
@Override
public void run() {
if (...) {
holder.lblExpand.setVisibility(View.VISIBLE);
}
}
});


llMyItem
is the LinearLayout of the items in the ListView.

lblExpand
is my TextView that should be visible or not.

The first time my View appears it works fine on Android 4.3. But on Android 2.1 it is not working.

The label only appears after I clicked the “next” button on my view. Just before my Activity finished, my Textview will appear. But that’s too late!
And there is a second problem:
After I removed one item in my list with the following method, it will not work after I called
notifyDataSetChanged
. Just after a touch somewhere on the screen, the runnable starts.

I think the two issues have the same root.

Here is the Code for the method that removes the item (I simplified it)

public void removeListItem(int position) {
//do some animation stuff
ArrayList<SomeClass> data = getData();
data.remove (position);
notifyDataSetChanged();
}


(The "item removing thing" is working fine)

I tried it with the invalidate Method on the ListView to redraw it. But it still isn't working. The Runnable is not starting after the layout is finished.

Can anybody help me?

Answer

Just solved it!

Instead of adding the Runnable to my layout I added it to an handler.

Now it looks like that: In my getView method I added this line

//uiHandler is a private Attribute    
uihandler = new Handler();

In my create method I call the post method on my new handler

uiHandler.post(new Runnable() {
   @Override
   public void run() {
       if (...){
          holder.lblExpand.setVisibility(View.VISIBLE);
       }
    }
 });

The hint to this I got from: http://stackoverflow.com/a/4083830/2380896

And this answer, above the other, helps to understand why it wasn't always working: http://stackoverflow.com/a/10457064/2380896