I have a ListView with some TextViews, an ImageView & a Button. the ImageView is bydefault 'Invisible'. In button's click handler, I have to do some http calls which can not be done in the UI-Thread, so I have created a background thread for it. Based on the result of the http call, I have to show the ImageView (which was initially 'Invisible').
Here is a part of my layout file (list_row.xml):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_selector"
android:padding="5dip" >
<ImageView
android:id="@+id/imageViewIcon"
android:layout_width="50dip"
android:layout_height="50dip"
android:visibility="invisible"
/>
<TextView
android:id="@+id/textViewName"
...
/>
<Button
android:id="@+id/button"
...
/>
Here is how I am setting the adapter:
ListView appList = (ListView) findViewById(R.id.list);
MyAdapter adapter = new MyAdapter(getApplicationContext(), MainActivity.this, MyDataInAnArray);
appList.setAdapter(adapter);
and here is the MyAdapter class:
public class MyAdapter extends BaseAdapter
{
Context mContext;
Context mActivity;
SomeDataType[] mData;
LayoutInflater mInflater;
public MyAdapter(Context context, Context activity, SomeDatatype[] data)
{
mContext = context;
mActivity = activity;
mData = data;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
..... Some more required @Override functions here ....
@Override
public View getView(final int pos, View convertView, ViewGroup parent)
{
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.list_row, null);
TextView tvName = (TextView) vi.findViewById(R.id.textViewName);
tvName.setText(mData[pos].name);
final ImageView icon = (ImageView) vi.findViewById(R.id.imageViewIcon);
final Button button = (Button) vi.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
String result = Utils.httpPost("MyURLHere", SomePostData);
if (result != null)
{
... and some more processing
**makeIconVisibile(icon);**
}
}
});
thread.start();
}
});
return vi;
}
Question: How should I toggle the visiblity of ImageView in the function makeIconVisible()?
Since the http response processing is in a background thread, I can not modify the visiblity directly from there. I will have to run this on UIThread. both mContext.runOnUiThread & mActivity.runOnUiThread are not working. How should I modify the below function to make it work?
private void makeIconVisible(ImageView icon)
{
// What else is to be done here?
icon.setVisibility(View.VISIBLE);
}
makeIconVisiblein your postExecute mehod of AsynckTask or check out the Volley Library here for faster and cache enable request/response developers.google.com/events/io/sessions/325304728