android:onClick get the id of the clicked item - android

I have a list of posts with the autor name.
I want to know which author name had been clicked.
The layout :
<TextView
android:id="#+id/user"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:layout_marginLeft="10dp"
android:textStyle="bold"
android:onClick="userClick"
tools:text="User" />
<TextView android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/black"
android:layout_alignLeft="#+id/user"
android:layout_below="#+id/user"
android:onClick="postClick"
tools:text="Content" />
When an author name is clicked this function is called :
public void userClick(View v) {
//Is it possible to know which author name had been clicked from here?
}
What is the correct method to identify on which author name the user had clicked.
EDIT
I've tryied the getId() method
public void userClick(View v) {
Log.d("userClick called :",String.valueOf(v.getId()));
}
It always return the same id even if I click on different users.

If you are using listview, you can use the following:
String author ;
yourListView.setOnItemClickListener (new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent,View view,int position,long id){
Textview user = (TextView) view.findViewById(R.id.user);
author=user.getText().toString();
}
});
Update :
Did you try that ?
public void userClick(View view){
TextView textview = (TextView) view;
author=textview.getText().toString();
}

I assume that this is the RecyclerView.
And you can use
RecyclerViewAdapter.class
private View.OnClickListener globalClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
int clickedPosition = (int) v.getTag();
// do something with position
}
}
RecyclerViewAdapter.onBindViewHolder
holder.itemView.setTag(position);
holder.itemView.setOnClickListener(globalClickListener);
Also if you want to get view id,
private View.OnClickListener globalClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if(R.id.title == v.getId()){
// Clicked child view (R.id.title which is implemented in XML)
}

I would solve this problem by implementing an AdapterView.OnItemClickListener and adding it to my ListView. The following solution works because both MyAdapter and MyListener have access to the Activity's posts field.
public class MainActivity extends AppCompatActivity {
private List<Post> posts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
posts = new ArrayList<>();
posts.add(new Post("author1", "title1"));
posts.add(new Post("author1", "title2"));
posts.add(new Post("author2", "title3"));
posts.add(new Post("author3", "title4"));
posts.add(new Post("author2", "title5"));
posts.add(new Post("author1", "title6"));
posts.add(new Post("author3", "title7"));
posts.add(new Post("author3", "title8"));
ListView list = (ListView) findViewById(R.id.list);
list.setAdapter(new MyAdapter());
list.setOnItemClickListener(new MyListener());
}
private class MyAdapter extends BaseAdapter {
#Override
public int getCount() {
return (posts != null) ? posts.size() : 0;
}
#Override
public Post getItem(int position) {
return posts.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.post, parent, false);
}
ViewHolder holder = (ViewHolder) convertView.getTag();
if (holder == null) {
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
Post item = getItem(position);
holder.user.setText(item.user);
holder.title.setText(item.title);
return convertView;
}
}
private class MyListener implements AdapterView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Post item = posts.get(position);
Toast.makeText(MainActivity.this, item.user, Toast.LENGTH_SHORT).show();
}
}
private static class ViewHolder {
private final TextView user;
private final TextView title;
public ViewHolder(View v) {
this.user = (TextView) v.findViewById(R.id.user);
this.title = (TextView) v.findViewById(R.id.title);
}
}
private static class Post {
private final String user;
private final String title;
public Post(String user, String title) {
this.user = user;
this.title = title;
}
}
}

In the java file, after calling the onClickListener, try to access the button or clickable using the this keyword. It refers the the context of the clicked item.
Works in Java and JavaScript.

Related

Added items to cart list

