Get the position of view in LinearLayout (Android)

12,475

Solution 1

You can use the View's tag;

for (int position=0; position<items.size(); position++) {
    v.setTag(position);
}

and in the onClick(View v)

public void onClick(View v) {
    int position = 0;
    if (v.getTag() instanceof Integer) {
       position = (Integer) v.getTag();
    }
}

Solution 2

Can you have

v.setTag(items.get(position).getId();

and then in onClick

public void onClick(View v) {
  int id= v.getTag();
}
Share:
12,475

Related videos on Youtube

Danil Onyanov
Author by

Danil Onyanov

Android, Java, Zend Framework, jQuery, HTML, CSS, PHP, MySQL, SQLite

Updated on June 04, 2022

Comments

  • Danil Onyanov
    Danil Onyanov almost 2 years

    A had a custom ListView recently. Then I had to display all the list items without scrollbar. Following the method to place items in LinearLayout I changed my code but I can't bind onClickListener to new layout. In ListView I used position var to determine what view was touched. But in LinearLayout onClick callback hasn't position parameter.

    Here is my BasketActivity.class:

    package ru.**.**;
    
    public class BasketActivity extends Activity {
    
        ArrayList<Item> items = new ArrayList<Item>();
        SQLiteDatabase database;
        Map<String, ?> all;
        ItemAdapter adapter;
        Item item2delete;
        View deletingView;
    
        private SharedPreferences settings;
        private SharedPreferences settings2;
        private Basket basket;
        TextView basketSum;
        private int position2delete;
        private Map<String, ?> all2;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_basket);
    
            <..cutted..>
    
            settings = getSharedPreferences("basket", 0);
            settings2 = getSharedPreferences("price", 0);
            basket = new Basket(settings, settings2);
            all = basket.getList();
    
            LinearLayout l1 = (LinearLayout) findViewById(R.id.l1);
            MyDBAdapter myDBAdapter = new MyDBAdapter(getBaseContext());
            myDBAdapter.open();
            Cursor itemCursor = myDBAdapter.getItemsInBasket(all);
            while (itemCursor.moveToNext()) {
    
                String[] columns = itemCursor.getColumnNames();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < columns.length; i++) {
                    sb.append(columns[i]);
                }
    
                Item item = new Item();
                item.setId(itemCursor.getString(0));
                item.setArticul(itemCursor.getString(MyDBSchema.ITEM_ARTICUL));
                item.setTitle(itemCursor.getString(MyDBSchema.ITEM_TITLE));
                item.setPrice(itemCursor.getInt(MyDBSchema.ITEM_PRICE));
                item.setPic80(itemCursor.getString(MyDBSchema.ITEM_PIC80));
                item.setPic300(itemCursor.getString(MyDBSchema.ITEM_PIC300));
                item.setMessage(itemCursor.getString(MyDBSchema.ITEM_MESSAGE));
                item.setColor(itemCursor.getString(MyDBSchema.ITEM_COLOR));
                item.setColorpos(itemCursor.getString(MyDBSchema.ITEM_COLORPOS));
                items.add(item);
            }
            itemCursor.close();
            myDBAdapter.close();
    
            for (int position=0; position<items.size(); position++) {
                LayoutInflater inflater = getLayoutInflater();
                View v = inflater.inflate(R.layout.list_basket, null);
    
                final Item i = items.get(position);
                    if (i != null) {
                        Item ei = (Item) i;
    
                        final TextView title = (TextView) v.findViewById(R.id.title);
                        if (title != null) title.setText(ei.title);
    
                        final TextView articul = (TextView) v.findViewById(R.id.articul);
                        if (articul != null) articul.setText(ei.articul);
    
                        TextView payed = (TextView) v.findViewById(R.id.payed);
                        if (payed != null) payed.setVisibility(TextView.GONE);
    
                        TextView status = (TextView) v.findViewById(R.id.status);
                        if (status != null) status.setVisibility(TextView.GONE);
    
                        Context context = getBaseContext();
                        ProgressBar p = new ProgressBar(context);
                        p.setIndeterminate(true);
                        Drawable d = p.getIndeterminateDrawable();          
                        WebImageView wiv = (WebImageView) v.findViewById(R.id.pic80);
                        wiv.setImageWithURL(context, ei.pic80, d);
    
                        final TextView price = (TextView) v.findViewById(R.id.price);
                        if (price != null) price.setText(ei.price_valid);
    
                        final TextView quant = (TextView) v.findViewById(R.id.quant);
                        if (quant != null) {
                            int q = (Integer) all.get(ei.articul);
                            if (q > 1) {
                                quant.setText("x "+q+" шт.");
                            }
                        }
    
                    }
                    v.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            deletingView = v;
                            int position = 0; //The order number of the view should be here!
                            Item item = (Item) items.get(position);
                            item2delete = item;
                            position2delete = position;
    
                            AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
                            builder.setMessage(getString(R.string.suredelete))
                                    .setCancelable(false)
                                    .setPositiveButton(getString(R.string.yes),
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int id) {
                                                    BasketActivity.this.removeItem();
                                                    deletingView.setVisibility(View.GONE);
                                                }
                                            })
                                    .setNegativeButton(getString(R.string.no),
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog, int id) {
                                                    dialog.cancel();
                                                }
                                            });
                            AlertDialog alert = builder.create();
                            alert.show();
                        }
                    });
                    l1.addView(v);
            }
    
    
            basketSum = (TextView) findViewById(R.id.basketsum);
            basketSum.setText(Html.fromHtml(getString(R.string.basketsum) + ": <b>"
                    + basket.getBasketPriceValid() + "</b>"));
        }
    
        protected void removeItem() {
            basket.remove(item2delete);
            Context context = getApplicationContext();
            CharSequence text = getText(R.string.item_deleted);
            int duration = Toast.LENGTH_SHORT;
            Toast toast = Toast.makeText(context, text, duration);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
            basketSum.setText(Html.fromHtml(getString(R.string.basketsum) + ": <b>"
                    + basket.getBasketPriceValid() + "</b>"));
            items.remove(position2delete);
        }
    }
    

    My question is how to get view's position at onClick(View v)?

  • Danil Onyanov
    Danil Onyanov over 11 years
    Thanks. I prefer your way to define 'position'
  • AdrianoCelentano
    AdrianoCelentano over 9 years
    i think you have to cast like this (Integer) v.getTag()
  • Blackbelt
    Blackbelt over 9 years
    the cast is definitely necessary @AdrianoCelentano. Thanks
  • Gray
    Gray over 3 years
    Since you are formally posting an answer to an older question. It would be most helpful that you support your purported answer with some code and the output that results from using your code. You can support your answer with a copy and paste of the code or even a screen print if the output code cannot be copied.