I have a custom list adapter that populates a listview.
I am trying to get each item in the listview to be clickable. When clicked, I want the app to load another activity and populate it with the proper data. The data comes from a java list of listing.java.
I can't seem to get it to respond to clicks, here is what I've tried so far:
//this is in the onCreate method
final ListView listview = (ListView) findViewById(R.id.listview);
listingsAdapter = new ListingsAdapter(this, mylistings);
listview.setAdapter(listingsAdapter);
here is my first attempt (this was just to get toast working, but it didn't work)
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, final View view,int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG).show();
};
});
I have also tried this:
listview.setOnItemClickListener( new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Intent i = new Intent(HomeScreenActivity.this, DetailedViewActivity.class);
startActivity(i);
};
});
Help would be appreciated. Let me know if I should post my adapter as well!
Here is the adaptor:
public class ListingsAdapter extends BaseAdapter{
List<Listing> listings;
Context context;
LayoutInflater inflater;
public ListingsAdapter(Context context, List<Listing> listings){
this.context = context;
this.listings = listings;
inflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public boolean isEnabled(int position)
{
return true;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View _localView = convertView;
if (_localView == null){
_localView = inflater.inflate(R.layout.main_cell, parent, false);
}
TextView text1 = (TextView) _localView.findViewById(R.id.firstline);
TextView text2 = (TextView) _localView.findViewById(R.id.secondLine);;
Listing listing = listings.get(position);
text1.setText(listing.getTitle());
text2.setText(listing.getAddress());
return _localView;
}
#Override
public int getCount(){
// TODO Auto-generated method stub
return listings.size();
}
#Override
public Object getItem(int arg0){
return listings.get(arg0);
}
#Override
public long getItemId(int arg0){
// TODO Auto-generated method stub
return arg0;
}
}
this is the main_cell.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_marginRight="6dip"
android:contentDescription="TODO"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/secondLine"
android:layout_width="fill_parent"
android:layout_height="26dip"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_toRightOf="#id/icon"
android:ellipsize="marquee"
android:singleLine="true"
android:text="Description"
android:textSize="12sp" />
<TextView
android:id="#+id/firstline"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#id/secondLine"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_alignWithParentIfMissing="true"
android:layout_toRightOf="#id/icon"
android:gravity="center_vertical"
android:text="Example application"
android:textSize="16sp"/>
</RelativeLayout>
Right, so I am recovering from a severe hangover and I just remembered that I promised to elaborate on the link I posted - disregard the link!
You should add the following piece of code to your ListingsAdapter:
#Override
public boolean isEnabled(int position)
{
return true;
}
And you should edit the RelativeLayout in your main_cell.xml from
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43"
android:longClickable="true">
to
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dp"
android:background="#CC7C43">
This works, I have tested it.
try to initialize local instance of View:
#Override
public View getView(int position, View convertView, ViewGroup parent){
View _localView = convertView;
if (_localView == null){
_localView = inflater.inflate(R.layout.main_cell, parent, false);
}
TextView text1 = (TextView) _localView.findViewById(R.id.firstline);
TextView text2 = (TextView) _localView.findViewById(R.id.secondLine);;
Listing listing = listings.get(position);
text1.setText(listing.getTitle());
text2.setText(listing.getAddress());
return _localView;
}
UPD:
Also modify other necessary methods in your adapter class, because you need to get id of an item clicked for using it in onItemClick method:
#Override
public Object getItem(int arg0){
// TODO Auto-generated method stub
listings.get(arg0);
}
#Override
public long getItemId(int arg0){
// TODO Auto-generated method stub
return arg0;
}
as an example. Hope this will help you.
Related
hi i want to put a cursor content in a list view is there any specific way to do it ?
i researched online nothing specific
i get this error when excuting
public class AfficherToousLesMembre extends AppCompatActivity {
String nom,prenom,email;
int numero;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_afficher_toous_les_membre);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
BaseDeDonee bdd = new BaseDeDonee(this);//database
Cursor c =bdd.GETallMem();//function returns all the data from table person
ArrayAdapter<String> mp = new ArrayAdapter<String>(this,R.layout.display_member_row);
c.moveToFirst();
listView=(ListView)findViewById(R.id.listView);
while(c.moveToNext()){
nom= c.getString(c.getColumnIndex("nom"));
prenom=c.getString(c.getColumnIndex("prenom"));
email=c.getString(c.getColumnIndex("profile"));
numero=c.getInt(c.getColumnIndex("numero_tel"));
String f=Integer.toBinaryString(numero);
mp.add(nom);
mp.add(prenom);
mp.add(email);
mp.add(f);
}
listView.setAdapter(mp);
}
}
and the layout is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:background="#76ba7e"
android:layout_height="75dp">
<TextView
android:layout_width="70dp"
android:layout_height="match_parent"
android:id="#+id/nom_id"
android:layout_alignParentLeft="true"
android:text="nom"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="80dp"
android:layout_height="match_parent"
android:id="#+id/prenom_id"
android:layout_toRightOf="#+id/nom_id"
android:text="Prenom"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="70dp"
android:layout_height="match_parent"
android:id="#+id/email_id"
android:layout_toRightOf="#+id/prenom_id"
android:text="Email"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
<TextView
android:layout_width="200dp"
android:layout_height="match_parent"
android:id="#+id/numero_tele_id"
android:layout_toRightOf="#+id/email_id"
android:text="Numero telephone"
android:gravity="center"
android:textAppearance="?android:textAppearanceLarge"
/>
please help i spend the hole day trayin to figure it out
Here your adapter need to change like this
ArrayAdapter(Context context, int resource, T[] objects).
this is the basic constructor for ArrayAdapter you can use this below way.
(1) If you use Default layout for single value in ListItem than make it like
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
where items is a array of object which you want to display in ListView
(2) If you want to display single item in your custom layout for ListItem than make it like
ArrayAdapter<String> itemsAdapter = new ArrayAdapter<String>(this,
R.layout.rowlayout, R.id.label, values);
where R.id.label is a resource in which you want to display values
(3) Make your own Adapter to display bulk data in your ListItem
for this refer http://www.vogella.com/tutorials/AndroidListView/article.html
public class CustomListAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomListAdapter (Context mContext, String[] NameList, int[] Images) {
// TODO Auto-generated constructor stub
result=NameList;
context=mContext;
imageId=Images;
inflater = ( LayoutInflater )context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.row_list_item, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
}
and used like this
ListView yourListView = (ListView) findViewById(R.id.itemListView);
CustomListAdapter customAdapter = new CustomListAdapter(this,String Array of NameList, int Array of Images);
yourListView.setAdapter(customAdapter);
Mainactivity.xml
<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:orientation="vertical"
tools:context=".ListActivity" >
<ListView
android:id="#+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
listview_detail.xml
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
MainActivity.Java
//getting all user data from database
UserMst sql_userMst = new UserMst(context);
sql_usermst.open();
Cursor cursor = sql_userMst.getAllUserData();
//binding cursor to listview
ListView listView = (ListView) findViewById(R.id.mobile_list);
listView.setAdapter(new TodoCursorAdapter(context,cursor));
public class TodoCursorAdapter extends CursorAdapter {
public TodoCursorAdapter(Context context, Cursor cursor) {
super(context, cursor);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.listview_detail, parent, false);
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Find fields to populate in inflated template
TextView label = (TextView) view.findViewById(R.id.label);
// Extract properties from cursor
String username= cursor.getString(cursor.getColumnIndexOrThrow("UserName"));
// Populate fields with extracted properties
label .setText(username);
}
}
use this url for reference listview with cursor
I have a list view from which the user must choose two teams by checking the boxes and then validate by pressing the OK button. The problem is I want to make it so that there can only be two checked boxes at any time
Example :
if the user picks team 1 and 2 then the boxes for 1 and 2 should be checked but if the user then picks team 3, 1 should un-check automatically.
I've already managed to isolate and store the position of the box that needs to be unchecked but I don't know what to do with it.
Thanks!!
heres the listView
<Button
android:id="#+id/btnConfirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok"
/>
<ListView
android:id="#+id/listEquipe"
android:layout_below="#+id/btnConfirm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
and the following 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="wrap_content"
android:orientation="horizontal"
>
<TextView
android:id="#+id/txtIdEquipe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"/>
<CheckedTextView
android:id="#+id/txtNomEquipe"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:checkMark="?android:attr/listChoiceIndicatorMultiple"
android:padding="5dp"
android:textSize="12pt"
android:textColor="#000000"
/>
</LinearLayout>
This is one way to achieve it (I used stupid data in the adapter):
public class MainActivity extends AppCompatActivity {
private List<Integer> selectedItems = new ArrayList<>();
private String[] teams = new String[]{ "Team A", "Team B", "Team C"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView lv = (ListView) findViewById(R.id.listEquipe);
final BaseAdapter adapter = new BaseAdapter() {
#Override
public int getCount() {
return teams.length;
}
#Override
public Object getItem(int position) {
return teams[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = getLayoutInflater().inflate(R.layout.item, null);
((TextView) view.findViewById(R.id.txtIdEquipe)).setText((String) getItem(position));
CheckedTextView ctv = (CheckedTextView) view.findViewById(R.id.txtNomEquipe);
ctv.setChecked(selectedItems.contains(position));
return view;
}
};
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(selectedItems.contains(position)) {
selectedItems.remove(position);
}
else {
selectedItems.add(position);
if(selectedItems.size() > 2) {
selectedItems.remove(0);
}
}
adapter.notifyDataSetChanged();
}
});
}
}
This is my code:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
View vie = (View)parent.getParent();
TextView tv = (TextView) vie.findViewById(R.id.tv_id);
String genus = (String) tv.getText();
Toast.makeText(getBaseContext(), genus+"--"+id, Toast.LENGTH_SHORT).show();
}
});
return adapter;
}
Every time it is returning the same value for every item. Here are my list items:
<?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="match_parent" >
<TextView
android:id="#+id/tv_country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="20dp"
android:textStyle="bold" />
<ImageView
android:id="#+id/iv_flag"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_below="#id/tv_country"
android:layout_centerVertical="true"
android:padding="5dp"
/>
<TextView
android:id="#+id/tv_country_details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iv_flag"
android:layout_below="#id/tv_country" />
<TextView
android:id="#+id/tv_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_country_details"
/>
</RelativeLayout>
Here is my view file.
<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_countries"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:context=".NearbyGymList" />
<Button android:id="#+id/btnNoResults"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/lv_countries"
android:text="No More Results"/>
</RelativeLayout>
How can fix this problem?
Remove this line:
View vie = (View)parent.getParent();
And change to use view from parameter, because it is the view of item which is clicked:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
//Remove this line: View vie = (View)parent.getParent();
//Use view because it is the view of item which is clicked.
TextView tv1 = (TextView) view.findViewById(R.id.tv_id);
//Add this
TextView tv2 = (TextView) view.findViewById(R.id.tv_country_details);
String genus = (String) tv1.getText().toString();
String genus2 = (String) tv2.getText().toString();
Toast.makeText(getBaseContext(),genus+"--"+id+" "+genus2 , Toast.LENGTH_SHORT).show();
}
});
return adapter;
}
You're not adding a reference to your others TextViews. Do it this way:
Remove this line
View vie = (View)parent.getParent();
so your code will become:
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
TextView tv1 = (TextView) view.findViewById(R.id.tv_id);
TextView tv2 = (TextView) view.findViewById(R.id.tv_country_details);
String genus = (String) tv1.getText().toString();
String genus2 = (String) tv2.getText().toString();
Toast.makeText(getBaseContext(),genus+"--"+id+" "+genus2 , Toast.LENGTH_SHORT).show();
}
});
return adapter;
}
To access the element in the dataset at position you can use
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Object object = parent.getItemAtPosition(position);
and cast it to the correct type.
In Adapter Class
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.yourlayout, parent, false);
TextView textView = (TextView) row.findViewById(R.id.textView);
textView .setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Do whatever you want
});
I'm trying to set my indicator to be next to the textview, but I just can't get the right code to do it.
XML:
<TextView
android:id="#+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textColor="#000000"
android:textSize="17dp" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="#+id/lblListHeader"
android:src="#drawable/custom_arrow" />
This is the only stack of code that I have found researching but I can't get it to work:
//inside getGropView method
View v;
if (convertView == null) {
v = newGroupView(isExpanded, parent);
} else {
v = convertView;
}
bindView(v, mGroupData.get(groupPosition), mGroupFrom, mGroupTo);
((ImageView) v.findViewById(R.id.videos_group_indicator))
.setImageResource(isExpanded?R.drawable.videos_chevron_expanded:R.drawable.videos_chevron_collapsed);
return v;
The main problem is that it "underlines" the newGroupView method etc. because I don't have such method and it is not mentioned how to create it in the example I was looking at.
Also, once I get the solution, could someone please try and explain this code to me? I have read it through a lot of time and I just can't get myself to understand it, I'm a beginner.
Here's an example of custom expandable list view:
What you want to see if you apply this code in your new project:
create this code into activity
public class ExpActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Находим наш list
ExpandableListView listView = (ExpandableListView)findViewById(R.id.exListView);
//Создаем набор данных для адаптера
ArrayList<ArrayList<String>> groups = new ArrayList<ArrayList<String>>();
ArrayList<String> children1 = new ArrayList<String>();
ArrayList<String> children2 = new ArrayList<String>();
children1.add("Child_1");
children1.add("Child_2");
groups.add(children1);
children2.add("Child_1");
children2.add("Child_2");
children2.add("Child_3");
groups.add(children2);
//Создаем адаптер и передаем context и список с данными
ExpListAdapter adapter = new ExpListAdapter(getApplicationContext(), groups);
listView.setAdapter(adapter);
}
}
add expandableListView into main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ExpandableListView
android:id="#+id/exListView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:indicatorLeft="250dp"
android:indicatorRight="300dp"
/>
</LinearLayout>
create an adapter class
public class ExpListAdapter extends BaseExpandableListAdapter {
private ArrayList<ArrayList<String>> mGroups;
private Context mContext;
public ExpListAdapter (Context context,ArrayList<ArrayList<String>> groups){
mContext = context;
mGroups = groups;
}
#Override
public int getGroupCount() {
return mGroups.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return mGroups.get(groupPosition).size();
}
#Override
public Object getGroup(int groupPosition) {
return mGroups.get(groupPosition);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return mGroups.get(groupPosition).get(childPosition);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.group_view, null);
}
if (isExpanded){
//Изменяем что-нибудь, если текущая Group раскрыта
}
else{
//Изменяем что-нибудь, если текущая Group скрыта
}
TextView textGroup = (TextView) convertView.findViewById(R.id.textGroup);
textGroup.setText("Group " + Integer.toString(groupPosition));
return convertView;
}
#Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_view, null);
}
TextView textChild = (TextView) convertView.findViewById(R.id.textChild);
textChild.setText(mGroups.get(groupPosition).get(childPosition));
Button button = (Button)convertView.findViewById(R.id.buttonChild);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext,"button is pressed",5000).show();
}
});
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
the names of methods and parameters is quite informative. methods getGroupView and getChildView returns View for pparents and children accordingly. using the parameter isExpanded in the method getGroupView, we ca, for instance, change the back of group in different states. using LayoutInflater we use custom layout for our list.
group_view.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">
<TextView
android:id="#+id/textGroup"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginLeft="5dp"
android:layout_marginTop="20dp"
android:textColor="#android:color/white"
android:textStyle="bold"
/>
</LinearLayout>
child_view.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">
<TextView
android:id="#+id/textChild"
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:textColor="#android:color/white"
/>
<Button
android:id="#+id/buttonChild"
android:layout_width="100dp"
android:layout_height="40dp"
android:layout_marginLeft="150dp"
android:layout_marginTop="10dp"
android:text="Button"
android:focusable="false"
/>
</LinearLayout>
in the child view we added a button, in the adapter method getChildView controlling its pressed. in the similar way we can add buttons and other elements in group_view.xml .
also, we can pin listeners to our list.
•OnChildClickListener — pressing on an element
•OnGroupCollapseListener – collapsing group
•OnGroupExpandListener – expanding group
•OnGroupClickListener – press on group
now lets look at groupIndicater - indicator of the group state. it's placement pointed in main.xml with parameters indicatorLeft, indicatorRigh - corresponding to left and right border. by default the indicator placed on the left side, what is not so cool.
also we can add custom images, for that, we need to add indicator.xml in the folder drawable with this code.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_expanded="true"
android:drawable="#drawable/imageOpen">
</item>
<item android:state_empty="true"
android:drawable="#drawable/imageClose">
</item>
</selector>
where imageOpen is for expanded group
imageClose is for collapsed group
next time we need to add a row for parameters of our list in main.xml
android:groupIndicator="#drawable/indicator"
| Icon(image) | Title(text) | cross(image) |
| | Description(text)| |
| | | coupon(image) |
Its a list view.
Here i want to get id of different items when clicked separately in list view like cross, coupon, icon is clicked then i will get their id...
I'm a newbie...Please help me out....
<?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" >
<ImageView
android:id="#+id/list_item_iv_icon"
android:layout_width="100dp"
android:layout_height="100dp"
android:contentDescription="#string/app_name"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<ImageView
android:id="#+id/list_item_iv_icon_cross"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:clickable="true"
android:contentDescription="#string/app_name"
android:src="#drawable/cross_selector" />
<TextView
android:id="#+id/list_item_tv_title"
android:layout_width="wrap_content"
android:layout_height="30dp"
android:layout_toRightOf="#+id/list_item_iv_icon"
android:gravity="left"
android:textColor="#CC0033"
android:textIsSelectable="false"
android:textSize="20sp" />
<TextView
android:id="#+id/list_item_tv_desc"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/list_item_tv_title"
android:layout_toRightOf="#+id/list_item_iv_icon"
android:gravity="left"
android:textColor="#3399FF"
android:textIsSelectable="false"
android:textSize="14sp" />
<ImageView
android:id="#+id/list_item_iv_type"
android:layout_width="100dp"
android:layout_height="30dp"
android:layout_alignBottom="#id/list_item_iv_icon"
android:layout_alignParentRight="true"
android:contentDescription="#string/app_name" />
</RelativeLayout>
I know how to get id of the clicked list. i want to know is how to get item id of a clicked item in list.
Here is the answer for NewBies like Me...
<ImageView
android:id="#+id/list_item_iv_icon_cross"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_alignParentRight="true"
android:clickable="true"
android:contentDescription="#string/app_name"
android:src="#drawable/cross_selector"
android:onClick="onCrossClick" />
i used onClick on item and to get position in which it has been clicked i used
final int position = listView.getPositionForView((View) v.getParent());
full code :-
public void onCrossClick(View v) {
final int position = listView.getPositionForView((View) v.getParent());
Toast.makeText(this, "click on button " + position, Toast.LENGTH_LONG)
.show();
}
The following is the code to set a listener for the list view which would capture the list item selection event.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
// To get the item from the list use the position value
Object yourObject = yourAdapter.getItem(position);
}
})
Check below Sample code :
public class ListViewAdapter_test extends BaseAdapter {
private LayoutInflater mInflater;
public ListViewAdapter_test(Context con) {
// TODO Auto-generated constructor stub
mInflater = LayoutInflater.from(con);
}
public int getCount() {
// TODO Auto-generated method stub
return a_product_id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
// return product_id1.size();
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
// return product_id1.get(position).hashCode();
return position;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
final ListContent holder;
View v = convertView;
if (v == null) {
v = mInflater.inflate(R.layout.scan_row1, null);
holder = new ListContent();
holder.name = (TextView) v.findViewById(R.id.sc_textname);
holder.name1 = (TextView) v.findViewById(R.id.sc_review);
holder.ratings = (RatingBar) v.findViewById(R.id.sc_ratingBar1);
holder.total_rate = (Button) v.findViewById(R.id.button1);
holder.img_p = (ImageView) v.findViewById(R.id.image_prod);
// holder.total_rate.setOnClickListener(mOnTitleClickListener1);
v.setTag(holder);
} else {
holder = (ListContent) v.getTag();
}
holder.total_rate.setOnClickListener(mOnTitleClickListener3);
holder.img_p.setOnClickListener(mOnTitleClickListener_image);
return v;
}
}
static class ListContent {
ImageView img_p;
TextView name1;
TextView name;
RatingBar ratings;
Button total_rate;
}
public OnClickListener mOnTitleClickListener3 = new OnClickListener() {
public void onClick(View v) {
final int position = list_v
.getPositionForView((View) v.getParent());
Log.d("you are click on Ratings","you are click on Ratings");
}
};
public OnClickListener mOnTitleClickListener_image = new OnClickListener() {
public void onClick(View v) {
final int position = list_v
.getPositionForView((View) v.getParent());
Log.d("you are click on image view","you are click on image view");
}
};