I have created an android application. in that application when I click on add, item added to the array list and this array list I want to show in Cart Activity. how to do that.
here is my activity1
public void addShirt(View view) {
MainActivity.cartItems.add(getString(R.string.shirt));
}
public void addPant(View view) {
MainActivity.cartItems.add(getString(R.string.pant));
}
public void view(View view) {
Intent i =new Intent(OnlyIron.this,CartActivity.class);
startActivity(i);
}
and cart activity is
for(int i=0; i<MainActivity.cartItems.size();i++) {
Toast.makeText(this, "item : " + MainActivity.cartItems.get(i), Toast.LENGTH_SHORT).show();
}
it showing toast but I enter code here want this show in listview
First lets Create model class and store data in it.
public class Cart {
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Now to add items in that list i would call it this way :
private ArrayList<Cart > cart_array;
cart_array= new ArrayList<>();
Cart cart1 = new Cart ();
cart.setId("1");
cart.setName("first product");
Cart cart2 = new Cart ();
cart.setId("2");
cart.setName("first product");
Cart cart3 = new Cart ();
cart.setId("3");
cart.setName("first product");
//and than add your model into array
cart_array.add(cart1);
cart_array.add(cart2);
cart_array.add(cart3);
//and finaly set your adapter
Cart_Adapter adapter = new Cart_Adapter(cart_array, getActivity());
Recycler.setAdapter(adapter );
Please take a list view in CartActivity & create an Custom Adapter as according to your need(UI). Pass the MainActivity.cartItems this list to Adapter. It will start to show in your CartActivity.
You can see below example:
public class CustomAdapter extends BaseAdapter{
Activity mContext;
public ArrayList<String> mCartList = new ArrayList<String>();
private LayoutInflater mInflater=null;
public CustomAdapter(Activity activty, ArrayList<String> list)
{
this.mContext = activty;
mInflater = activty.getLayoutInflater();
this.mCartList=list;
}
#Override
public int getCount() {
if (mCartList != null){
return mCartList.size();
} else{
return 0;
}
}
#Override
public String getItem(int arg0) {
return mCartList.get(arg0);
}
#Override
public long getItemId(int index) {
return index;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
final ViewHolder holder;
if (convertView == null ) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.item_layout, null);
holder.mItemNameTV= (TextView) convertView.findViewById(R.id.itemtv);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.mNameTV.setText(mCartList.get(position));
return convertView;
}
private static class ViewHolder {
TextView mNameTV;
}
}
// Item Layout
<LinearLayout
android:layout_width="match_parent"
android:layout_height="#dimen/forty_dp"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:id="#+id/fieldTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/five_dp"
android:layout_weight="0.4"
android:padding="#dimen/ten_dp"
android:text="Custom Field"
android:textColor="#color/dark_gray_color"
android:textSize="#dimen/normal_font_size"
android:visibility="visible" />
</LinearLayout>
// Let Suppose your CartActivity is following:
ListView mListView = (ListView)findViewById(R.id.listview);
CustomAdapter adapter = new CustomAdapter(this, MainActivity.cartItems);
mListView.setAdapter(adapter);

Click button inside listview then trigger gridview to load its button list on android studio

