Search code examples
javaandroidkotlinandroid-linearlayoutonclicklistener

Add event OnClickListener in dynamically Linear layout in android


How to set the click event on each layout is in LinearLayout:

I want to display a list of 5 elements as shown below (Do not use RecycleView, ListView):

enter image description here

But there was a problem catching the click event for each item, and how to know which item I clicked on, please help me.

This my code:

activity_main.xml

<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="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/layoutRoot"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

    </LinearLayout>

</LinearLayout>

item_content.xml

<?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"
    android:padding="10dp"
    >
    <ImageView
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:src="@drawable/ic_launcher_background"
        />
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="12dp"
        android:textSize="18sp"
        android:text="string name"
        />

</LinearLayout>

And Java Code:

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addView();
    }

    public void addView() {
        ViewGroup viewGroup = findViewById(R.id.layoutRoot);
        for (int i = 0; i <= 5; i++) {
            LayoutInflater inflater = (LayoutInflater) getApplicationContext().
                    getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.item_content, null);
            TextView textView = view.findViewById(R.id.text);
            textView.setText("Name " + i);
            viewGroup.addView(view);
        }
        // viewGroup.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

    }
}

Solution

  • For each view in a loop (item_content.xml) You can add tag with the position. Then in onClick You can get that tag and parse to Integer.

    Example:

    public class MainActivity extends AppCompatActivity
    {
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            addView();
        }
    
        public void addView()
        {
            ViewGroup viewGroup = findViewById(R.id.layoutRoot);
            for (int i = 0; i <= 5; i++)
            {
                LayoutInflater inflater = (LayoutInflater) getApplicationContext().
                        getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.item_content, null);
                view.setTag(Integer.toString(i));
                TextView textView = view.findViewById(R.id.text);
                textView.setText("Name " + i);
                viewGroup.addView(view);
    
                view.setOnClickListener(clickInLinearLayout()); //setting click to each item_content
            }
        }
    
        private View.OnClickListener clickInLinearLayout()
        {
            return new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Integer position = Integer.parseInt(v.getTag().toString());
                    System.out.println("Clicked item at position: " + position);
                }
            };
        }
    }
    

    Or the second similar option with variable not function:

    public class MainActivity extends AppCompatActivity
    {
        private View.OnClickListener clickInLinearLayout;
    
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            clickInLinearLayout = new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    Integer position = Integer.parseInt(v.getTag().toString());
                    System.out.println("Clicked item at position: " + position);
                }
            };
    
            addView();
        }
    
        public void addView()
        {
            ViewGroup viewGroup = findViewById(R.id.layoutRoot);
            for (int i = 0; i <= 5; i++)
            {
                LayoutInflater inflater = (LayoutInflater) getApplicationContext().
                        getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.item_content, null);
                view.setTag(Integer.toString(i));
                TextView textView = view.findViewById(R.id.text);
                textView.setText("Name " + i);
                viewGroup.addView(view);
    
                view.setOnClickListener(clickInLinearLayout); //setting click to each item_content
            }
        }
    }