Android ListView with onClick items

前端 未结 9 1593
梦如初夏
梦如初夏 2020-11-27 03:33

I\'m a new programmer and new in Android. I\'m using this example http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/ and it works great.

9条回答
  •  执念已碎
    2020-11-27 03:56

    for what kind of Hell implementing Parcelable ?

    he is passing to adapter String[] so

    • get item(String) at position
    • create intent
    • put it as extra
    • start activity
    • in activity get extra

    to store product list you can use here HashMap (for example as STATIC object)

    example class describing product:

    public class Product {
        private String _name;
        private String _description;
        private int _id
    
        public Product(String name, String description,int id) {
            _name = name;
            _desctription = description;
            _id = id;
        }
    
        public String getName() {
            return _name;
        }
    
        public String getDescription() {
            return _description;
        }
    }
    
    Product dell = new Product("dell","this is dell",1);
    
    HashMap _hashMap = new HashMap<>();
    _hashMap.put(dell.getName(),dell);
    

    then u pass to adapter set of keys as:

    String[] productNames =  _hashMap.keySet().toArray(new String[_hashMap.size()]);
    

    when in adapter u return view u set listener like this for example:

     @Override
     public View getView(int position, View convertView, ViewGroup parent) {
    
         Context context = parent.getContext(); 
    
         String itemName = getItem(position)
    
         someView.setOnClikListener(new MyOnClickListener(context, itemName));
    
     }
    
    
     private class MyOnClickListener implements View.OnClickListener { 
    
         private  String _itemName; 
         private  Context _context
    
         public MyOnClickListener(Context context, String itemName) {
             _context = context;
             _itemName = itemName; 
         }
    
         @Override 
         public void onClick(View view) {
             //------listener onClick example method body ------
             Intent intent = new Intent(_context, SomeClassToHandleData.class);
             intent.putExtra(key_to_product_name,_itemName);
             _context.startActivity(intent);
         }
     }
    

    then in other activity:

    @Override 
    public void onCreate(Bundle) {
    
        String productName = getIntent().getExtra(key_to_product_name);
        Product product = _hashMap.get(productName);
    
    }
    

    *key_to_product_name is a public static String to serve as key for extra

    ps. sorry for typo i was in hurry :) ps2. this shoud give you a idea how to do it ps3. when i will have more time i I'll add a detailed description

    MY COMMENT:

    • DO NOT USE ANY SWITCH STATEMENT
    • DO NOT CREATE SEPARATE ACTIVITIES FOR EACH PRODUCT ( U NEED ONLY ONE)

提交回复
热议问题