I have a listview, from database (category list) and i want to load gridview (product gridview) when i click any button in the category listview, i'm able to make the listview and gridview, but cannot connect them, since im still new at android programming and have no clue to do it.
my main purpose is:
List category
on click on the category button will load gridview of product button
on click product button will add the product id to table cart
ps: if you notice i do SQL query in the mainActivity class, i still new at the code so i tried my best first before convert into better practice.
Any suggestion to do it?
Here i include my snippet:
Category.java (setter and getter)
public class Category {
private int _id;
private String _name;
public Category() {
}
public Category(int id, String name) {
this._id = id;
this._name = name;
}
public Category(String name) {
this._name = name;
}
public int getID() {
return this._id;
}
public void setID(int id) {
this._id = id;
}
public String get_name()
{
return this._name;
}
public void set_name(String name)
{
this._name = name;
}
}
CategoryListAdapter.java
public class CategoryListAdapter extends BaseAdapter {
private ArrayList<Category> listData;
private LayoutInflater layoutInflater;
public CategoryListAdapter(Context aContext, ArrayList<Category> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
CategoryListAdapter.ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_category, null);
holder = new CategoryListAdapter.ViewHolder();
holder.btnCategory = (Button) convertView.findViewById(R.id.btnCategory);
convertView.setTag(holder);
} else {
holder = (CategoryListAdapter.ViewHolder) convertView.getTag();
}
holder.btnCategory.setText(listData.get(position).get_name());
return convertView;
}
static class ViewHolder {
Button btnCategory;
}
}
listview_category.xml (layout that will be repeated)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp"
android:textStyle="bold"
android:textSize="16dp"
android:id="#+id/btnCategory"
android:focusable="false"
android:focusableInTouchMode="false"
android:background="#drawable/button_category"/>
</LinearLayout>
listview inside MainActivity
<ListView
android:id="#+id/listviewCategory"
android:layout_margin="10dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
java inside MainActivity
protected void onCreate(Bundle savedInstanceState) {
...
/* LIST CATEGORY TO LOAD PRODUCT */
ArrayList list_category = getListCategory();
final ListView listview_category = (ListView) findViewById(R.id.listviewCategory);
listview_category.setAdapter(new CategoryListAdapter(this, list_category));
listview_category.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Log.d(TAG, "click cat");
//Give product list an id from category_id get from here
}
});
...
}
/* List Category for selecting category product */
private ArrayList getListCategory() {
SQLiteDatabase mydatabase = openOrCreateDatabase("posDb",MODE_PRIVATE,null);
Cursor resultSet = mydatabase.rawQuery("Select * from categories",null);
ArrayList<Category> results = new ArrayList<Category>();
if (resultSet.moveToFirst()) {
do {
Category categoriesData = new Category();
categoriesData.set_name(resultSet.getString(1));
results.add(categoriesData);
} while (resultSet.moveToNext());
}
return results;
}
The grid of product mostly the same as category, but load product from database which later i want to onclick the product button to save record to cart table
on Click on button will add the product id in to table_cart
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// ArrayList list_category = getListCategory();
int id[]={1, 2, 3, 4, 5};
String categoryName[]={"category1","category2","category3","category4","category5"};
ArrayList<Category> listData=new ArrayList<>();
Category category;
for (int i=0; i<id.length; i++)
{
category=new Category();
category.set_id(id[i]);// setting Id
category.set_name(categoryName[i]);// setting category name
listData.add(category);
}
final ListView listview_category = (ListView) findViewById(R.id.listviewCategory);
listview_category.setAdapter(new CategoryListAdapter(this, listData ));
}
}
CategoryListAdapter.java
public class CategoryListAdapter extends BaseAdapter {
private ArrayList listData;
private LayoutInflater layoutInflater;
ArrayList table_cart = new ArrayList();
private static final String TAG = "CategoryListAdapter";
public CategoryListAdapter(Context aContext, ArrayList<Category> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
final CategoryListAdapter.ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.listview_category, null);
holder = new CategoryListAdapter.ViewHolder();
holder.btnCategory = (Button) convertView.findViewById(R.id.btnCategory);
convertView.setTag(holder);
} else {
holder = (CategoryListAdapter.ViewHolder) convertView.getTag();
}
holder.btnCategory.setText(listData.get(position).get_name());
holder.btnCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// getting product id
int product_id = listData.get(position).getID();
Log.e(TAG, "product_id: " + product_id);
// now you can get category name as well
String category_name = listData.get(position).get_name();
Log.e(TAG, "category_name: " + category_name);
// now adding product id in to table_cart
table_cart.add(listData.get(position).getID());
}
});
return convertView;
}
static class ViewHolder {
Button btnCategory;
}
}
Category.java
public class Category {
private int _id;
private String _name;
public int getID() {
return this._id;
}
public void setID(int id) {
this._id = id;
}
public String get_name() {
return this._name;
}
public void set_name(String name) {
this._name = name;
}
public void set_id(int _id) {
this._id = _id;
}
}
there is no need to change layouts
Add on click listener for category button, add grid view in fragment and open fragment on button click.
holder.btnCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ProductFragment nextFrag= new ProductFragment();
this.getFragmentManager().beginTransaction()
.replace(R.id.Layout_container, nextFrag,TAG_FRAGMENT)
.commit();
}
});

remove elements from listview in android

i have 2 arrays productname and price. my each row in listview contains productname,price and an image button remove. when i click remove button,the selected productname and price should be removed from my array as well as from my listview. Please guide me doing this,is very important for me. If there is another way of doing this plz let me know.i m student only!
this is my CartActivity
public class CartActivity extends Activity implements View.OnClickListener {
CartAdapter contactAdapter;
ListView listView;
public String productname[]=new String[10];
public String price[]=new String[10];
int i=0,m;
CartActivity(String scanContent){
this.content = scanContent;
}
public CartActivity() {}
String product,Price;
String pri,prod;
Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
listView = (ListView) findViewById(R.id.cart_list_view);
contactAdapter = new CartAdapter(this,R.layout.activity_cart_list_view);
listView.setAdapter(contactAdapter);
intent = getIntent();
productname = intent.getStringArrayExtra("productname");
price = intent.getStringArrayExtra("price");
for(int j=0;j<price.length;j++) {
product = productname[j];
Price = price[j];
if (Price != null || product != null) {
Cart contacts = new Cart(product, Price);
contactAdapter.add(contacts);
}
}
}
this is my CartAdapter
public class CartAdapter extends ArrayAdapter {
List list = new ArrayList();
int ind,x=0;
public CartAdapter(CartActivity context, int resource) {
super(context, resource);
}
public void add(Cart object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
ContactHolder contactHolder;
if(row == null)
{
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.activity_cart_list_view,parent,false);
contactHolder = new ContactHolder();
contactHolder.tx_name =(TextView) row.findViewById(R.id.product_name);
contactHolder.tx_price =(TextView) row.findViewById(R.id.price);
contactHolder.cancelButton = (ImageButton) row.findViewById(R.id.cancel_button);
row.setTag(contactHolder);
}
else
{
contactHolder = (ContactHolder)row.getTag();
}
cancelButton.setTag(position);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Integer index = (Integer) view.getTag();
list.remove(index.intValue());
notifyDataSetChanged();
}
});
Cart contacts = (Cart) this.getItem(position);
contactHolder.tx_name.setText(contacts.getItemname());
contactHolder.tx_price.setText(contacts.getPrice());
return row;
}
static class ContactHolder
{
TextView tx_name,tx_price;
ImageButton cancelButton;
}
}
this is my Cart
public class Cart {
private String itemname,price;
public Cart(String itemname,String price) {
this.setItemname(itemname);
this.setPrice(price);
}
public void setItemname(String itemname) {
this.itemname = itemname;
}
public void setPrice(String price) {
this.price = price;
}
public String getItemname() {
return itemname;
}
public String getPrice() {
return price;
}
}
my each row in a listview contains this
Just do this,
in your adapter class,
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
list.remove(position); //position is getView position
// above line will remove from arraylist
notifyDataSetChanged(); //this line reflects change in listview
}
});
To remove from Activity class,
better create an ArrayList first.
ArrayList<Cart> cardList = new ArrayList<Cart>();
add into arrayList,
if (Price != null || product != null) {
Cart contacts = new Cart(product, Price);
cardList.add(contacts);
contactAdapter.add(contacts); // this line should be removed if you work with arrayList
}
now create a method to remove from ActivityCard arrayList,
//call this method from cancelimage click in adapter class
public void removeFromList(int position){
cardList.remove(position); //this will remove from activity arraylist
}
At the end calculate your bill from existing cartList data.
*** You can also create adapter class object with cardList just changing your constructor. If you do this then just call removeFromList on cancelimage click and put,
adapter.notifyDataSetChanged();
after
cardList.remove(position);
it will refresh your listview also.

Android OnClickListener not working with custom adapter

