I am new to android and facing one very comman problem of listview i googled alot but did'nt found anything usefull for my case.Hope you people show me the right direction.Whenever I am changing my image from "plus" to "tick" on click my last item image also got automatically changed on scroll.
My list_comapare_product 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:background="#color/white_color"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="100dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/white_color"
android:gravity="center_vertical" >
<ImageView
android:id="#+id/img_product"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/crane" />
<com.mss.skyjack.custom.views.SkyjackCustomTextview
android:id="#+id/tv_product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center"
android:text="test"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ImageView
android:id="#+id/img_plus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:src="#drawable/plus" />
</RelativeLayout>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#color/black_color" />
</LinearLayout>
Here is my Adapter :-
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ComapreProductSelectionAdapter extends BaseAdapter {
Activity activity;
List<SelectorTest> listSelector;
private LayoutInflater mLayoutInflater;
public ComapreProductSelectionAdapter(Activity activity,
List<SelectorTest> listSelector) {
this.activity = activity;
this.listSelector = listSelector;
mLayoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listSelector.size();
}
#Override
public SelectorTest getItem(int position) {
return listSelector.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int i = position;
final SelectorTest listItem = listSelector.get(position);
if (convertView == null) {
convertView = mLayoutInflater.inflate(
R.layout.list_comapare_product, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvProductName = (TextView) convertView
.findViewById(R.id.tv_product_name);
viewHolder.imgProduct = (ImageView) convertView
.findViewById(R.id.img_product);
viewHolder.imgadd = (ImageView) convertView
.findViewById(R.id.img_plus);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imgadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.imgadd.getDrawable().getConstantState() == activity
.getResources().getDrawable(R.drawable.plus)
.getConstantState()) {
viewHolder.imgadd.setImageResource(R.drawable.tick);
} else {
viewHolder.imgadd.setImageResource(R.drawable.plus);
}
}
});
return convertView;
}
static class ViewHolder {
TextView tvProductName;
ImageView imgProduct, imgadd;
View viewRightLine;
}
}
Thanks.
You need to keep track of which items have been "ticked". I copied your adapter and made necessary changes. You can just copy-paste the code and it should work.
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class ComapreProductSelectionAdapter extends BaseAdapter {
Activity activity;
List<SelectorTest> listSelector;
private LayoutInflater mLayoutInflater;
private ArrayList<Integer> tickedItems = new ArrayList<Integer>();
public ComapreProductSelectionAdapter(Activity activity,
List<SelectorTest> listSelector) {
this.activity = activity;
this.listSelector = listSelector;
mLayoutInflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return listSelector.size();
}
#Override
public SelectorTest getItem(int position) {
return listSelector.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final int i = position;
final SelectorTest listItem = listSelector.get(position);
if (convertView == null) {
convertView = mLayoutInflater.inflate(
R.layout.list_comapare_product, parent, false);
viewHolder = new ViewHolder();
viewHolder.tvProductName = (TextView) convertView
.findViewById(R.id.tv_product_name);
viewHolder.imgProduct = (ImageView) convertView
.findViewById(R.id.img_product);
viewHolder.imgadd = (ImageView) convertView
.findViewById(R.id.img_plus);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imgadd.setTag(position);
viewHolder.imgadd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(tickedItems.contains((Integer)v.getTag()) {
//Already ticked, set to plus
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.plus));
tickedItems.remove((Integer)v.getTag());
} else {
tickedItems.add((Integer)v.getTag());
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.tick));
}
}
});
if(tickedItems.contains(position))
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.tick));
else
viewHolder.imgadd.setImageDrawable(activity.getResources().getDrawable(R.drawable.plus));
return convertView;
}
static class ViewHolder {
TextView tvProductName;
ImageView imgProduct, imgadd;
View viewRightLine;
}
}
As an extra, don't use ImageView.setImageResource() as it is inefficient.
Quote from Android docs about ImageView.setImageReource()
This does Bitmap reading and decoding on the UI thread, which can cause a latency hiccup. If that's a concern, consider using setImageDrawable(android.graphics.drawable.Drawable) or setImageBitmap(android.graphics.Bitmap) and BitmapFactory instead.
Related
I currently have a grid view using a base adapter inside a fragment and I am trying to transfer to a different fragment when one of the items is clicked but none of the solutions I found on stack overflow has worked. I might miss something.
Adapter
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.licenta.joberfrontend.R;
import com.licenta.joberfrontend.rest.backend_entieties.Category;
import java.util.ArrayList;
import java.util.List;
public class CategoriesAdapter extends BaseAdapter {
public class ViewHolder {
TextView textName;
ImageView imageView;
}
private ArrayList<Category> categoryList;
public Context context;
public CategoriesAdapter(List<Category> apps, Context context) {
this.context = context;
this.categoryList = (ArrayList<Category>) apps;
}
#Override
public int getCount() {
return categoryList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View view, ViewGroup parent) // inflating the layout and initializing widgets
{
ViewHolder viewHolder;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.category_list_content, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = view.findViewById(R.id.textName);
viewHolder.imageView = view.findViewById(R.id.iconView);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
// here we are setting up the names and images
viewHolder.textName.setText(categoryList.get(position).getName());
viewHolder.imageView.setImageResource(this.context.getResources().getIdentifier(categoryList.get(position).getCategoryIconId(), "mipmap", this.context.getPackageName()));
return view;
}
}
Fragment's OnCreate
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LocalStorageSaver localStorageSaver = new LocalStorageSaver(Objects.requireNonNull(getContext()));
final ToastShower toastShower = new ToastShower();
//REST services creation
final RetrofitCreator retrofitCreator = new RetrofitCreator();
final Retrofit retrofit = retrofitCreator.getRetrofit();
final CategoryService categoryService = retrofit.create(CategoryService.class);
final Call<List<Category>> getCategoriesRequest = categoryService.getAllCategoriesAndTheirJobs(localStorageSaver.getValueFromStorage(Constants.TOKEN));
getCategoriesRequest.enqueue(
new Callback<List<Category>>() {
#Override
public void onResponse(Call<List<Category>> call, Response<List<Category>> response) {
toastShower.showToast("Categories succesfully retrieved from backend.", getContext());
final GridView gridView = Objects.requireNonNull(getView()).findViewById(R.id.gridViewNewContract);
gridView.setAdapter(new CategoriesAdapter(response.body(), getActivity()));
}
#Override
public void onFailure(Call<List<Category>> call, Throwable t) {
toastShower.showToast("There has been a problem with retrieving the categories data!", getContext());
}
}
);
}
Items inside the grid view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="100dp"
android:layout_height="100dp"
app:cardCornerRadius="15dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginLeft="10dp"
android:layout_marginTop="15dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="15dp"
android:orientation="vertical">
<ImageView
android:id="#+id/iconView"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
android:src="#mipmap/ic_list"
android:tint="#color/colorAccent" />
<TextView
android:id="#+id/textName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:fontFamily="sans-serif"
android:maxLength="12"
android:text="#string/appName"
android:textColor="#color/colorAccent"
android:textSize="13sp" />
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
If you need any more information I will gladly provided.
I can mention that I've tried placing listeners both in the adapter and in the fragment directly on the grid.
please try this
viewHolder.imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do stuff
}
});
my ListView I would like to be about a height of 50dp, but the problem is no matter what value I set the xml layout file too, it automatically makes it much bigger.
Here is my listview layout:
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/mainListView"
android:layout_below="#+id/"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp" />
My rowview is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="?android:attr/listPreferredItemHeight">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/"
android:layout_alignParentTop="false"
android:layout_alignParentLeft="false"
android:layout_alignParentStart="false"
android:textColor="#000000"
android:layout_centerVertical="true"
android:layout_marginLeft="5dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/"
android:layout_alignParentRight="false"
android:layout_alignParentEnd="false"
android:layout_alignParentLeft="false"
android:layout_toRightOf="#+id/"
android:textColor="#000000"
android:layout_centerVertical="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/usernameTextView"
android:layout_below="#+id/"
android:textColor="#666666"
android:layout_toRightOf="#+id/" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/"
android:layout_alignParentTop="false"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
</RelativeLayout>
And my LocalQueueAdapter
package .skyrealm.com;
import android.content.Context;
import android.graphics.Color;
import android.text.Layout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by RockyFish on 1/24/16.
*/
public class LocalQueueAdapter extends BaseAdapter {
Context context;
LayoutInflater layoutInflater;
ArrayList<ArrayList<String>> localQueueInfo;
public LocalQueueAdapter(Context context, ArrayList<ArrayList<String>> localQueueInfo)
{
this.context = context;
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.localQueueInfo = localQueueInfo;
}
#Override
public int getCount() {
return localQueueInfo.size();
}
#Override
public Object getItem(int position) {
return localQueueInfo.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder
{
TextView songNameTextView, artistNameTextView, usernameTextView, numberEditText;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = layoutInflater.inflate(R.layout.local_queue_list_item, null);
Holder holder = new Holder();
holder.songNameTextView = (TextView) rowView.findViewById(R.id.songNameTextView);
holder.artistNameTextView = (TextView) rowView.findViewById(R.id.artistNameTextView);
holder.usernameTextView = (TextView) rowView.findViewById(R.id.usernameTextView);
holder.numberEditText = (TextView) rowView.findViewById(R.id.numberTextView);
holder.songNameTextView.setText(" " + localQueueInfo.get(position).get(1));
holder.artistNameTextView.setText(" - " + localQueueInfo.get(position).get(2));
holder.usernameTextView.setText(localQueueInfo.get(position).get(4));
holder.numberEditText.setText(String.valueOf(position + 1) + ".");
if(position == 0)
{
rowView.setBackgroundColor(Color.parseColor("#45B8AC"));
} else if(position == 1)
{
rowView.setBackgroundColor(Color.parseColor("#74E2D5"));
}
return rowView;
}
}
Thank you!
The problem is the inflater. I'm not really sure why. The code below should work for you. Also, you didn't understand how to use ViewHolder (Here is an example and the explanation: https://www.codeofaninja.com/2013/09/android-viewholder-pattern-example.html)
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
View convertView = LayoutInflater.from(context).inflate(R.layout.local_queue_list_item, parent, false);
Holder holder = new Holder();
holder.songNameTextView = (TextView) rowView.findViewById(R.id.songNameTextView);
holder.artistNameTextView = (TextView) rowView.findViewById(R.id.artistNameTextView);
holder.usernameTextView = (TextView) rowView.findViewById(R.id.usernameTextView);
holder.numberEditText = (TextView) rowView.findViewById(R.id.numberTextView);
convertView.setTag(holder);
}
Holder holder = convertView.getTag();
....
return convertView;
}
Hi I'm trying to show text, image alternatively in list view. To load the content into my list view i had three scenarios.
1. Some times i'm getting only the text from json. So, in this case i have to hide the ImageView
2. Some cases i'm getting only the image url from json. So, in this case i have to hide the TextView
3. In other case i'm getting both image url and text from json, so, in this case i don't have to hide anything
By following these scenarios i'm loading all the content correctly at first time but when i'm scrolling top to bottom and bottom to up. All the image views are filled with images (But there is no image url for that particular position)
My adapter code is
package com.app.listviewitemid.adapter;
import java.util.ArrayList;
import com.app.listviewitemid.R;
import com.app.listviewitemid.model.Items;
import com.bumptech.glide.Glide;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ItemsAdapter extends ArrayAdapter<Items>{
ArrayList<Items> itemsArrayList;
int Resource;
LayoutInflater inflater;
Context context;
ViewHolder holder;
Button btnCheck;
Items globPosition;
public ItemsAdapter(Context context, int resource, ArrayList<Items> objects){
super(context, resource, objects);
this.context = context;
this.Resource = resource;
this.itemsArrayList = objects;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if(v == null){
v = inflater.inflate(Resource, null);
holder = new ViewHolder();
holder.tvPostID = (TextView) v.findViewById(R.id.tv_post_id);
holder.tvPostText = (TextView) v.findViewById(R.id.tv_post_text);
holder.ivPostImage = (ImageView) v.findViewById(R.id.iv_post_img);
btnCheck = (Button) v.findViewById(R.id.btn_check);
v.setTag(holder);
}else{
holder = (ViewHolder) v.getTag();
}
globPosition = itemsArrayList.get(position);
holder.tvPostID.setText(itemsArrayList.get(position).getPostID());
if(globPosition.getPostText().equals(null) || globPosition.getPostText().equals("")){
}else {
holder.tvPostText.setText(globPosition.getPostText());
}
if(globPosition.getPostImage().equals(null) || globPosition.getPostImage().equals("")){
}else {
Glide.with(context).load(globPosition.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(holder.ivPostImage);
}
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("PostID", globPosition.getPostID());
}
});
return v;
}
static class ViewHolder{
TextView tvPostID;
TextView tvPostText;
ImageView ivPostImage;
}
}
adapter layout
<?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" >
<TextView
android:id="#+id/tv_post_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/post_id"
android:textColor="#000000"
android:textSize="12sp" />
<TextView
android:id="#+id/tv_post_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textSize="12sp" />
<ImageView
android:id="#+id/iv_post_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="#string/empty" />
<Button
android:id="#+id/btn_check"
android:layout_width="match_parent"
android:layout_height="35dp"
android:background="#000000"
android:text="#string/check"
android:textColor="#FFFFFF" />
</LinearLayout>
How to get rid of this?
if(globPosition.getPostText().equals(null) || globPosition.getPostText().equals("")){
holder.tvPostText.setVisibility(View.GONE);
}else {
holder.ivPostImage.setVisibility(View.GONE);
holder.tvPostText.setVisibility(View.VISIBLE);
holder.tvPostText.setText(globPosition.getPostText());
}
if(globPosition.getPostImage().equals(null) || globPosition.getPostImage().equals("")){
holder.ivPostImage.setVisibility(View.GONE);
}else {
holder.ivPostImage.setVisibility(View.GONE);
holder.tvPostText.setVisibility(View.VISIBLE);
Glide.with(context).load(globPosition.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(holder.ivPostImage);
}
I got the idea from ankit aggarwal answer (his code is not working properly but he gave me the basic idea). And one more thing, previously i didn't get the correct position, so i changed the adapter code little bit
Code
package com.app.listviewitemid.adapter;
import java.util.List;
import com.app.listviewitemid.R;
import com.app.listviewitemid.model.Items;
import com.bumptech.glide.Glide;
import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class ItemsAdapter extends BaseAdapter{
List<Items> itemsArrayList;
int Resource;
LayoutInflater inflater;
Context context;
Button btnCheck;
public ItemsAdapter(Context context, List<Items> items) {
this.context = context;
this.itemsArrayList = items;
}
#Override
public int getCount() {
return itemsArrayList.size();
}
#Override
public Object getItem(int location) {
return itemsArrayList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#SuppressLint("InflateParams") #Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.adapter_layout, null);
TextView tvPostID = (TextView) convertView.findViewById(R.id.tv_post_id);
TextView tvPostText = (TextView) convertView.findViewById(R.id.tv_post_text);
ImageView ivPostImage = (ImageView) convertView.findViewById(R.id.iv_post_img);
btnCheck = (Button) convertView.findViewById(R.id.btn_check);
final Items items = itemsArrayList.get(position);
tvPostID.setText(items.getPostID());
if(items.getPostText().equals(null) || items.getPostText().equals("")){
tvPostText.setVisibility(View.GONE);
}else {
//ivPostImage.setVisibility(View.GONE);
if(items.getPostImage().equals(null) || items.getPostImage().equals("")){
ivPostImage.setVisibility(View.GONE);
}else {
ivPostImage.setVisibility(View.VISIBLE);
tvPostText.setVisibility(View.GONE);
Glide.with(context).load(items.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(ivPostImage);
}
tvPostText.setVisibility(View.VISIBLE);
tvPostText.setText(items.getPostText());
}
if(items.getPostImage().equals(null) || items.getPostImage().equals("")){
ivPostImage.setVisibility(View.GONE);
}else {
ivPostImage.setVisibility(View.VISIBLE);
//tvPostText.setVisibility(View.GONE);
if(items.getPostText().equals(null) || items.getPostText().equals("")){
tvPostText.setVisibility(View.GONE);
}else {
tvPostText.setVisibility(View.VISIBLE);
tvPostText.setText(items.getPostText());
}
Glide.with(context).load(items.getPostImage()).placeholder(R.drawable.loading_img).error(R.drawable.bg_480_800).into(ivPostImage);
}
btnCheck.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("PostID", items.getPostID());
}
});
return convertView;
}
}
Thanks to ankit aggarwal
I am new in android..
Can someone tell me what is wrong with my code? I am trying to make gallery in Fragment. When I install the apk file on the device, the program works but in that Fragment I see white screen instead of Gallery.Please help me :)
That is my Fragment class
package info.androidhive.fitnesslascalla;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.Toast;
public class ForUsFragment extends Fragment{
public class MainActivity extends Activity
{
ImageView selectedImage;
private Integer[] mImageIds = {
R.drawable.car1,
R.drawable.car2,
R.drawable.car3,
R.drawable.car4,
R.drawable.car5,
R.drawable.car6,
R.drawable.car7,
R.drawable.car8
};
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle saedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_for_us, parent, false);
//setContentView(R.layout.fragment_for_us);
Gallery gallery = (Gallery) findViewById(R.id.gallery1);
selectedImage=(ImageView)findViewById(R.id.image1);
gallery.setSpacing(1);
gallery.setAdapter(new GalleryImageAdapter(this));
// clicklistener for Gallery
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(MainActivity.this, "Your selected position = " + position, Toast.LENGTH_SHORT).show();
// show the selected Image
selectedImage.setImageResource(mImageIds[position]);
}
});
return rootView;
}
}
public class GalleryImageAdapter extends BaseAdapter
{
private Context mContext;
private Integer[] mImageIds = {
R.drawable.car1,
R.drawable.car2,
R.drawable.car3,
R.drawable.car4,
R.drawable.car5,
R.drawable.car6,
R.drawable.car7,
R.drawable.car8
};
public GalleryImageAdapter(Context context)
{
mContext = context;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
// Override this method according to your need
public View getView(int index, View view, ViewGroup viewGroup)
{
// TODO Auto-generated method stub
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[index]);
i.setLayoutParams(new Gallery.LayoutParams(200, 200));
i.setScaleType(ImageView.ScaleType.FIT_XY);
return i;
}
}
}
and that is my Layout for that fragment
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="{relativePackage}.${activityClass}"
android:orientation="vertical" >
<Gallery
android:id="#+id/gallery1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/image1"
android:layout_width="215dp"
android:layout_height="315dp"
android:layout_gravity="center_horizontal"
android:background="#cfcfcf"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:src="#drawable/car1"
android:contentDescription="#null" />
</LinearLayout>
Problem with your Getview mathod
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
imageView = new ImageView(this.context);
imageView.setPadding(3, 3, 3, 3);
convertView = imageView;
holder.imageView = imageView;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.imageView.setImageDrawable(plotsImages.get(position));
holder.imageView.setScaleType(ImageView.ScaleType.FIT_XY);
holder.imageView.setLayoutParams(new Gallery.LayoutParams(150, 90));
return imageView;
}
private static class ViewHolder {
ImageView imageView;
}
I'm struggling with assigning my listview row more than one textview.
I want my row to have one textview for a person's name, one for address and one for age - but I'm not succeeding in doing so.
If someone could provide me with a simple example, that would be great.
Thanks!
Here's my custom ArrayAdapter
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater = null;
private ArrayList<Invoice> peopleList;
private final class ViewHolder {
TextView kidLabel;
TextView restLabel;
TextView fristLabel;
TextView amountLabel;
}
private ViewHolder mHolder = null;
public MyAdapter(Context context) {
Context mContext = context;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return peopleList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
mHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
convertView.setTag(mHolder);
} else {
mHolder = (ViewHolder) convertView.getTag();
}
mHolder.kidLabel = (TextView) convertView.findViewById(R.id.kidLabel);
mHolder.kidLabel.setText(peopleList.get(position).getKID());
mHolder.fristLabel = (TextView) convertView
.findViewById(R.id.fristLabel);
mHolder.fristLabel.setText(peopleList.get(position).getDueDate());
mHolder.restLabel = (TextView) convertView.findViewById(R.id.restLabel);
mHolder.restLabel.setText(peopleList.get(position).getDueAmount());
mHolder.amountLabel = (TextView) convertView
.findViewById(R.id.amountLabel);
mHolder.amountLabel.setText(peopleList.get(position).getDueAmount());
return convertView;
}
}
And Here's my custom row xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="fill_parent"
android:layout_height="45dip"
android:src="#drawable/cellback" android:scaleType="fitXY"/>
<TextView
android:id="#+id/kidLabel"
android:layout_width="160dip"
android:layout_height="25dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="13dip" android:textColor="#333"/>
<TextView
android:id="#+id/fristLabel"
android:layout_width="160dip"
android:layout_height="20dip"
android:layout_marginTop="25dip"
android:textSize="11dip" android:textColor="#999"/>
<TextView
android:id="#+id/amountLabel"
android:layout_width="160dip"
android:layout_height="25dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="13dip" android:layout_marginLeft="160dip" android:gravity="right" android:textColor="#333"/>
<TextView
android:id="#+id/restLabel"
android:layout_width="160dip"
android:layout_height="20dip"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="11dip" android:layout_marginLeft="160dip" android:layout_marginTop="25dip" android:gravity="right" android:textColor="#999"/>
</RelativeLayout>
First,you should create a xml to describe what your list cell likes,called cell.xml,for example:
<?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="wrap_content"
android:orientation="vertical" android:background="#color/spink">
<TextView
android:id="#+id/name_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/address_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Second,create a adapter.It helps your listview to show data:
public class MyAdapter extends BaseAdapter {
private LayoutInflater mInflater = null;
private ArrayList<People> peopleList;
private final class ViewHolder {
TextView nameTextView;
TextView addressTextView;
}
private ViewHolder mHolder = null;
public MyAdapter(Context context) {
mContext = context;
mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return peopleList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
mHolder = new ViewHolder();
convertView = mInflater.inflate(R.layout.cell, null);
convertView.setTag(mHolder);
} else {
mHolder = (ViewHolder)convertView.getTag();
}
mHolder.nameTextView (TextView)convertView.findViewById(R.id.name_textView);
mHolder.nameTextView.setText(peopleList.get(position).getName());
mHolder.addressTextView = (TextView)convertView.findViewById(R.id.address_textView);
mHolder.addressTextView.setText(peopleList.get(position).getAddress());
return convertView;
}
}
Finally,when you want to show the data,do this in your activity:
listView.setAdapter(new MyAdapter());
hope it helps you.
You need to create a custom listview layout and a custom array adapter (I have also created a custom class to work with the layout).
An example of this is:
Custom class that works with the custom listview layout:
package id10778734.sceresini.week4.exercise3.views;
import id10778734.sceresini.week4.exercise3.R;
import id10778734.sceresini.week4.exercise3.Constants;
import id10778734.sceresini.week4.exercise3.tasks.Task;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class TaskListItem extends LinearLayout {
private Task mTask;
private ImageView mEmailImageView;
private ImageView mPriorityImageView;
private TextView mTaskNameTextView;
private TextView mTaskResponsibleTextView;
private ImageView mDeleteImageView;
public TaskListItem (Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void onFinishInflate() {
super.onFinishInflate();
mEmailImageView = (ImageView) findViewById(R.id.list_row_layout_email_button);
mPriorityImageView = (ImageView) findViewById(R.id.list_row_layout_priority_icon);
mTaskNameTextView = (TextView) findViewById(R.id.list_row_layout_task_name);
mTaskResponsibleTextView = (TextView) findViewById(R.id.list_row_layout_responsible);
mDeleteImageView = (ImageView) findViewById(R.id.list_row_layout_delete_button);
}
public void setTask (Task task) {
mTask = task;
mEmailImageView.setTag(task);
switch (task.getPriority()) {
case Constants.LOW:
mPriorityImageView.setImageResource(R.drawable.low);
break;
case Constants.MEDIUM:
mPriorityImageView.setImageResource(R.drawable.medium);
break;
case Constants.HIGH:
mPriorityImageView.setImageResource(R.drawable.high);
break;
}
mTaskNameTextView.setText(task.getName());
mTaskResponsibleTextView.setText(task.getResponsible());
mDeleteImageView.setTag(task);
}
public Task getTask () {
return mTask;
}
public ImageView getDeleteImageView () {
return mDeleteImageView;
}
public ImageView getEmailImageView () {
return mEmailImageView;
}
}
the custom layout xml file:
<?xml version="1.0" encoding="UTF-8"?>
<id10778734.sceresini.week4.exercise3.views.TaskListItem
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/list_row_layout_email_button"
android:layout_width="36dip"
android:layout_height="36dip"
android:layout_gravity="center_vertical"
android:layout_marginLeft="4dip"
android:layout_marginRight="5dip"
android:contentDescription="#string/list_row_email_icon_description"
android:src="#android:drawable/ic_dialog_email" />
<ImageView
android:id="#+id/list_row_layout_priority_icon"
android:layout_width="24dip"
android:layout_height="24dip"
android:layout_gravity="center_vertical"
android:layout_marginLeft="4dip"
android:layout_marginRight="10dip"
android:contentDescription="#string/view_task_priority_icon_description" />
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >
<TextView
android:id="#+id/list_row_layout_task_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/list_row_layout_responsible"
android:paddingRight="5dip"
android:textAppearance="#style/list_row_task_name" />
<TextView
android:id="#id/list_row_layout_responsible"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/list_row_layout_delete_button"
android:maxWidth="100dip"
android:textAppearance="#style/list_row_task_responsible" />
<ImageView
android:id="#id/list_row_layout_delete_button"
android:layout_width="36dip"
android:layout_height="36dip"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginLeft="5dip"
android:layout_marginRight="5dip"
android:contentDescription="#string/delete_task_icon_description"
android:src="#drawable/task_delete" />
</RelativeLayout>
</id10778734.sceresini.week4.exercise3.views.TaskListItem>
And the custom array adapter:
package id10778734.sceresini.week4.exercise3;
import id10778734.sceresini.week4.exercise3.R;
import id10778734.sceresini.week4.exercise3.tasks.Task;
import id10778734.sceresini.week4.exercise3.views.TaskListItem;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
public class TaskListAdapter extends BaseAdapter
{
private ArrayList<Task> mTasks;
private Context mContext;
private AlertDialog unsavedChangesDialog;
private TaskManagerApplication mApp;
public TaskListAdapter(Context context, ArrayList<Task> tasks) {
super();
mApp = (TaskManagerApplication) context.getApplicationContext();
mContext = context;
mTasks = tasks;
}
#Override
public int getCount()
{
return mTasks.size();
}
#Override
public Task getItem(int position)
{
return (null == mTasks) ? null : mTasks.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
TaskListItem tli;
if (null == convertView)
{
tli = (TaskListItem) View.inflate(mContext, R.layout.list_row_layout, null);
} else
{
tli = (TaskListItem) convertView;
}
tli.setTask(mTasks.get(position));
tli.getEmailImageView().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
emailTask(v);
}
});
tli.getDeleteImageView().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
deleteTask(v);
}
});
return tli;
}
/**
* deleteTask() prompts the user with an alert dialog and presents them with
* the option to continue with the delete request or to cancel the request.
* Upon confirmation, the selected Task object which is retrieved from the
* deleteTaskIcon tag, will be removed from the list of currentTasks.
*
* #param v
*/
protected void deleteTask(View v)
{
final Task t = (Task) v.getTag();
String alertMessage = String.format(mContext.getString(R.string.delete_task_message), t.getName());
unsavedChangesDialog = new AlertDialog.Builder(mContext).setTitle(R.string.delete_task_title).setMessage(alertMessage)
// Delete the task and refresh the adapter.
.setPositiveButton(R.string.delete_task_delete, new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1)
{
// Remove task from array list
mTasks.remove(t);
// Remove task from Database
mApp.deleteTask(t);
// Display toast message stating the task was deleted
mApp.displayToast(Constants.TASK_DELETED);
// Update listView with modified adapter
forceReload();
}
})
// Cancel the delete request and do nothing.
.setNegativeButton(R.string.delete_task_cancel, new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1)
{
unsavedChangesDialog.cancel();
}
}).create();
unsavedChangesDialog.show();
}
/**
* emailTask() populates the selected task into an intent which allows the
* user to select a client to send the task. This is formatted for email
* clients.
*
* #param v
*/
protected void emailTask(View v)
{
// Retrieve the task that is allocated to this RowView
final Task t = (Task) v.getTag();
// Instantiate the intent that will be used to call the email client
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
// Variables/Arrays to hold email attributes
String[] emailRecipients = { mContext.getString(R.string.email_task_to_email) };
String emailType = mContext.getString(R.string.email_task_type);
String emailTitle = mContext.getString(R.string.email_task_title);
String emailSubject = String.format(mContext.getString(R.string.email_task_subject), t.getName());
String emailMessage = String.format(mContext.getString(R.string.email_task_message), t.getResponsible(), t.getName(), mContext.getString(t.getPriorityStringId()));
// Add the email attributes to the intent
emailIntent.setType(emailType);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, emailRecipients);
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, emailSubject);
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, emailMessage);
// Start intent
mContext.startActivity(Intent.createChooser(emailIntent, emailTitle));
}
/**
* Refreshes the ListView with the modified dataset.
*/
public void forceReload()
{
notifyDataSetChanged();
}
}