F
F
feniksdv2020-08-05 20:49:00
Java
feniksdv, 2020-08-05 20:49:00

How to get ID from dynamic View?

Hello everyone, in my application, elements are displayed dynamically on the screen, and I can also remove these dynamic elements. I need to somehow bind to the element being deleted, get an ID or getText, at least get something unique from the element being deleted.

MainActivity.java

package ru.test

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    //Логи для отладки
    private static final String TAG = "myLogs";

    //счетчик чисто декоративный для визуального отображения edittext'ov
    private int counter = 0;

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

        Button addButton = (Button) findViewById(R.id.button);

        //находим наш linear который у нас под кнопкой add edittext в activity_main.xml
        final LinearLayout linear = (LinearLayout) findViewById(R.id.linear);
        addButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                counter++;

                //берем наш кастомный лейаут находим через него все наши кнопки и едит тексты,
                // задаем нужные данные
                final View view = getLayoutInflater().inflate(R.layout.custom, null);
                Button deleteField = (Button) view.findViewById(R.id.button2);
                EditText text = (EditText) view.findViewById(R.id.editTextCustom);
                text.setText("Some text" + counter);
                //добавляем елементы в linearlayout
                linear.addView(view);

                //Удаляем элемент
                deleteField.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try {
                            //получаем родительский view и удаляем его
                            ((LinearLayout) view.getParent()).removeView(view);
                            Log.e(TAG, "Delete = "+ view.getId());
                        } catch (IndexOutOfBoundsException ex) {
                            ex.printStackTrace();
                        }
                    }
                });
            }
        });
    }
}


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:text="Add edittext" />

    <LinearLayout
        android:id="@+id/linear"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:layout_alignEnd="@+id/button"
        android:layout_alignRight="@+id/button"
        android:orientation="vertical"/>
</RelativeLayout>


custom.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editTextCustom"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_toLeftOf="@+id/button2"
        android:layout_toStartOf="@+id/button2"
        android:text="Some text" />

    <Button
        android:id="@+id/button2"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editTextCustom"
        android:layout_alignParentRight="true"
        android:layout_marginRight="56dp"
        android:text="X" />

    <Switch
        android:id="@+id/switch1"
        android:layout_width="50dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/button2"
        android:layout_marginStart="-53dp"
        android:layout_marginBottom="9dp"
        android:layout_toEndOf="@+id/button2"
        android:text="" />
</RelativeLayout>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Neonoviiwolf, 2020-08-06
@feniksdv

add id to your views

D
Dmtm, 2020-08-06
@Dmtm

you can add any information to the tags to the view (setTag/getTag)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question