I want to short my code length by using array.If I have 100 button or image view I have to write for 100 . I want to get value from assets folder and pass it in to array . how to use
String[] colorNames = getResources().getStringArray(R.array.colorList);
String[] animalNames = getResources().getStringArray(R.array.animalList);
Current working code :
public class Main extends Activity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag);
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
image = (ImageView) findViewById(R.id.image);
Button btn1,btn2;
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
if(key.equals("animalIntent") )
{
btn1.setText("cat");
btn2.setText("dog");
// same for 100 button ............. here i want to short my code
} else {
btn1.setText("red");
btn2.setText("blue");
}
}
public void btn1(View view) {
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
if(key.equals("animalIntent") )
{
image.setBackgroundResource(R.drawable.cat);
// same for 100 image view ............. here i want to short my code
} else {
image.setBackgroundResource(R.drawable.red);
}
}
public void btn2(View view) {
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
if(key.equals("animalIntent") )
{
image.setBackgroundResource(R.drawable.dog);
} else {
image.setBackgroundResource(R.drawable.blue);
}
}
To do that you should use GridView,it would be best option. try the below sample code.
Step-1 add the gridview in your drag.xml
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/edt"
android:numColumns="2"
android:stretchMode="columnWidth" >
</GridView>
Step-2 Declare the variables and get the grid view reference.
GridView gridview;
Integer[] drawableIds = { R.drawable.poster1, R.drawable.poster2, R.drawable.poster3, R.drawable.poster4,
R.drawable.poster5 };
String[] colorNames = { "poster one", "poster two", "poster three", "poster four", "poster five" };
//In OnCreate() method add
gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new CustomGridAdapter(this, drawableIds, colorNames));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(Main.this, "" + position, Toast.LENGTH_LONG).show();
}
});
Step-3 create a class for grid adapter CustomGridAdapter.class
public class CustomGridAdapter extends BaseAdapter {
private Context context;
private Integer[] drawableitems;
private String[] drawablelabel;
public CustomGridAdapter(Context context, Integer[] drawableitems, String[] drawablelabel) {
this.context = context;
this.drawablelabel = drawablelabel;
this.drawableitems = drawableitems;
}
#Override
public int getCount() {
return drawableitems.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
RecordHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new RecordHolder();
convertView = inflater.inflate(R.layout.grid_item, null);
holder.txtTitle = (TextView) convertView.findViewById(R.id.grid_item_label);
holder.imageItem = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
} else {
holder = (RecordHolder) convertView.getTag();
}
holder.txtTitle.setText(drawablelabel[position]);
holder.imageItem.setImageResource(drawableitems[position]);
return convertView;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
Add custom view for grid grid_item.xml in layout folder.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center" >
</ImageView>
<TextView
android:id="#+id/grid_item_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textSize="18sp"
android:textStyle="bold" >
</TextView>
</LinearLayout>
Hope it will help you.
Related
I have a custom Listview where it contains image & text and implemented the OnItemClickListener for list which should work only for image not for text. OnItemClick is working fine for image but there is a Fatal Exception when i click on text. Additionally image will be visible in list if it exists else it will be hide.
Tried with android:focusable="false", android:clickable="false" but still i am getting the below exception
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable.getBitmap()' on a null object reference
OnItemClick:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ImageView imageView1 = (ImageView) view.findViewById(R.id.imageList);
final GlideBitmapDrawable bitmapDrawable = (GlideBitmapDrawable) imageView1.getDrawable();
final Bitmap yourBitmap = bitmapDrawable.getBitmap();
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourBitmap);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
How can i implement click only on image?
In your custom layout xml, set
android:descendantFocusability="blocksDescendants"
to your root layout.
Edit
Check my Custom ListView.
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:gravity="center"
android:descendantFocusability="blocksDescendants"
android:layout_height="60dp">
<ImageView
android:id="#+id/m_imageview"
android:layout_width="0dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"
android:layout_height="50dp" />
<TextView
android:id="#+id/m_textview"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="50dp"
android:gravity="center|center"
android:textColor="#ffffff"
android:text="hello"/>
<Button
android:id="#+id/m_buttonview"
android:layout_width="0dp"
android:layout_weight="2"
android:text="OK"
android:layout_height="50dp" />
</LinearLayout>
activity_main.xml
<RelativeLayout 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" >
<ListView
android:id="#+id/lv_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:dividerHeight="2dp"
android:divider="#ffffff"
tools:context=".MainActivity" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView m_pic;
TextView m_title;
Button m_btn;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.m_title = (TextView) convertView.findViewById(R.id.m_textview);
holder.m_btn = (Button)convertView.findViewById(R.id.m_buttonview);
holder.m_pic = (ImageView) convertView.findViewById(R.id.m_imageview);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.m_title.setText(rowItem.getTxt());
holder.m_pic.setImageResource(rowItem.getImage());
holder.m_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position + " clicked" , Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
RowItem.java
public class RowItem {
private int image;
private String txt;
public RowItem(int imageview , String textview)
{
this.image = imageview;
this.txt = textview;
}
public int getImage() {
return image;
}
public String getTxt() {
return txt;
}
public void setImage(int image) {
this.image = image;
}
public void setTxt(String txt) {
this.txt = txt;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
String m_txt[] = {"one" , "two" , "three" , "four", "five"};
int m_img [] = {R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher};
ListView m_list;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_list = (ListView)findViewById(R.id.lv_items);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < m_txt.length; i++) {
RowItem item = new RowItem(m_img[i],m_txt[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.listitem, rowItems);
m_list.setAdapter(adapter);
m_list.setOnItemClickListener(MainActivity.this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position) + ": " + rowItems.get(position).getTxt(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
This should helps you.
Happy coding.!!!
use a recyclerview.
a recylerview handles every list item as a view, it can hold clicklisteners for every view it holds and that view can hold clicklisteners for every view its holding.
I am new to android and i am working on listview. I am trying to show data using listview in xml and adapter in class file. I am working on following 3 files.
First file: activity_main.xml
<RelativeLayout 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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.listpractice.MainActivity" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
></ListView>
</RelativeLayout>
Second file: row1.xml
<?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" >
<ImageView
android:id="#+id/icon"
android:contentDescription="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/firstTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:textSize="30sp"
android:text="#string/hello_world"
/>
<TextView
android:id="#+id/secondTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:layout_below="#id/firstTextView"
android:textSize="13sp"
android:text="#string/hello_world"
/>
</RelativeLayout>
Third file: MainActivity.java
package com.listpractice;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class MainActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
My Problem : Now i want to show data of row1.xml but i don't have dynamic data. how can i show data using third(.class) file.
check out this link it will help http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
either you need to create adapter file
public class CustomBaseAdapter extends BaseAdapter{
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
//TextView txtDesc;
ImageView imgarrow;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
//holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.imgarrow=(ImageView)convertView.findViewById(R.id.arrow_icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
//holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.imgarrow.setImageResource(rowItem.getImg());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
MainActivity
public class MainActivity extends Activity implements OnItemClickListener{
public static final String[] titles = new String[] { "Krish",
"John Cena", "Kane","Roman Reigns"};
public static final Integer[] images = { R.drawable.fourth,R.drawable.second,R.drawable.first,R.drawable.third};
public static final Integer[] imagearow = {R.drawable.arrow,R.drawable.arrow,R.drawable.arrow,R.drawable.arrow };
ListView listView;
List<RowItem> rowItems;
private ImageView btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_home);
//list_travels=(ListView)findViewById(R.id.list_travels);
btn=(ImageView)findViewById(R.id.btnaddhotels);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Intent i=new Intent(HomeScreen.this,Registerhotel_resorts.class);
startActivity(i);
}
});
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i],imagearow[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list_hotels);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Intent i1=new Intent(HomeScreen.this,KrishnaParkResort.class);
startActivity(i1);
}
}
You should read this article on Building Layouts with an Adapter. It has some handy concepts which you will need to get your head around.
The fundamental concept is that you need to link your ListView to an Adapter which populates the rows and adds them to the ListView.
Looking at your row1.xml, it looks like you will need a collection of objects which contain;
An image for icon
String for firstTextView
String for secondTextView
You can build a little snippet to create an array of prepopulated objects for test purposes.
public class YourObject {
private Bitmap icon;
private String text1;
private String text2;
public YourObject(Bitmap icon, String text1, String text2) {
this.icon = icon;
this.text1 = text1;
this.text2 = text2;
}
// GETTERS AND SETTERS
}
Then create a collection of them
List<YourObject> data = new ArrayList<>();
for (int z = 0; z < 5; z++) {
YourObject yourObject = new YourObject(yourIcon, "Text1: " + z, "Text2: " + z);
data.add(yourObject);
}
Once you have this collection, you send it to a your Adapter constructor along with the reference to row1.xml, then follow the guide to populate the rows.
I am creating a android app in which i have list of channels(items) in a Custom GridView.
I have a favorite icon associated with each channel to add them in favorites list.
On click of this favorite icon the channel gets added to the Favorites List of channels.
When i use a android box remote i am not able to select the ImageView for favorite.
Instead the whole GridItem gets selected.
The single grid item is a LinearLayout which mainly has two ImageViews in it.
View code for a single grid-item of the gridview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="false"
android:clickable="true"
android:orientation="vertical" >
<ImageView
android:id="#+id/channelLogo"
android:layout_width="75dip"
android:layout_height="75dip"
android:layout_gravity="center"
android:focusable="false"
android:contentDescription="#string/app_name"/>
<TextView
android:id="#+id/channelName"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<TextView
android:id="#+id/channelStatus"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<ImageView
android:id="#+id/addToFavourite"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="false"
android:contentDescription="Add to favourites"
android:src="#drawable/addfavorites"
/>
</LinearLayout>
Code for my grid adapter where i handle the click of the ImageView (for adding a channel to favorite).
public class GridAdapter extends BaseAdapter {
private Context mContext;
private int resourceId;
private ArrayList<Item> itemList = new ArrayList<Item>();
private ArrayList<Category> categoryList = new ArrayList<Category>();
private int size;
private Integer[] mThumbIds;
private ViewGroup gridGroup;
private static final String PREFS_FAVOURITES = "favourites";
public GridAdapter(MainActivity c, int layoutResourceId, ArrayList<Item> data, int gsize) {
mContext = c;
resourceId = layoutResourceId;
itemList = data;
size = gsize;
mThumbIds = new Integer[gsize];
for(int i=0;i<mThumbIds.length;i++) {
mThumbIds[i] = R.drawable.ic_launcher;
}
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int arg0) {
return mThumbIds[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
class ViewHolder {
ImageView imageUrl;
TextView channelNameTxt;
TextView channelStatusTxt;
ImageView imgFavourite;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String contextClass = mContext.getClass().toString();
ViewHolder holder;
gridGroup = parent;
View grid = null;
if(convertView==null){
grid = new View(mContext);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
if (contextClass.contains("MainActivity") || contextClass.contains("FavoriteActivity")) {
grid = inflater.inflate(R.layout.grid_item, parent, false);
}
}else{
grid = (View)convertView;
return grid;
}
if (contextClass.contains("MainActivity")) {
if (position < itemList.size()) {
holder = new ViewHolder();
holder.channelNameTxt = (TextView) grid
.findViewById(R.id.channelName);
String channelName = itemList.get(position).getChannelName().replace("\n", "").replace("\r", "");
holder.channelNameTxt.setText(channelName);
holder.channelStatusTxt = (TextView) grid
.findViewById(R.id.channelStatus);
holder.channelStatusTxt
.setText(itemList.get(position).getStatus());
if(itemList.get(position).getStatus().equalsIgnoreCase("Online")) {
holder.channelStatusTxt.setTextColor(Color.GREEN);
} else if(itemList.get(position).getStatus().equalsIgnoreCase("Offline")) {
holder.channelStatusTxt.setTextColor(Color.RED);
}
holder.imageUrl = null;
try {
holder.imageUrl = (ImageView) grid
.findViewById(R.id.channelLogo);
holder.imageUrl.setTag(itemList.get(position).getImageUrl());
new DownloadImagesTask().execute(holder.imageUrl);
notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex.toString());
}
final Item info = itemList.get(position);
holder.imgFavourite = (ImageView)grid.findViewById(R.id.addToFavourite);
holder.imgFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//GridView gridview1;
if(mContext.getClass().toString().contains("MainActivity")) {
GridView gv = (GridView)gridGroup;
final int position = gv.getPositionForView((View) v.getParent());
Toast.makeText(mContext, "Position is :" + position, Toast.LENGTH_SHORT).show();
SharedPreferences settings = mContext.getSharedPreferences(PREFS_FAVOURITES, 0);
String favourites = settings.getString("favourites", "");
Item clicked_item = itemList.get(position);
String sep1 = "<sep1>";
String sep = "<sep>";
String favourite = clicked_item.getChannelUrl()+sep1+clicked_item.getChannelName()+sep1+clicked_item.getStatus()+sep1+"Favorite"+sep1+clicked_item.getImageUrl()+sep;
favourite = favourite.replace("\n", "").replace("\r", "");
if(!favourites.contains(favourite))
favourites = favourites+favourite;
SharedPreferences.Editor editor = settings.edit();
editor.putString("favourites", favourites);
editor.commit();
}
}
});
grid.setTag(holder);
}
}
return grid;
}
This works fine on a android phone.
I have custom ListView layout with a TextView and CheckBox. Everything works fine.
What I want is, when I click on the CheckBox or TextView (on the single View from ListView) both should behave like one object. (I can click on the CheckBox and it does not effect the TextView and TextView has no effect on CheckBox.) Code has no problem.
I have implemented all possible solutions but problem is still there. (One single click on every object of list should consider ONE COMPLETE CLICK for complete row.) I hope I explained very well.
MAIN ACTIVITY
package com.example.smsplanner;
public class SMSPlanner extends ListActivity {
ListView contactsListView;
private String TAG = "SMSPlanner"; CheckBox check;
int count;
List<ContactInfo> list = new ArrayList<ContactInfo>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ph = new String[3];
phType = new String[3];
LoadContactListFromPhone();
ContactsAdapter contactadAdapter = new ContactsAdapter(this, list);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setListAdapter(contactadAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id)
{
TextView tx =(TextView)v.findViewById(R.id.firstname);
TextView ph =(TextView)v.findViewById(R.id.phone);
Toast.makeText(this, tx.getText().toString() + " " + ph.getText().toString() + " " + Integer.toString(count), Toast.LENGTH_SHORT).show();
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
void LoadContactListFromPhone()
{
loadlistandreturns();
}
void call()
{
Toast toast = Toast.makeText(this, "Called...",Toast.LENGTH_LONG);
toast.show();
}
}
CUSTOM ADAPTER
public class ContactsAdapter extends ArrayAdapter<ContactInfo>
{
private final Activity context;
int resourceid;
List<ContactInfo> list = null;
public ContactsAdapter(Activity context, List<ContactInfo> list) {
super(context, R.layout.contactrow, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
}
LAYOUT
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<RadioGroup
android:id="#+id/rgStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="15"
android:orientation="vertical" >
<TextView
android:id="#+id/firstname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
<RadioGroup
android:id="#+id/rgStyle2"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="85"
android:orientation="vertical" >
<CheckBox
android:id="#+id/check"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:checked="false"
android:focusable="false"
android:focusableInTouchMode="false" >
</CheckBox>
</RadioGroup>
</LinearLayout>
1. Bydefault all the Rows of the ListView are enabled to listen to click....
You must implement onItemClickListener() for the ListView....
See this example:
http://www.mkyong.com/android/android-listview-example/
you can use a CheckedTextView, or you can create a Checkable Layout, like this one :
http://tokudu.com/2010/android-checkable-linear-layout/
i think you should make adapter as
public class ContactsAdapter extends BaseAdapter {
ArrayList<ContactInfo> mlist;
Context mcontext;
public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) {
mlist = mchtlist;
mcontext = context;
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public Object getItem(int postion) {
return mlist.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// to open the selected file in resp
// do your work here
}});
chkselected .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(context,// "checked is clicke="+pos, 12).show();
if (chkselected.isChecked())
{
// do your work here
} else {
// do your work here
}
}
});
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
}
I would like to implement that kind of gallery, but with the difference of getting images remotly.
The idea is to update the view only when an image has been downloaded.
=> I need to update the view only when going to onComplete.
Please find below my code :
public class displayAlbums extends Activity {
private static String URL_GRAPH_API = "https://graph.facebook.com/";
private static final String TAG = "displayAlbums";
private ArrayList<Bitmap> thumbnails = new ArrayList<Bitmap>();
private ArrayList<URI> thumbnails_uri = new ArrayList<URI>();
private ImageAdapter imageAdapter;
private int imageCounter = 0;
public boolean[] thumbnailsselection;
public Albums album;
private Context displayAlbums_context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galleryitem);
this.displayAlbums_context = this;
Log.d(TAG, "on create");
findViewById(R.id.itemCheckBox).setVisibility(View.GONE);
final GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
populateThumbnailsList();
processThumbnailsToDownload(thumbnails_uri, new PictureRequestListener() {
#Override
public void onComplete(Bitmap bitmap) {
if(imageAdapter == null) {
Log.d(TAG, "image adapter is null");
imageAdapter = new ImageAdapter(displayAlbums_context);
imagegrid.setAdapter(imageAdapter);
}
imagegrid.setId(imageCounter);
thumbnails.add(bitmap);
imageCounter++;
//imageAdapter.notifyDataSetChanged();
}
});
}
public void processThumbnailsToDownload(ArrayList<URI> thumbnails_uri, final FbRequestListener listener) {
Log.v(TAG,"processThumbnailsToDownload CALLED");
for(URI thumbnail_uri : thumbnails_uri ) {
new HttpConnection(ConnectionManager.getConnectionHandler(listener)).bitmap(thumbnail_uri);
}
}
public void populateThumbnailsList() {
URI uri = null;
for(final Albums album : LoadObjects.albums ) {
Bundle parameters = new Bundle();
parameters.putString("access_token", FbpicturesActivity.mFacebook.getAccessToken());
try {
uri = new URI(URL_GRAPH_API + album.getAid() + "/picture" + "?" +Util.encodeUrl(parameters) );
thumbnails_uri.add(uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context myContext;
public ImageAdapter(Context displayAlbums_context) {
Log.v(TAG,"IMAGE ADAPTER");
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
Log.d(TAG,"thumnail_uri size"+thumbnails_uri.size());
return thumbnails_uri.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
Log.v(TAG,"GET VIEW CALLED");
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
//holder.checkbox.setId(position);
//holder.imageview.setId(position);
Log.d(TAG,"thumnail size"+thumbnails.size());
Log.d(TAG,"thumnail position"+thumbnails.get(position));
holder.imageview.setImageBitmap(thumbnails.get(position));
holder.checkbox.setChecked(true);
holder.id = position;
return convertView;
}
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
galleryItem.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<Button android:id="#+id/selectBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Select" android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:minWidth="200px" />
<GridView android:id="#+id/PhoneImageGrid"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:numColumns="auto_fit" android:verticalSpacing="10dp"
android:horizontalSpacing="10dp" android:columnWidth="90dp"
android:stretchMode="columnWidth" android:gravity="center"
android:layout_above="#id/selectBtn" />
<ImageView android:id="#+id/thumbImage" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true" />
<CheckBox android:id="#+id/itemCheckBox" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
Please note i have added some Log.v to understand when getView is called :
=> http://pastebin.com/L9PYBYDa
questions :
1) Why getView is called 4 times ?
2) Why holder.imageview.setImageBitmap(thumbnails.get(position)) returns java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1 ?
3) Do you have any advice to implement my gallery with remote image ?
Thank you very much for your help
1) getView will be called at least (numberOfVisibleRows+ 1 or +2) times. I say at least because it can be called as many times as the system wants. There is no guarantee on that.
2)Because thumbnails is lower than size 2 or is null. You have to debug to see that
3) Check this out