英文:
Add event OnClickListener in dynamically Linear layout in android
问题
如何在每个LinearLayout布局上设置点击事件:
我想要显示一个包含5个元素的列表,如下所示(不要使用RecycleView、ListView):
但是有一个问题,就是如何捕获每个项目的点击事件,以及如何知道我点击了哪个项目,请帮助我。
这是我的代码:
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>
以及Java代码:
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);
            view.setOnClickListener(this);
        }
    }
    @Override
    public void onClick(View view) {
        // 在这里处理点击事件
    }
}
英文:
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) {
    }
}
答案1
得分: 4
在每个循环中的view(item_content.xml)中,您可以添加一个带有位置的tag。然后在onClick中,您可以获取该标记并解析为Integer。
示例:
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()); //为每个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);
            }
        };
    }
}
或者第二个类似的选项,使用变量而不是函数:
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); //为每个item_content设置点击
        }
    }
}
英文:
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);
            }
        };
    }
}
<hr>
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
        }
    }
}
答案2
得分: 1
为视图添加标签(setTag())可以是一个数字,比如一个ID(例如:1、2、3等,甚至是您在for循环中使用的i),然后当您单击时,检查标签(getTag()),如下所示:
@Override
public void onClick(View view) {
    switch(view.getTag()){
        case 1:
            // ...
    }
}
或者只需使用if else语句。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。



评论