在Android中在动态LinearLayout中添加事件OnClickListener

huangapple go评论76阅读模式
英文:

Add event OnClickListener in dynamically Linear layout in android

问题

如何在每个LinearLayout布局上设置点击事件:

我想要显示一个包含5个元素的列表,如下所示(不要使用RecycleView、ListView):

在Android中在动态LinearLayout中添加事件OnClickListener

但是有一个问题,就是如何捕获每个项目的点击事件,以及如何知道我点击了哪个项目,请帮助我。

这是我的代码:

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

在Android中在动态LinearLayout中添加事件OnClickListener

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

&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
    xmlns:tools=&quot;http://schemas.android.com/tools&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    tools:context=&quot;.MainActivity&quot;&gt;

    &lt;LinearLayout
        android:id=&quot;@+id/layoutRoot&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:orientation=&quot;horizontal&quot;&gt;

    &lt;/LinearLayout&gt;

&lt;/LinearLayout&gt;

item_content.xml

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:orientation=&quot;vertical&quot;
    android:layout_width=&quot;match_parent&quot;
    android:layout_height=&quot;match_parent&quot;
    android:padding=&quot;10dp&quot;
    &gt;
    &lt;ImageView
        android:layout_width=&quot;150dp&quot;
        android:layout_height=&quot;150dp&quot;
        android:src=&quot;@drawable/ic_launcher_background&quot;
        /&gt;
    &lt;TextView
        android:id=&quot;@+id/text&quot;
        android:layout_width=&quot;wrap_content&quot;
        android:layout_height=&quot;wrap_content&quot;
        android:layout_marginTop=&quot;12dp&quot;
        android:textSize=&quot;18sp&quot;
        android:text=&quot;string name&quot;
        /&gt;

&lt;/LinearLayout&gt;

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 &lt;= 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(&quot;Name &quot; + i);
            viewGroup.addView(view);
        }
        // viewGroup.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

    }
}

答案1

得分: 4

在每个循环中的viewitem_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 &lt;= 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(&quot;Name &quot; + 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(&quot;Clicked item at position: &quot; + 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(&quot;Clicked item at position: &quot; + position);
            }
        };

        addView();
    }

    public void addView()
    {
        ViewGroup viewGroup = findViewById(R.id.layoutRoot);
        for (int i = 0; i &lt;= 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(&quot;Name &quot; + 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

huangapple
  • 本文由 发表于 2020年8月5日 22:12:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/63267076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定