简体   繁体   中英

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):

在此处输入图像描述

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) {

    }
}

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
        }
    }
}

Add a tag to the view ( setTag() ) can be a number like an id(ex: 1,2,3,... or even the i that you are using in for loop), to each of them then when you click check the tag( getTag() ) like:

@Override
public void onClick(View view) {
     switch(view.getTag()){
     case 1:
       ....
}

or just use a if else statement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM