0

Пишу приложение под android. Создал отдельное activity для словаря(приложение будет переводить слова из существующей базы и при подключении интернета ещё и онлайн). Создал это activity специально, чтобы отображать весь список слов, которые на данный момент находятся в базе.введите сюда описание изображения Из этого следует то, что на activity пришлось делать динамическую таблицу при помощи Inflater Моя реализация:

public void addRow(String c0, String c1, String c2) {
        TableLayout tableLayout = (TableLayout) findViewById(R.id.table);
        LayoutInflater inflater = LayoutInflater.from(this);
        TableRow tr = (TableRow) inflater.inflate(R.layout.table_row, null);
        TextView tv = (TextView) tr.findViewById(R.id.col1);
        tv.setText(c0);
        tv = (TextView) tr.findViewById(R.id.col2);
        tv.setText(c1);
        tv = (TextView) tr.findViewById(R.id.col3);
        tv.setText(c2);
        ImageButton imageButton = (ImageButton) tr.findViewById(R.id.col4);
        imageButton.setImageDrawable(getResources().getDrawable(R.drawable.ban_day));
        tableLayout.addView(tr);
    }

Реализация таблицы:

<TableRow xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView android:id="@+id/col1"
              android:text=""
              android:layout_width="100dp"
              android:background="@drawable/text_view_border_night"
              android:layout_height="40dp"/>

    <TextView android:id="@+id/col2"
              android:text=""
              android:layout_width="184dp"
              android:background="@drawable/text_view_border_night"
              android:layout_height="40dp"/>

    <TextView android:id="@+id/col3"
              android:text=""
              android:layout_width="60dp"
              android:background="@drawable/text_view_border_night"
              android:layout_height="40dp"/>

    <ImageButton android:id="@+id/col4"
                 android:layout_width="16dp"
                 android:background="@drawable/text_view_border_night"
                 android:layout_height="40dp"/>
</TableRow>

Содержимое xml файла описывающего окно словаря:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scrollbars="none"
        android:layout_weight="1">

    <TableLayout
                 android:id="@+id/table"
                 android:layout_width="fill_parent" android:layout_height="wrap_content">
    </TableLayout>

</ScrollView>

И возникает вопрос, а как обработать нажатие на динамически создаваемые кнопки "удалить из словаря" (это кнопки с крестиком)

1 ответ 1

4

В твоем случае вообще лучше не использовать Tablerow. У тебя будет создаваться под каждую строку новая вьюха и висеть в памяти, и при большом количестве твой завернутый в ScroolView Tablerow еще и будет подлагивать при прокрутке. Recyclerview + Adapter идеально подходит для таких задач, он переиспользует небольшое количество ранее созданных вью.

P.S Если тебе очень важен ответ конкретно на твой вопрос, то вод код:

private TableLayout tableLayout;

public void addRow(String c0, String c1, String c2) {
    LayoutInflater inflater = LayoutInflater.from(this);
    TableRow tr = (TableRow) inflater.inflate(R.layout.table_row, null);
    TextView tv = (TextView) tr.findViewById(R.id.col1);
    tv.setText(c0);
    tv = (TextView) tr.findViewById(R.id.col2);
    tv.setText(c1);
    tv = (TextView) tr.findViewById(R.id.col3);
    tv.setText(c2);
    ImageButton imageButton = (ImageButton) tr.findViewById(R.id.col4);
    imageButton.setImageDrawable(getResources().getDrawable(R.drawable.ban_day));
    imageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(view.getParent() instanceof TableRow) {
                TableRow tableRow = (TableRow) view.getParent();
                tableLayout.removeView(tableRow);
            }
        }
    });
    tableLayout.addView(tr);
}

И вынеси findViewbyid в onCreate()

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.