I've made a custom adapter for a ListView in order to display a String and an ImageButton within the same row. A row is generated every time the add button is clicked. The string is taken from the EditText field, while the ImageButton bin_button is allocated dinamically. Everything works fine except I can't make the bin_buttons fire an OnClick event.
I've tried several solutions. Here bin_button_listener is generated outside the add_button OnClickListener and then set. I've also tried to set listeners with a new OnClickListener every time a new bin_button was created.
Here some code:
Row layout list_string_button_layout.xml:
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
android:paddingEnd="0dp"
android:paddingTop="8dp"
android:textSize="18sp"
android:textStyle="bold"/>
<ImageButton
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingEnd="5dp"
android:background="#00ffffff"
android:src="#drawable/ic_delete_black_18dp"
android:layout_alignBottom="#+id/list_item_string"
android:layout_alignParentEnd="true"
android:focusableInTouchMode="true"
/>
</RelativeLayout>
Activity layout activity_search.xml:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ingredient_text_input"
android:hint="#string/start_typing_ingredient"
android:layout_marginTop="52dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<Button
style="#style/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_button"
android:backgroundTint="#color/colorPrimaryLight"
android:id="#+id/add_button"
android:layout_alignTop="#+id/ingredient_text_input"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ingredients_view"
android:layout_above="#+id/search_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/add_button" />
</RelativeLayout>
Custom Adapter IngredientBinAdapter:
public class IngredientBinAdapter extends BaseAdapter {
private Context context = null;
private List<HashMap<String,ImageButton>> items = new ArrayList<>();
public IngredientBinAdapter(Context context, ArrayList<HashMap<String,ImageButton>> items){
this.context=context;
this.items=items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = LayoutInflater.from(context).inflate(R.layout.list_string_button_layout,null);
HashMap<String,ImageButton> item = (HashMap<String,ImageButton>) getItem(position);
TextView string = (TextView) convertView.findViewById(R.id.list_item_string);
String key=(String) item.keySet().toArray()[0];
string.setText(key);
item.get(key).setImageResource(R.drawable.ic_delete_black_18dp);
return convertView;
}
}
Activity:
public class SearchActivity extends AppCompatActivity{
//getting resources and allocating variables
Button add_button = null;
Button search_button = null;
EditText insert_ingredient = null;
ListView ingredient_list_view = null;
ArrayList<HashMap<String,ImageButton>> ingredient_list = new ArrayList<>();
IngredientBinAdapter list_adapter = new IngredientBinAdapter(this,ingredient_list);
ArrayList<String> ingredients_utils = new ArrayList<>();
View.OnClickListener bin_button_listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("BIN_BUTTON CLICKED");
ImageButton clicked_button = (ImageButton) v;
for(Iterator<HashMap<String,ImageButton>> i = ingredient_list.iterator(); i.hasNext(); ){
HashMap<String,ImageButton> temp= i.next();
if(temp.values().toArray()[0].equals(clicked_button))
ingredient_list.remove(temp);
}
list_adapter.notifyDataSetChanged();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
}
#Override
protected void onStart(){
super.onStart();
add_button = (Button) findViewById(R.id.add_button);
search_button = (Button) findViewById(R.id.search_button2);
insert_ingredient = (EditText) findViewById(R.id.ingredient_text_input);
ingredient_list_view = (ListView) findViewById(R.id.ingredients_view);
ingredient_list_view.setAdapter(list_adapter);
//add_button listener
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String current_ingredient_string = insert_ingredient.getText().toString().trim();
if (!current_ingredient_string.isEmpty() && !ingredients_utils.contains(current_ingredient_string)) {
HashMap<String, ImageButton> temp = new HashMap<String, ImageButton>();
ImageButton temp_bin_button = new ImageButton(SearchActivity.this);
temp_bin_button.setOnClickListener(bin_button_listener);
temp.put(current_ingredient_string, temp_bin_button);
ingredient_list.add(temp);
list_adapter.notifyDataSetChanged();
}
ingredients_utils.add(insert_ingredient.getText().toString().trim());
insert_ingredient.getText().clear();
}
});
}
}
first of all
u should move your logic to onCreate() see: Difference between onCreate() and onStart()?
second
u should in your method in adapter :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. inflate view
// 2. find button
// 3. assign here listener to bin button
// i advice to use convert view pattern
}
some hints :
create data object describing row item
public class BinRow {
private String _someString;
private Drawable _imageDrawable; // (or resource id name)
public String getString() {
return _someString;
}
public Drawable getImage() {
return _imageDrawable;
}
public BinRow(String someText, Drawable imageDrawable) {
_someText = someText;
_imageDrawable = imageDrawable;
}
}
here u have adapter example ( u need adjust Album - to your BinRow & layout for row & convert view items in view holder ) - this should show you idea how adapter works :
public class AlbumAdapter extends BaseAdapter implements IListAdapter<Album> {
private List<Album> _albums;
private Context _context;
private LayoutInflater _layoutInflater;
static class ViewHolder {
ImageView imageView;
TextView albumName;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.image);
albumName = (TextView) v.findViewById(R.id.tvAlbumName);
}
}
public AlbumAdapter(List<Album> albums) {
if(albums == null) {
_albums = new ArrasyList<>();
} else {
_albums = albums;
}
}
#Override
public int getCount() {
return _albums.size();
}
#Override
public Album getItem(int position) {
return _albums.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final Album album = getItem(position);
if (_context == null) {
_context = parent.getContext();
}
if (_layoutInflater == null) {
_layoutInflater = LayoutInflater.from(_context);
}
View _view = convertView;
ViewHolder viewHolder;
if (_view == null) {
_view = _layoutInflater.inflate(R.layout.album_item_layout, parent, false);
viewHolder = new ViewHolder(_view);
_view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _view.getTag();
}
viewHolder.albumName.setText(album.getAlbumDescription());
// here u can set: image to image view & listener to image
// image view could be a button
viewHolder.imageView.setOnClickListener(View.OnClickListener);
return _view;
}
#Override
public void add(Album listElement) {
_albums.add(listElement);
}
#Override
public void addAll(List<Album> listOfElements) {
_albums.addAll(listOfElements);
}
#Override
public void clear() {
_albums.clear();
}
#Override
public void remove(Album listElement) {
_albums.remove(listElement);
}
}
public interface IListAdapter<T> {
void add(T listElement);
void addAll(List<T> listOfElements);
void clear();
void remove(T listElement);
}
above interface serves as helper for adapter list methods

