Search code examples
javaandroid-studioclick

android - java get id of the item just clicked without set "onClick" to the item


How do I get an item id when I click on it without setting an "onClick" event in the xmk file?

I tried that:

private View.OnClickListener globalClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int clickedPosition = (int) v.getTag();
                // do something with position
            }
        }

But i don't understand how to use it


Solution

  • Hello! Rebuild the method as follows:

        private View.OnClickListener globalClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    
                }
    }
    

    Well, to get the target ID that you click, it is better to first define the attribute android:tag="target_id" in the XML file, and then access it within the called method when the target is clicked, using the v.getTag(). Of course, you can also get the clicked ID via v.getId() without doing so. You can check the ID from: use if (v.getTag () == R.id.target_id), or parse it as follows:

    String viewID = getResources (). GetResourceName (v.getId ())