Hello I have custom adopter for a ListView how can I add clickListener on item and I also need a menu in item with some other button(DropDwons) I am new to android development I tried many solutions from internet but not working for me.
please help me
My Code
public class TrackAdapter extends ArrayAdapter<Result> {
private Context mContext;
private List<Result> trackList = new ArrayList<>();
public TrackAdapter(#NonNull Context context, List<Result> list) {
super(context, 0 , list);
mContext = context;
trackList = list;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listItem = convertView;
if(listItem == null)
listItem = LayoutInflater.from(mContext).inflate(R.layout.track,parent,false);
Result currentTrack = trackList.get(position);
return listItem;
}
}
Item.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width="match_parent"
android:padding="8dp"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageView_poster"
android:layout_width="45dp"
android:src="#drawable/default_album"
android:layout_height="45dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/textView_release"
android:layout_width="wrap_content"
android:text="Artist Name"
app:layout_constraintStart_toEndOf="#+id/imageView_poster"
app:layout_constraintTop_toBottomOf="#+id/textView_name" />
</android.support.constraint.ConstraintLayout>
Just give id to your android.support.constraint.ConstraintLayout like:
android:id="#+id/parent"
And then create like
ConstraintLayout parent = (ConstraintLayout)listItem.findViewById(R.id.parent);
parent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Code stuff
}
});
Related
I have a dynamically created list. It's fragment-layout is as follows:
<ListView
android:id="#+id/colorsList"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
When I add a row to the listview, I want an "X" mark to appear at the end of the row so that when the user clicks on the "X", the row gets deleted.
Not sure, if its relevant but, the way I am adding and removing rows to the listview is as follows.
Logic to add a row tot he listView:
#BindView(R.id.understood_languages_list)
View mColorsList;
*********
*********
ListView listFavoriteColors;
listFavoriteColors = (ListView) mColorsList;
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, getColorsList());
listFavoriteColors.setAdapter(arrayAdapter);
Logic to remove a row from the ListView.
listFavoriteColors.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
initializeView();
arrayAdapter.remove(((TextView)view).getText().toString());
}
});
Any helpful suggestions on how this can be achieved is much appreciated.
User Custom Adapter with custom Layout to attach delete button to each item in listview
try this code :
CustomAdapter
public class ListAdapter extends ArrayAdapter<String> {
private int resourceLayout;
private Context mContext;
ListInterFace interface;
public ListAdapter(Context context, int resource, List<String>
items,ListInterFace interface) {
super(context, resource, items);
this.resourceLayout = resource;
this.mContext = context;
this.interface=interface;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(mContext);
v = vi.inflate(resourceLayout, null);
}
String value= getItem(position);
if (value!= null) {
TextView tt1 = (TextView) v.findViewById(R.id.dummytext);
Button cancel_click=v.findViewById(R.id.cancel_click);
if (tt1 != null) {
tt1.setText(value);
}
//remove item on button click
cancel_click.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
interface.removeItem(position);
}
})
}
return v;
}
}
R.layout.itemlistrow defines the row of the ListView.
<?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:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/dummytext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dummy"
android:textColor="#android:color/black"
android:textSize="18sp"
android:padding="5dp"/>
<ImageView
android:id="#+id/cancel_click"
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#mipmap/cancel"
android:layout_alignParentRight="true"
android:layout_margin="5dp"/>
</RelativeLayout>
</LinearLayout>
In the MainActivity define ListViewlike this,
ListView yourListView = (ListView) findViewById(R.id.itemListView);
// get data from the table by the ListAdapter
ListAdapter customAdapter = new ListAdapter(this, R.layout.itemlistrow, myList, new ListInterFace () {
#Override
public void removeItem( int position) {
myList.remove(position);
customAdapter .notifyDataSetChanged();
});
yourListView .setAdapter(customAdapter);
InterFace
public interface ListInterFace {
void removeItem(int position);
}
try this link to remove item from list view on button click
Remove Item From List View On Button Click
Basically I am trying to code a onClickListener for a button in MainActivity.java .
This Button is defined in a resource file : main_resource.xml inside a ListView and not in activity_main.xml.
I am getting the error :
Trying to define a onClick Listener on null item.
Button btn = (Button) findViewById(R.id.mybutton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
});
Here is my main_resource.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dip">
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/ridedetails"
android:layout_marginLeft="2dip">
</TextView>
<EditText
android:layout_height="wrap_content"
android:hint="Quote Price"
android:layout_width="wrap_content"
android:id="#+id/PriceQuotation"
android:layout_below="#+id/ridedetails"
android:layout_marginLeft="2dip">
</EditText>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/PriceQuotation"
android:layout_marginStart="61dp"
android:layout_toEndOf="#+id/PriceQuotation"
android:text="Button" />
</RelativeLayout>
Here is my activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
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/myrefresh"
android:focusable="false"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_home"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_home"
app:menu="#menu/activity_home_drawer" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".PreviousRide"
>
<ListView
android:id="#+id/incomingrides"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="30dp"
android:layout_marginTop="80dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"></ListView>
</LinearLayout>
</android.support.v4.widget.DrawerLayout>
</android.support.v4.widget.SwipeRefreshLayout>
Here I am not using any Custom Adapter Class : I am injecting the data into my list view using the following ArrayAdapter code written in onRefresh() of Swipe Refresh Widget ::
final ArrayAdapter<String > adapter=new ArrayAdapter<String>(getApplicationContext(),
R.layout.home_resource, R.id.ridedetails, allNames);
l1.setAdapter(adapter);
// L1 is the listView Reference
You have to create custom class for adapter
Here is sample code for adapter.
public class MyAdapter extends ArrayAdapter<String> {
private int resourceId;
private List<String> sites = null;
private Context context;
public MyAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
this.context = context;
this.resourceId = resource;
this.sites = objects;
}
#Override
public String getItem(int position) {
return sites.get(position);
}
#Override
public int getCount() {
return sites.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String name = getItem(position);
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(resourceId, null);
}
TextView mTextView = (TextView) view.findViewById(R.id.ridedetails);
mTextview.setText(name);
Button mButton = (Button) view.findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, name, Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
set adapter in listview like below code.
l1.setAdapter(new MyAdapter(getApplicationContext(), R.layout.home_resource, allNames));
you should put your onClickListener in Adapter Not in Main Activity
Your Adapter
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
Button btn = (Button ) v.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myFancyMethod(v);
}
})
}
I am developing an app where I show a dropdownlist using a spinner.
I used a custom adapter, here is the code:
public class DemandeCongeAdapter extends BaseAdapter {
public static final String TAG = "DemandeCongeAdapter";
private final Context mContext;
private List<DemandeCongeType> mData;
protected LayoutInflater mInflater;
public DemandeCongeAdapter(Context mContext, List<DemandeCongeType> mData) {
this.mContext = mContext;
this.mData = mData;
this.mInflater = LayoutInflater.from(mContext);
}
static class ViewHolder {
public ViewHolder(View v) {
typedeDemandeName = (TextView) v.findViewById(R.id.type_demande_name);
}
protected final TextView typedeDemandeName;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public DemandeCongeType getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.layout_create_demande_conge_custom_spinner, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
if (position != 0) {
DemandeCongeType item = getItem(position);
String name = item.getTypdeDemandeName() == null ? "" : item.getTypdeDemandeName();
viewHolder.typedeDemandeName.setText(name);
}
return convertView;
}
}
And for the activity code, here is it:
private List<DemandeCongeType> congeTypes;
private DemandeCongeAdapter spinnerCongeTypeArrayAdapter;
congeTypes.addAll(new ArrayList<>((List<DemandeCongeType>) responseBody));
congeTypes.add(0, new DemandeCongeType());
spinnerCongeTypeArrayAdapter = new
DemandeCongeAdapter(DemandeCongeNewActivity.this, congeTypes);
congeTypeSpinner.setAdapter(spinnerCongeTypeArrayAdapter);
congeTypeSpinner.setSelection(Adapter.NO_SELECTION, false);
Everything works fine, but when I select the spinner for the first time, it shows the list correctly like this:
Once I click outside the spinner and I click for the second time on the spinner, I got it like this:
So I can't the find the problem, please if anyone can help me with that.
Here is the XML code:
<Spinner
android:id="#+id/spinner_type_conge"
fontPath="fonts/light.otf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:background="#null"
android:dropDownWidth="match_parent"
android:ellipsize="end"
android:lines="1"
android:paddingRight="2dp"
android:spinnerMode="dropdown"
android:textSize="13sp" />
And for the spinner item xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/type_demande_name"
fontPath="fonts/light.otf"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:lines="1"
android:padding="10dp"
android:textColor="#color/annuaire_hint_color"
android:textSize="13sp" />
Try This way i have use this in my Application.
XML Design Code.
Spinner set in your Activity
<Spinner
android:id="#+id/sp_pen_Category"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:background="#android:color/transparent"
android:padding="#dimen/margin_10" />
This file XML File sp_list.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="marquee"
android:padding="15dp"
android:singleLine="true"
android:textColor="#color/black"
android:textSize="#dimen/sub_title">
</CheckedTextView>
This file XML File sp_items.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ellipsize="marquee"
android:singleLine="true"
android:textColor="#color/black">
</CheckedTextView>
This is Java code when you fill spinner.
ArrayAdapter<String> adp_sp = new ArrayAdapter<String>(Activity.this, R.layout.sp_items, arr_spinner);
adp_sp.setDropDownViewResource(R.layout.sp_list);
sp_pen_Category.setAdapter(adp_sp);
I have a simple listView via a custom adapter. Each row in the list view is composed of a ImageButton and TextView.
The idea is to change the ImageButton when user taps on it and it does not work. However, ImageButton changes for the views that are scrolled and recycled. I mean, when user scrolls down the list and comes back to the top and tap on the ImageButton it works as expected for those rows that were scrolled and back again.
Can you guys help me out what i'm missing? I'm extremely new to Android and have been stuck around this for about a week now trying to fix this.
Here's the APK for the sample test app:
https://www.dropbox.com/s/pzlahtqkgj010m8/app-ListViewExample.apk?dl=0
Here are the relevant parts of my code:
avtivity_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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
/>
</RelativeLayout>
and to render the single row in the ListView the following xml is utilized:
single_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"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
>
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageButton"
android:src="#drawable/b"
android:layout_weight="2"
style="#style/ListView.first"
android:layout_gravity="center"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/textView"
android:layout_weight="10"
android:layout_gravity="center"
/>
</LinearLayout>
coming to the Java code,
MainActivity.java is
public class MainActivity extends AppCompatActivity {
String[] titles;
ListView list;
private listViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
titles = res.getStringArray(R.array.titles);
list = (ListView) findViewById(R.id.listView);
adapter = new listViewAdapter(this, titles);
list.setAdapter(adapter);
}
}
and the custom adapter listViewAdapter.java look like this
class sListItem {
public ImageButton button;
public TextView text;
public boolean active;
}
public class listViewAdapter extends ArrayAdapter<String> {
private final String[] titles;
Context context;
private int size = 15;
public sListItem mp[] = new sListItem[size];
public listViewAdapter(Context context, String[] titles) {
super(context, R.layout.single_row, R.id.imageButton, titles);
this.context = context;
this.titles = titles;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.single_row, parent, false);
if(mp[position] == null)
mp[position] = new sListItem();
mp[position].button = (ImageButton) row.findViewById(R.id.imageButton);
mp[position].button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp[position].active = !mp[position].active;
setIcon(position, mp[position].active);
}
});
mp[position].text = (TextView) row.findViewById(R.id.textView);
mp[position].text.setText(titles[position]);
setIcon(position, mp[position].active);
return row;
}
private void setIcon(int position, boolean active) {
Drawable drawable;
if(active){
drawable = getContext().getResources().getDrawable(R.drawable.a);
} else {
drawable = getContext().getResources().getDrawable(R.drawable.b);
}
mp[position].button.setImageDrawable(drawable);
}
}
EDIT: Added link to sample test app.
You should tell adapter to update by calling notifydatasetchanged in the click listener
mp[position].button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp[position].active = !mp[position].active;
setIcon(position, mp[position].active);
notifydatasetchanged();
}
});
I'm just getting my feet wet with Android and have built a UI that contains a TabHost with three tabs. Each tab is powered by its own Activity. The first Tab contains a listview with a prepopulated set of rows and is built from a custom ArrayAdapter.
The problem I'm running into is that none of the ListView rows are tappable. In other words, when I tap on them there is no orange selection. If I use the scroll ball on my Nexus One it will select, but any touch gestures don't seem to be responding.
All the UI is being handled using XML files with a main.xml housing the TabHost -> LinearLayout -> TabWidget/FrameLayout and a nearby_activity.xml file containing my ListView UI
<?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">
<TextView
android:id="#+id/android:empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/nearby_no_events"
/>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1.0"
android:choiceMode="multipleChoice"
android:divider="#d9d9d9"
android:dividerHeight="1px"
android:cacheColorHint="#eee"
/>
</LinearLayout>
And the relevant code from my Activity that is set to show in the selected tab.
public class NearbyActivity extends ListActivity
{
private ArrayList<Event> m_events = null;
private EventAdapter m_adapter = null;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.nearby_activity);
getEvents();
this.m_adapter = new EventAdapter(this, R.layout.eventrow, m_events);
setListAdapter(this.m_adapter);
}
private void getEvents()
{
m_events = new ArrayList<Event>();
for (int i = 0; i < 100 ; i++)
{
Event e = new Event();
e.setEventName("Event " + i);
e.setVenueName("Staples Center");
e.setStartDate(new Date());
m_events.add(e);
}
}
private class EventAdapter extends ArrayAdapter<Event>
{
private ArrayList<Event> items;
public EventAdapter(Context context, int textViewResourceId, ArrayList<Event> items)
{
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView (int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.eventrow, null);
}
Event e = items.get(position);
if (e != null)
{
TextView nameText = (TextView)v.findViewById(R.id.eventName);
TextView venueNameText = (TextView)v.findViewById(R.id.venueName);
if (nameText != null)
{
nameText.setText(e.getEventName());
}
if(venueNameText != null)
{
venueNameText.setText(e.getVenueName());
}
}
return v;
}
}
}
My listview row's are populated by an XML file as well.
<?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="?android:attr/listPreferredItemHeight"
android:orientation="vertical"
android:padding="4dip">
<TextView
android:id="#+id/eventName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:inputType="text"
android:singleLine="true"
android:ellipsize="marquee"
android:textSize="18sp"
android:textColor="#000"
/>
<TextView
android:id="#+id/venueName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/eventName"
android:layout_alignParentBottom="true"
android:layout_marginRight="55dip"
android:singleLine="true"
android:ellipsize="end"
android:scrollHorizontally="true"
android:textSize="13sp"
android:textColor="#313131"
android:layout_alignWithParentIfMissing="true"
android:gravity="center_vertical"
/>
</RelativeLayout>
Thanks for any help you can offer.
You want a Listview tappable, well you need implement the method onListItemClick()
#Override
protected void onListItemClick(ListView l, View v, final int position, long id) {
super.onListItemClick(l, v, position, id);
Toast.makeText(this, "This is my row number " + position,Toast.LENGTH_LONG).show();
}
and to ensure the orange colour you must set the property
android:focusable="false"
in your Listview Row.xml