Android listview showing only last element

i created custom listview with text and two buttons, i set up arraylist and adapter but my listview is showing every element as last, for ex. if i add 3 elements: "text1","text2","text3" my listview shows "text3", "text3" "text3" and i dont have any idea why.
private ListView lista;
private List<Piosenka> listaPiosenek;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText) findViewById(R.id.editText1);
lista = (ListView) findViewById(R.id.listView1);
lista.setClickable(true);
}
public void update_listy() throws MalformedURLException, IOException
{
final List<Piosenka> listaPiosenek = new ArrayList<Piosenka>();
listaPiosenek.add(new Piosenka("text1"));
listaPiosenek.add(new Piosenka("text2"));
listaPiosenek.add(new Piosenka("text3"));
PiosenkaAdapter adapter = new PiosenkaAdapter(this, listaPiosenek);
lista.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long index)
{
System.out.println("sadsfsf");
}
});
lista.setAdapter(adapter);
}
Edit: PiosenkaAdapter code
public class PiosenkaAdapter extends BaseAdapter implements OnClickListener {
private Context context;
private List<Piosenka> listapiosenek;
public PiosenkaAdapter(Context context, List<Piosenka> listapiosenek) {
this.context = context;
this.listapiosenek = listapiosenek;
}
public int getCount() {
return listapiosenek.size();
}
public Object getItem(int position) {
return listapiosenek.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup viewGroup) {
Piosenka element = listapiosenek.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.listview_element, null);
}
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Button btnPobierz = (Button) convertView.findViewById(R.id.btnPobierz);
btnPobierz.setFocusableInTouchMode(false);
btnPobierz.setFocusable(false);
btnPobierz.setTag(element);
Button btnPlay = (Button) convertView.findViewById(R.id.btnPlay);
btnPlay.setFocusableInTouchMode(false);
btnPlay.setFocusable(false);
btnPlay.setOnClickListener(this);
btnPlay.setTag(element);
// btnRemove.setId(position);
return convertView;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.btnPobierz:
Piosenka entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
case R.id.btnPlay:
entry = (Piosenka) view.getTag();
listapiosenek.remove(entry);
notifyDataSetChanged();
break;
}
}
}
Try this...
lista.setAdapter(adapter);
adapter.notifyDataSetChanged();
Can you paste you PiosenkaAdapter's code?
I don't know your language, but the Piosenka variable is fetched correctly in getView()
Piosenka element = listapiosenek.get(position);
But this looks strange to me
TextView tvTytul = (TextView) convertView.findViewById(R.id.tvTytul);
tvTytul.setText(Piosenka.getTytul());
Piosenka.getTytul() looks to me as a static method call, where you should do a regular method call to element.getTytul() instead.

Categories

Resources