Как мне настроить таргетинг идентификатора макета от Java inflate - PullRequest
0 голосов
/ 08 марта 2020

Я новичок в Android программировании ... Я хочу программно добавить макеты в ScrollView, поэтому я использую этот код ниже

for(int i = 0; i < 10; i++){
    LinearLayout myLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.my_layout, null);
    ImageView imgView = (ImageView) getLayoutInflater().inflate(R.layout.img_view, null);
    //set ImageView source
    TextView txtView = (TextView) getLayoutInflater().inflate(R.layout.txt_view, null);
    //set TextView text
    myLayout.addView(imgView);
    myLayout.addView(txtView);
    scrllView.addView(myLayout);
}

Приведенный выше код работает нормально. Но я хочу знать, есть ли более короткий и простой способ сделать это, потому что мой код будет громоздким, и мне придется создавать файл макета XML для каждого представления, которое я хочу добавить

Может быть Я думаю, что вместо создания нескольких файлов XML в папке макета, у меня может быть только один файл XML, имеющий LinearLayout в качестве родителя с ImageView и TextView в качестве дочерних элементов, поэтому my_layout.xml будет выглядеть вот так

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

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:id="@+id/img"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/txt"/>

</LinearLayout>

Тогда я могу надуть файл my_layout.xml в своем коде Java и добавить цель ImageView и TextView, используя их IDs

LinearLayout myLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.my_layout, null);
ImageView imgView = //find the child of myLayout (ImageView) with ID of img
//set ImageView source
TextView txtView = //find the child of myLayout (TextView) with ID of txt
//set TextView text

I хочу знать, можно ли этого достичь.

1 Ответ

0 голосов
/ 09 марта 2020

Хорошо ... Я наконец-то получил то, что искал. Код ниже работал отлично

LinearLayout myLayout = (LinearLayout) getLayoutInflater().inflate(R.layout.my_layout, null);
ImageView imgView = myLayout.findViewById(R.id.img);
//set ImageView source
TextView txtView = myLayout.findViewById(R.id.txt);
//set TextView text
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...