@feniksdv

Как получить ID у динамического View?

Всем привет, в моем приложении на экран выводятся динамически элементы, а также я могу удалять эти динамические элементы. Мне нужно как то привязаться к удаляемому элементу, получить ID или getText, хоть что-нибудь получить уникальное от удаляемого элемента.

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>
  • Вопрос задан
  • 384 просмотра
Решения вопроса 1
@Neonoviiwolf
Flutter developer
добавьте id к вашим view
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
@Dmtm
Android
можно в теги к view добавлять любую информацию (setTag/getTag)
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы