I need to add dot indicator to my code for slide show so kindly help me to add this indicator and also click listner for views in page viewer
viewPager = (ViewPager) findViewById(R.id.splash);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.slider,
R.drawable.slider,
R.drawable.slider,
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
// return 10;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
new LoadImage(imageView).execute("http://www.gadgetbaazar.com/wp-content/uploads/2016/12/Top-Mobile-Phones.jpg");
new LoadImage(imageView).execute("https://pisces.bbystatic.com/BestBuy_US/store/ee/2015/com/pm/nav_desktops_1115.jpg");
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img=null;
public LoadImage(ImageView img){
this.img=img;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
Bitmap bitmap=null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
}
}
}
Here i need the indicators if possible along with pageclick listner for this viewpager
I done this using following LIB PageIndicatorView
compile 'com.romandanylyk:pageindicatorview:0.1.1'
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:id="#+id/pager"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
<com.rd.PageIndicatorView
android:id="#+id/pageIndicatorView"
android:layout_width="wrap_content"
android:layout_centerHorizontal="true"
android:layout_above="#+id/buttons"
android:layout_marginBottom="20dp"
app:piv_animationType="swap"
app:piv_viewPager="#id/pager"
android:layout_height="wrap_content" />
Java code
mViewPager = (ViewPager) findViewById(pager);
mViewPager.setAdapter(mCustomPagerAdapter);
//dots
PageIndicatorView pageIndicatorView = (PageIndicatorView) findViewById(R.id.pageIndicatorView);
pageIndicatorView.setViewPager(mViewPager);
OUTPUT
Related
I have just started developing Android application. I have used XAMPP to generate the database(MYSQL) and php to convert the extracted data into JSON. However, I could not display the following JSON output in Android Recyclerview and there is no error being generated while building this application. I have also referred to some other examples/solutions from this website but I still could not solve this issue. The code I have used is below. May I know which part can be corrected or missing?
herblist.php (to convert MYSQL data to JSON)
<?php
include 'dbConnect.php';
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn, 'utf8');
$sql = "SELECT * FROM herb";
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
?>
JSON generated by herblist.php
[{"h_name":"Basil","h_image":"http:\/\/localhost\/Herb\/Herb_image\/basil.jpg"},{"h_name":"Cilantro","h_image":"http:\/\/localhost\/Herb\/Herb_image\/cilantro.jpg"},{"h_name":"Kaffir lime leaf","h_image":"http:\/\/localhost\/Herb\/Herb_image\/kaffir_lime.jpg"},{"h_name":"Lemongrass","h_image":"http:\/\/localhost\/Herb\/Herb_image\/lemongrass.jpg"},{"h_name":"Mint","h_image":"http:\/\/localhost\/Herb\/Herb_image\/mint.jpg"},{"h_name":"Oregano","h_image":"http:\/\/localhost\/Herb\/Herb_image\/oregano.jpg"},{"h_name":"Pandan leaf","h_image":"http:\/\/localhost\/Herb\/Herb_image\/pandan.jpg"},{"h_name":"Parsley","h_image":"http:\/\/localhost\/Herb\/Herb_image\/parsley.jpg"},{"h_name":"Rosemary","h_image":"http:\/\/localhost\/Herb\/Herb_image\/rosemary.jpg"},{"h_name":"Thyme","h_image":"http:\/\/localhost\/Herb\/Herb_image\/thyme.jpg"}]
searchActivity.java (the main activity)
public class searchActivity extends AppCompatActivity {
List<DataAdapter> ListDataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://localhost/Herb/herblist.php";
String Image_Name_JSON = "h_name";
String Image_URL_JSON = "h_image";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager RecyclerViewLayoutManager;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
ImageTitleNameArrayListForClick = new ArrayList<>();
ListDataAdapter = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerview1);
recyclerView.setHasFixedSize(true);
RecyclerViewLayoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(recyclerViewadapter);
recyclerView.setLayoutManager(RecyclerViewLayoutManager);
JSON_HTTP_CALL();
// Implementing Click Listener on RecyclerView.
recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
GestureDetector gestureDetector = new GestureDetector(searchActivity.this, new GestureDetector.SimpleOnGestureListener() {
#Override public boolean onSingleTapUp(MotionEvent motionEvent) {
return true;
}
});
#Override
public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
if(view != null && gestureDetector.onTouchEvent(motionEvent)) {
//Getting RecyclerView Clicked Item value.
RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);
// Showing RecyclerView Clicked Item value using Toast.
Toast.makeText(searchActivity.this, ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
}
return false;
}
#Override
public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
}
public void JSON_HTTP_CALL(){
RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
ParseJSonResponse(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(searchActivity.this);
requestQueue.add(RequestOfJSonArray);
}
public void ParseJSonResponse(JSONArray array){
for(int i = 0; i<array.length(); i++) {
DataAdapter GetDataAdapter2 = new DataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));
// Adding image title name in array to display on RecyclerView click event.
ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
} catch (JSONException e) {
e.printStackTrace();
}
ListDataAdapter.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(ListDataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
}
}
DataAdapter.java (The adapter part of the text in cardview)
public class DataAdapter{
public String ImageURL;
public String ImageTitle;
public String getImageUrl() {return ImageURL;}
public void setImageUrl(String ImageServerUrl) {this.ImageURL = ImageServerUrl;}
public String getImageTitle() {return ImageTitle;}
public void setImageTitle(String ImageTitleName) {this.ImageTitle = ImageTitleName;}
}
ImageAdapter.java (The adapter part of the image in cardview)
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;
List<DataAdapter> dataAdapters;
ImageLoader imageLoader;
public RecyclerViewAdapter(List<DataAdapter> getDataAdapter, Context context){
super();
this.dataAdapters = getDataAdapter;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder Viewholder, int position) {
DataAdapter dataAdapterOBJ = dataAdapters.get(position);
imageLoader = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(dataAdapterOBJ.getImageUrl(),
ImageLoader.getImageListener(
Viewholder.VollyImageView,//Server Image
R.mipmap.ic_launcher,//Before loading server image the default showing image.
android.R.drawable.ic_dialog_alert //Error image if requested image dose not found on server.
)
);
Viewholder.VollyImageView.setImageUrl(dataAdapterOBJ.getImageUrl(), imageLoader);
Viewholder.ImageTitleTextView.setText(dataAdapterOBJ.getImageTitle());
}
#Override
public int getItemCount() {
return dataAdapters.size();
}
class ViewHolder extends RecyclerView.ViewHolder{
public TextView ImageTitleTextView;
public NetworkImageView VollyImageView ;
public ViewHolder(View itemView) {
super(itemView);
ImageTitleTextView = (TextView) itemView.findViewById(R.id.ImageNameTextView) ;
VollyImageView = (NetworkImageView) itemView.findViewById(R.id.VolleyImageView) ;
}
}
}
activity_search.xml (xml file of the main activity)
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
cardview.xml
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cardview1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
card_view:cardElevation="5dp"
card_view:contentPadding="5dp"
card_view:cardCornerRadius="5dp"
card_view:cardMaxElevation="5dp"
>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#ECEFF1">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/VolleyImageView"
android:layout_width="150dp"
android:layout_height="100dp"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toEndOf="#+id/VolleyImageView"
android:textSize="20sp"
android:textColor="#000"
android:text="JSon Image Name"
android:id="#+id/ImageNameTextView"
android:layout_centerVertical="true"/>
</RelativeLayout>
</android.support.v7.widget.CardView>
First change this
recyclerView.setHasFixedSize(true);
RecyclerViewLayoutManager = new LinearLayoutManager(this);
recyclerView.setAdapter(recyclerViewadapter);
recyclerView.setLayoutManager(RecyclerViewLayoutManager);
To
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerViewadapter = new RecyclerViewAdapter(ListDataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
Second remove this two line from JSON_HTTP_CALL() method
recyclerViewadapter = new RecyclerViewAdapter(ListDataAdapter, this);
recyclerView.setAdapter(recyclerViewadapter);
and put this line
recyclerViewadapter.notifyDataSetChanged();
public Object instantiateItem(ViewGroup container, int position) {
Context context = FullImageActivity.this; // i get error in this line that its not an enclosing class
I simply want to call FullImageActivity to ImageAdapter class
ImageAdapter class
public class ImageAdapter extends PagerAdapter {
public String mImages[] = {("http://www.fashionlady.in/wp-content/uploads/2016/03/creative-punjabi-mehndi-design-2016.jpg"),
("https://lumiere-a.akamaihd.net/v1/images/uk_toystory_chi_woody_n_5b5a006f.png?region=0,0,300,300"),
("https://lumiere-a.akamaihd.net/v1/images/open-uri20150422-20810-10n7ovy_9b42e613.jpeg"),
("http://www.wetpaint.com/wp-content/uploads/2015/11/toy-story-20th-anniversary.jpg"),
("http://i.imgur.com/4IZMjx3.jpg")};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = FullImageActivity.this;
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
Picasso.with(context).load(mImages[position]).placeholder(R.drawable.loading2).error(R.drawable.nointernet).into(imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
This is my FullImageActivity class
public class FullImageActivity extends AppCompatActivity {
TouchImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("ViewPager");
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
TouchImageView img = new TouchImageView(this);
int position = i.getExtras().getInt("id");
ImageAdapter adapter = new ImageAdapter();
img = (TouchImageView) findViewById(R.id.img);
img.setMaxZoom(4f);
Picasso.with(getApplicationContext()).load(adapter.mImages[position]).into(img);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
}
Your Adapter Class
public class ImageAdapter extends PagerAdapter {
Context activity_context;
public String mImages[] = {("http://www.fashionlady.in/wp-content/uploads/2016/03/creative-punjabi-mehndi-design-2016.jpg"),
("https://lumiere-a.akamaihd.net/v1/images/uk_toystory_chi_woody_n_5b5a006f.png?region=0,0,300,300"),
("https://lumiere-a.akamaihd.net/v1/images/open-uri20150422-20810-10n7ovy_9b42e613.jpeg"),
("http://www.wetpaint.com/wp-content/uploads/2015/11/toy-story-20th-anniversary.jpg"),
("http://i.imgur.com/4IZMjx3.jpg")};
public ImageAdapter(Context context)
{
activity_context=context;
}
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(activity_context);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
Picasso.with(activity_context).load(mImages[position]).placeholder(R.drawable.loading2).error(R.drawable.nointernet).into(imageView);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Your Activity class
public class FullImageActivity extends AppCompatActivity {
TouchImageView img;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("ViewPager");
setContentView(R.layout.activity_full_image);
Intent i = getIntent();
TouchImageView img = new TouchImageView(this);
int position = i.getExtras().getInt("id");
ImageAdapter adapter = new ImageAdapter(FullImageActivity.this);
img = (TouchImageView) findViewById(R.id.img);
img.setMaxZoom(4f);
Picasso.with(getApplicationContext()).load(adapter.mImages[position]).into(img);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setAdapter(adapter);
}
Here i have two url but when i run this app this images are been loaded to second page means first image will load in second page after few second the second image also adds to same loaction by overlapping. i need to add this to second and third pages these url
viewPager = (ViewPager) findViewById(R.id.splash);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
public class ImageAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.slider,
R.drawable.slider,
R.drawable.slider,
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
// return 10;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
imageView.setImageResource(GalImages[position]);
new LoadImage(imageView).execute("http://www.gadgetbaazar.com/wp-content/uploads/2016/12/Top-Mobile-Phones.jpg");
new LoadImage(imageView).execute("https://pisces.bbystatic.com/BestBuy_US/store/ee/2015/com/pm/nav_desktops_1115.jpg");
container.addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
ImageView img=null;
public LoadImage(ImageView img){
this.img=img;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
Bitmap bitmap=null;
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
}
}
}
}
Try this
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
if(position == 0){
imageView.setImageResource(GalImages[position]);
}else if(position == 1){
new LoadImage(imageView).execute("http://www.gadgetbaazar.com/wp-content/uploads/2016/12/Top-Mobile-Phones.jpg");
}else if(position ==2){
new LoadImage(imageView).execute("https://pisces.bbystatic.com/BestBuy_US/store/ee/2015/com/pm/nav_desktops_1115.jpg");
}
container.addView(imageView, 0);
return imageView;
}
I'm using the PhotoView library to have a slide view of images. That's easy. Then I wanted set as wallpaper the image I wanted, maybe on click in a button but I have a problem! The library seems that not allows create a layout but only its in this way.
<com.ex.paper.HackyViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
So i can't add any button. I need detect the right array position and in some way set that image as wallpaper.. So far the code is this:
`public class MainActivity extends Activity
{
Bitmap bitmap;
int lastImageRef;
private static final String ISLOCKED_ARG = "isLocked";
private ViewPager mViewPager;
private static MenuItem menuLockItem;
private WallpaperManager wallpaper;
private static int[] sDrawables = { R.drawable.wallpapertwo, R.drawable.twixkatfirst, R.drawable.wallpaper,
R.drawable.sfondo, R.drawable.wallpapertre};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
setContentView(mViewPager);
mViewPager.setAdapter(new SamplePagerAdapter());
if (savedInstanceState != null) {
boolean isLocked = savedInstanceState.getBoolean(ISLOCKED_ARG, false);
((HackyViewPager) mViewPager).setLocked(isLocked);
}
}
static class SamplePagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return sDrawables.length;
}
#Override
public View instantiateItem(ViewGroup container, int position) {
PhotoView photoView = new PhotoView(container.getContext());
photoView.setImageResource(sDrawables[position]);
WallpaperManager wallpaper = WallpaperManager.getInstance(container.getContext());
/*Toast number = Toast.makeText(container.getContext(), "wallpaper number "+position, Toast.LENGTH_LONG);
number.show();*/
// Now just add PhotoView to ViewPager and return it
container.addView(photoView, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
try
{
wallpaper.setResource(sDrawables[position]);
}
catch (IOException e)
{
}
return photoView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}`
Now, in the try catch, I can set the wallpaper through position but without tapping any button!! And of course it's not a good way. Any solution? Maybe a button in the actionbar? But I can't find the array position at that point.
You can use FrameLayout:
<FrameLayout...>
<com.ex.paper.HackyViewPager/>
<Button/>
<FrameLayout/>
In onCreate:
setContentView(your.layout.with.frameLayout);
mViewPager = (HackyViewPager) findViewById(R.id.view_pager);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
wallpaper.setResource(sDrawables[mViewPager.getCurrentItem()]);
}
});
}
I have a ListView that each item in the list contains multiple images.
When I create the list, I want to async download the image so the list can show fast and the images can fill in when they are downloaded.
I have extended the AsyncTask class and implemented a simple download method. However, I am not sure how to update the image back to the correct position in the list view in:
#Override
protected void onPostExecute(Bitmap result) {
// TODO show the downloaded image to the list
super.onPostExecute(result);
}
Here's my class definition:
public class ImageDownloadWorker extends AsyncTask<String, Void, Bitmap>
And my doInBackground method:
#Override
protected Bitmap doInBackground(String... params) {
try {
return downloadBitmap(params[0]);
} catch (ClientProtocolException e) {
return null;
} catch (Exception e) {
return null;
}
}
What is the common pattern we should use to map the downloaded image to the correct ImageView of the correct list item in the list? Thank you!
You need to implement an adapter pattern to populate the listview. In your case, you can create a custom adapter class and extend BaseAdapter and implement all its methods. The pattern goes like this.
MainActivity.java
public class MainActivity extends Activity {
private ListView listView;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = findViewById(android.R.id.list);
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... strings) {
try {
return downloadBitmap(params[0]);
} catch (ClientProtocolException e) {
return null;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(Bitmap bitmap) {
adapter = new CustomAdapter(bitmap);
listView.setAdapter(adapter);
super.onPostExecute(bitmap);
}
}
private class CustomAdapter extends BaseAdapter {
private Bitmap bitmap;
private LayoutInflater inflater = null;
class ViewHolder {
ImageView image;
}
public CustomAdapter(Bitmap bitmap) {
this.bitmap = bitmap;
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.list_item, parent, false);
holder.image = convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.image.setImageBitmap();
return convertView;
}
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="#+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
However, when you are loading many images into the listview, create an ArrayList and send that to the listAdapter
I need to do the same of you in lot of projects and this library is very very helpful and very simple to use:
https://github.com/koush/UrlImageViewHelper