Please forgive me for what may sound like a newbie question as I am just getting started
with Android.
What I am attempting to accomplish is creating a custom list Item layout that contains 2 textViews and a checkbox for selecting multiple items. The problem is the checkboxes are
"extra" selecting list items, (example) if I select #1 then #9 and # 18 selects as well.
as if the checkBox instances are recycling themselves or maybe sharing the same listener IDs
if that even makes sense. Ive narrowed my code to the primary components for simplicity. Any suggestions would be dearly appreciated.
package com.untame.mobile.app;
import java.text.ChoiceFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
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.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.untame.mobile.app.*;
public class TestList extends ListActivity {
ArrayList<Map<String, String>> artistList;
private static String TAG = "TESTLIST!";
ListView listv;
LayoutInflater mInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testlayout);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
artistList = new ArrayList<Map<String, String>>();
for(Integer loop = 0 ;loop < 21;loop++){
String loopI = loop.toString();
Map<String,String> hm = new HashMap<String, String>();
hm.put("artist", loopI);
hm.put("count", loopI);
artistList.add(hm);
}
// Loading artistNames in Background Thread
// new LoadArtistList().execute("extra_tracks");
listv = (ListView) getListView();
listv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// listv.setItemsCanFocus(false);
final class MyListAdapter extends BaseAdapter{
ArrayList<Integer> ids;
public MyListAdapter(Context context) {
ids = new ArrayList<Integer>();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.testlistitem1, null, false);
convertView.setClickable(true);
holder = new ViewHolder(getApplicationContext());
holder.choose = (CheckBox) convertView.findViewById(R.id.testcheckBox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return artistList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return artistList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
MyListAdapter adapter = new MyListAdapter(this);
setListAdapter(adapter);
}
}
ViewHolder.java
package com.untame.mobile.app;
import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class ViewHolder extends View {
public ViewHolder(Context context) {
super(context);
}
public CheckBox remove;
public CheckBox choose;
public TextView text2;
public TextView text1;
}
testlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
testitem.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" >
<com.untame.mobile.app.ArtistListCheckBox
android:id="#+id/testcheckBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choose"
/>
</LinearLayout>
Solved!!! It appears after much trial and error, that one must store the actual checkbox information (ie : checkbox.isChecked) into a seperate object that can be stored as a tag inside the current checkbox. This way when the view redraws the new items as you scroll the
list the newly created checkbox can recapture its last state from the object it was stored in.
In my case, I have a list of Music Artists in the list so I created an Artist.java class
to create Artist objects to store as checkbox tags.
Related
I'm using an AsyncTask to load images into my ListView. However when I run the app, the order of the images changes when I scroll. I suspect that the getView() method might be at fault. But I can't find a way to fix this.
Being relatively new to Android, I can't explore much options either.
Here is my code:
DisplayPlacements.java
package com.example.android.areainfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
public class DisplayPlacements extends AppCompatActivity {
ListView listView;
private String[] imageURLArray = new String[]{
"http://farm8.staticflickr.com/7315/9046944633_881f24c4fa_s.jpg",
"http://farm4.staticflickr.com/3777/9049174610_bf51be8a07_s.jpg",
"http://farm8.staticflickr.com/7324/9046946887_d96a28376c_s.jpg",
"http://farm3.staticflickr.com/2828/9046946983_923887b17d_s.jpg",
"http://farm4.staticflickr.com/3810/9046947167_3a51fffa0b_s.jpg",
"http://farm4.staticflickr.com/3773/9049175264_b0ea30fa75_s.jpg",
"http://farm4.staticflickr.com/3781/9046945893_f27db35c7e_s.jpg",
"http://farm6.staticflickr.com/5344/9049177018_4621cb63db_s.jpg",
"http://farm8.staticflickr.com/7307/9046947621_67e0394f7b_s.jpg",
"http://farm6.staticflickr.com/5457/9046948185_3be564ac10_s.jpg",
"http://farm4.staticflickr.com/3752/9046946459_a41fbfe614_s.jpg",
"http://farm8.staticflickr.com/7403/9046946715_85f13b91e5_s.jpg",
"http://farm8.staticflickr.com/7315/9046944633_881f24c4fa_s.jpg",
"http://farm4.staticflickr.com/3777/9049174610_bf51be8a07_s.jpg",
"http://farm8.staticflickr.com/7324/9046946887_d96a28376c_s.jpg",
"http://farm3.staticflickr.com/2828/9046946983_923887b17d_s.jpg",
"http://farm4.staticflickr.com/3810/9046947167_3a51fffa0b_s.jpg",
"http://farm4.staticflickr.com/3773/9049175264_b0ea30fa75_s.jpg",
"http://farm4.staticflickr.com/3781/9046945893_f27db35c7e_s.jpg",
"http://farm6.staticflickr.com/5344/9049177018_4621cb63db_s.jpg",
"http://farm8.staticflickr.com/7307/9046947621_67e0394f7b_s.jpg",
"http://farm6.staticflickr.com/5457/9046948185_3be564ac10_s.jpg",
"http://farm4.staticflickr.com/3752/9046946459_a41fbfe614_s.jpg",
"http://farm8.staticflickr.com/7403/9046946715_85f13b91e5_s.jpg"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_placements);
listView = (ListView) findViewById(R.id.listPlacements);
ImageAdapter imageAdapter = new ImageAdapter(this, R.layout.row, imageURLArray);
listView.setAdapter(imageAdapter);
}
}
activity_display_placements.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_display_placements"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.android.areainfo.DisplayPlacements">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listPlacements">
</ListView>
</LinearLayout>
row.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:layout_height="match_parent">
<ImageView
android:id="#+id/testImage"
android:layout_width="75dp"
android:layout_height="75dp"
android:scaleType="centerCrop" />
</LinearLayout>
ImageAdapter.java
package com.example.android.areainfo;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import java.io.IOException;
import java.net.URL;
/**
* Created by User on 30-Jan-17.
*/
public class ImageAdapter extends ArrayAdapter<String> {
private String[] imageURLArray;
private LayoutInflater inflater;
public ImageAdapter(Context context, int textViewResourceId,
String[] imageArray) {
super(context, textViewResourceId, imageArray);
// TODO Auto-generated constructor stub
inflater = ((Activity)context).getLayoutInflater();
imageURLArray = imageArray;
}
private static class ViewHolder {
String imageURL;
ImageView imageView;
Bitmap bitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder viewHolder = null;
if(convertView == null) {
convertView = inflater.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView)convertView.findViewById(R.id.testImage);
convertView.setTag(viewHolder);
}
viewHolder = (ViewHolder)convertView.getTag();
viewHolder.imageURL = imageURLArray[position];
new DownloadAsyncTask().execute(viewHolder);
return convertView;
}
private class DownloadAsyncTask extends AsyncTask<ViewHolder, Void, ViewHolder> {
#Override
protected ViewHolder doInBackground(ViewHolder... params) {
// TODO Auto-generated method stub
//load image directly
ViewHolder viewHolder = params[0];
try {
URL imageURL = new URL(viewHolder.imageURL);
viewHolder.bitmap = BitmapFactory.decodeStream(imageURL.openStream());
} catch (IOException e) {
// TODO: handle exception
Log.e("error", "Downloading Image Failed");
viewHolder.bitmap = null;
}
return viewHolder;
}
#Override
protected void onPostExecute(ViewHolder result) {
// TODO Auto-generated method stub
if (result.bitmap == null) {
// result.imageView.setImageResource(R.drawable.postthumb_loading);
} else {
result.imageView.setImageBitmap(result.bitmap);
}
}
}
}
Help appreciated.
Thanks!
You should use RecyclerView instead. It is not the main problem here but recyclerview is a more optimized way of populating lists.
You can find a good example here
and to load images use an image loading library like glide or Picasso
it is much easier to do things in this way.
you can find a good complete example here
I am having problem with changing color of Textview in custom Listview.
My xml file is column.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:layout_height="match_parent">
<TextView
android:id="#+id/cid"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:textSize="30dp"
android:visibility="gone"/>
<TextView
android:id="#+id/cname"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="25dp"
android:textColor="#f60505" />
<TextView
android:id="#+id/amt"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15dp"
android:textColor="#2ec31d"
android:textAlignment="center" />
</LinearLayout>
and ListViewAdapter.java goes like this
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by XYZ on 06-05-2016.
*/
public class ListViewAdapter extends BaseAdapter {
public ArrayList<HashMap<String,String>> list;
Activity activity;
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
public ListViewAdapter(Activity activity,ArrayList<HashMap<String,String>>list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = activity.getLayoutInflater();
ViewHolder holder;
if (convertView == null){
convertView = inflater.inflate(R.layout.colunm_row,null);
holder = new ViewHolder();
holder.textFirst=(TextView)convertView.findViewById(R.id.cid);
holder.textSecond=(TextView)convertView.findViewById(R.id.cname);
holder.textThird=(TextView)convertView.findViewById(R.id.amt);
txtFirst = (TextView) convertView.findViewById(R.id.cid);
txtSecond = (TextView)convertView.findViewById(R.id.cname);
txtThird = (TextView) convertView.findViewById(R.id.amt);
convertView.setTag(holder);
}else {
holder =(ViewHolder)convertView.getTag();
holder.textFirst.setText("");
holder.textSecond.setText("");
holder.textThird.setText("");
}
HashMap<String,String> map= list.get(position);
/* txtFirst.setText(map.get(FIRST_COLUMN));
txtSecond.setText(map.get(SECOND_COLUMN));
txtThird.setText(map.get(THIRD_COLUMN));*/
holder.textFirst.setText(map.get(FIRST_COLUMN));
holder.textSecond.setText(map.get(SECOND_COLUMN));
holder.textThird.setText(map.get(THIRD_COLUMN));
return convertView;
}
static class ViewHolder{
TextView textFirst;
TextView textSecond;
TextView textThird;
}
}
DisplayActivity :
package accounts.com.accountbook;
import static accounts.com.accountbook.Constants.FIRST_COLUMN;
import static accounts.com.accountbook.Constants.SECOND_COLUMN;
import static accounts.com.accountbook.Constants.THIRD_COLUMN;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class AccDisplay extends AppCompatActivity {
private ArrayList<HashMap<String,String>> arrayList;
Cursor c;
SQLiteDatabase db;
DBHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_acc_display);
ListView listView = (ListView)findViewById(R.id.AcclistView);
arrayList = new ArrayList<HashMap<String, String>>();
db = openOrCreateDatabase("AccountsDB", Context.MODE_PRIVATE,null);
c=db.rawQuery("select c.c_id ,c.c_name, ((select CASE WHEN (sum(cr.amount)) IS Null THEN 0 ELSE sum(cr.amount) END from credit_master cr where c.c_id=cr.c_id) ) - ((select CASE WHEN (sum(d.amount)) IS NULL THEN 0 ELSE sum(d.amount) END from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c ORDER BY c.c_name ASC",null);
//c=db.rawQuery("select c.c_id ,c.c_name, ((select sum(cr.amount) from credit_master cr where c.c_id=cr.c_id) ) - ((select sum(d.amount) from debit_master d where c.c_id = d.c_id ) ) as Tot from customers c",null);
try {
if (c!=null){
if(c.moveToFirst()){
Map<String,String> tem = new HashMap<String ,String>();
tem.clear();
arrayList.clear();
listView.setAdapter(null);
int cnt = c.getCount();
Toast.makeText(getApplicationContext(),""+cnt,Toast.LENGTH_SHORT).show();
do {
tem = new HashMap<String,String>();
tem.clear();
tem.put(FIRST_COLUMN, c.getString(0));
tem.put(SECOND_COLUMN,c.getString(1));
tem.put(THIRD_COLUMN,c.getString(2));
arrayList.add((HashMap<String, String>) tem);
}while (c.moveToNext());
}
}
}catch (Exception e){
Toast.makeText(getApplicationContext(),"Error"+e,Toast.LENGTH_LONG).show();
}
ListViewAdapter adapter = new ListViewAdapter(this,arrayList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView tv = (TextView) (view.findViewById(R.id.cid));
int str = Integer.parseInt(tv.getText().toString());
Toast.makeText(AccDisplay.this,"Clicked"+str,Toast.LENGTH_LONG).show();
Intent intent = new Intent(AccDisplay.this,Details.class);
intent.putExtra("name",str);
startActivity(intent);
}
});
}
protected void onRestart(){
super.onRestart();
Intent inte = getIntent();
finish();
startActivity(inte);
}
}
I am using same layout file for three different activities.
I want to display different color of each TextView in Different Activity.
I have tried this but didn't work
LayoutInflator inflator = (LayoutInflator)getSystemService(Context.LAYOUT_INFLATOR_SERVICE);
View vi = inflator.inflate(R.layout.column,null);
TextView tv = (TextView) vi.findViewById(R.id.amt);
tv.setTextColor(Color.BLACK);
I can change color of TextView in OnItemClickListener but i want to display color while displaying data.
I am having Debit/Credit activity which uses same Adapter class and column.xml layout for displaying data in listview.
I want to display TextView1 in black color font and TextView2 in Green color with big font size in Activity 1. and different color in different activity.
You can pass different flags in adapter constructor to adapter for identifying activity if same adapter you are using for other activities, and can put conditions according to the flag set colors to the TextView in adapter programmatically. textView.setTextColor(put_your_color);
I meet a problem developing an android project.
Using adapter, I place many items in a ListView, and there is an ImageButton in each item. Now I want to set a click listener for these ImageButtons. What should I do?
This achieves your desired result. Its functionality is the button itself has a click response different from the container, which also has a response.
MainActivity.java
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
ListView lv = (ListView) findViewById( R.id.list );
lv.setOnItemClickListener(
new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0,
android.view.View arg1, int arg2, long arg3) {
Toast.makeText( MainActivity.this,
"List item clicked",
Toast.LENGTH_SHORT).show();
}
});
ArrayList<String> items = new ArrayList<String>();
items.add( "item1");
items.add( "item2");
items.add( "item3");
ListAdapter adapter = new ListAdapter( this, items);
lv.setAdapter( adapter );
}
}
ListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.BaseAdapter;
import android.widget.Toast;
import java.util.List;
public class ListAdapter extends BaseAdapter {
public ListAdapter(Context context,
List<String> items ) {
inflater = LayoutInflater.from( context );
this.context = context;
this.items = items;
}
public int getCount() {
return items.size();
}
public Object getItem(int position) {
return items.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
String item = items.get(position);
View v = null;
if( convertView != null )
v = convertView;
else
v = inflater.inflate( R.layout.item, parent, false);
TextView itemTV = (TextView)v.findViewById( R.id.item);
itemTV.setText( item );
ImageButton button =
(ImageButton)v.findViewById( R.id.button);
button.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
Toast.makeText( context,
"ImageButton clicked",
Toast.LENGTH_SHORT).show();
}
});
return v;
}
private Context context;
private List<String> items;
private LayoutInflater inflater;
}
item.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="wrap_content"
android:descendantFocusability="blocksDescendants" >
<TextView
android:id="#+id/item"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textSize="28sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="#android:color/transparent"
android:src="#drawable/emo_im_cool" />
</RelativeLayout>
list.xml
<?xml version="1.0" encoding="utf-8" ?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/list" />
Try it out and hopefully you can see what's going on to learn what you need
I am working with custom listView in android. but I cant able click the item in listview.
my code is
Adapter code(BankArrayListAdapter.java)
package com.example.customlist;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.method.LinkMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class BankArrayListAdapter extends ArrayAdapter<Bank>{
private int resource;
private LayoutInflater inflater;
private Context ctx;
public BankArrayListAdapter(Context context, int resourceId, List<com.example.customlist.Bank> ls)
{
super(context, resourceId, ls);
resource = resourceId;
inflater = LayoutInflater.from( context );
ctx=context;
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
/* create a new view of my layout and inflate it in the row */
convertView = inflater.inflate( resource, null );
/* Extract the city's object to show */
Bank bank = (Bank) getItem(position);
/* Take the TextView from layout and set the city's name */
TextView txtName = (TextView) convertView.findViewById(R.id.textView1);
txtName.setText(bank.getName());
/* Take the TextView from layout and set the city's wiki link */
TextView txtWiki = (TextView) convertView.findViewById(R.id.textView2);
txtWiki.setTextSize(13);
txtWiki.setMovementMethod(LinkMovementMethod.getInstance());
txtWiki.setText(bank.getUrl());
/* Take the ImageView from layout and set the city's image */
ImageView imageCity = (ImageView) convertView.findViewById(R.id.imageView1);
String uri = "drawable/" + bank.getLogo();
int imageResource = ctx.getResources().getIdentifier(uri, null, ctx.getPackageName());
Drawable image = ctx.getResources().getDrawable(imageResource);
imageCity.setImageDrawable(image);
return convertView;
}
}
MainActivity.java
package com.example.customlist;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity {
ListView lv;
List<Bank> ls;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv= (ListView) findViewById(R.id.listView1);
ls= new ArrayList<Bank>();
ls.add(new Bank("sbi","State Bank Of India","http://www.sbi.com"));
ls.add(new Bank("iob", "India Overseas Bank","http://www.iob.com"));
ls.add(new Bank("icici","ICICI","http://www.icici.com"));
//lv.setAdapter( new BankArraylistA);
lv.setAdapter( new BankArrayListAdapter(Main.this, R.layout.banklist, ls ) );
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Toast.makeText(Main.this,"Your Listener Works!",Toast.LENGTH_SHORT).show();
// System.out.println("Name: "+ls.get(position).getName());
// String s =(String) ((TextView) v.findViewById(R.id.From)).getText();
// Toast.makeText(Messages.this, s, Toast.LENGTH_LONG).show();
}
});
System.out.println(ls);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
activity_main.xml file goes like this
<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"
android:descendantFocusability="blocksDescendants"
tools:context=".Main" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
Thanks in advance
Regards,
Sathish
I had the same problem and I solved by add this code to getView() method in my custom adapter class, yours BankArrayListAdapter.java
convertView.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Log.v("LV_ITEM", "Position of item is " + position);
}
});
last days I was browsing one of the apps in Android
and I found out an amazing list.
I Found that Custom ListView Interesting.
When we click on the Text it shows me some Activity and when we click on the Arrow on Right it shows me a dialog.
I want to learn this. Can anybody go through some Tutorials where this Custom List is explained. Please Friends. guide me.. Thanks alot
Hi Below Is Custom ListView Example
First Create test.Java File below is code
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class test extends Activity {
/** Called when the activity is first created. */
ArrayList<String> arrayString = new ArrayList<String>();
test_adapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrayString.add("TextView1");
arrayString.add("TextView2");
arrayString.add("TextView3");
arrayString.add("TextView4");
arrayString.add("TextView5");
ListView list = (ListView) findViewById(R.id.LIST);
adapter = new test_adapter(this, arrayString);
list.setAdapter(adapter);
}
}
Also Used below Class file test_adapter.java
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class test_adapter extends BaseAdapter {
private Activity activity;
ArrayList<String> data = new ArrayList<String>();
private static LayoutInflater inflater = null;
public test_adapter(Activity a, ArrayList<String> d) {
activity = a;
data = d;
inflater = LayoutInflater.from(activity);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView txt1;
public Button btn1;
public RelativeLayout rel1;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.txt1 = (TextView) vi.findViewById(R.id.txt1);
holder.btn1 = (Button) vi.findViewById(R.id.btn1);
holder.rel1 = (RelativeLayout) vi.findViewById(R.id.rel1);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.txt1.setText(data.get(position));
holder.rel1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast
.makeText(activity, "Click On TextView",
Toast.LENGTH_LONG).show();
}
});
holder.btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "Click On Button", Toast.LENGTH_LONG)
.show();
}
});
return vi;
}
}
Used below layout files main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ListView android:layout_width="fill_parent" android:id="#+id/LIST"
android:layout_height="fill_parent" />
</LinearLayout>
Used listview.xml file
<?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="wrap_content"
android:orientation="horizontal">
<RelativeLayout android:id="#+id/rel1" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/txt1"
android:text="Test Description"></TextView>
</RelativeLayout>
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:id="#+id/btn1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="ClickHere"
android:layout_alignParentRight="true"></Button>
</RelativeLayout>
</LinearLayout>
Used Above Code and you will get display toast message and you can changed as per you requirement.