Клонирование / дублирование линейного макета XML, в цикле, с динамическими данными - Android Studio - PullRequest
0 голосов
/ 29 октября 2018

Скриншот моего макета Это все мое занятие, три элемента в списке, которые вы видите, - это три разных LinearLayouts. Я хочу скопировать Layout в multi через цикл, поместив динамические данные, например: 1) Хафиз уль хак, кобель, пак 2) Али, Мале, Индия 3) Хина, Женский, Пак

Извините за глупые примеры, но главное, что я хочу узнать, как копировать LinearLayout, вы можете использовать строковый массив с циклом for, например: for (пользователь в пользователях) {Blah ... Blah ...}

1 Ответ

0 голосов
/ 29 октября 2018

Вы должны использовать RecyclerView .

Пример:

Модель данных

public class Person {
    private String name;
    private int gender;
    private String location;

    public Person(String name, int gender, String location) {
        this.name = name;
        this.gender = gender;
        this.location = location;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getGender() {
        return gender;
    }

    public void setGender(int gender) {
        this.gender = gender;
    }

    public String getLocation() {
        return location;
    }

    public void setLocation(String location) {
        this.location = location;
    }
}

Адаптер RecyclerView

public final class PeopleAdapter extends RecyclerView.Adapter<PeopleAdapter.PersonHolder> {
    private Context context;
    private List<Person> people;

    public PeopleAdapter(Context context, List<Person> people) {
        this.context = context;
        this.people = people;
    }

    @Override
    public PeopleAdapter.PersonHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new PersonHolder(LayoutInflater.from(context).inflate(R.layout.item_person, parent, false));
    }

    @Override
    public void onBindViewHolder(PeopleAdapter.PersonHolder holder, int position) {
        Person person = people.get(position);
        holder.txtPersonName.setText(person.getName());
        if(person.getGender() == 0)
            holder.txtGender.setText("Male");
        else if(person.getGender() == 1)
            holder.txtGender.setText("Female");
        else
            holder.txtGender.setText("_____");
        holder.txtPersonLocation.setText(person.getLocation());
    }

    @Override
    public int getItemCount() {
        return people.size();
    }

    final class PersonHolder extends RecyclerView.ViewHolder {
        private AppCompatTextView txtPersonName;
        private AppCompatTextView txtGender;
        private AppCompatTextView txtPersonLocation;

        PersonHolder(View itemView) {
            super(itemView);

            txtPersonName = itemView.findViewById(R.id.txt_person_name);
            txtGender = itemView.findViewById(R.id.txt_gender);
            txtPersonLocation = itemView.findViewById(R.id.txt_person_location);
        }
    }
}

В вашей деятельности / фрагмент

private RecyclerView rvPeople;
private PeopleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    rvPeople = findViewById(R.id.rv_people);
    List<Person> people = new ArrayList<>(3);
    ...
    adapter = new PeopleAdapter(this, people);
    ...
    rvPeople.setAdapter(adapter);
}

Ваша раскладка . Я обычно использую следующий код для решения вашей задачи. Вы можете изменить поля, отступы, размер изображения и необходимость стилизовать текстовые представления.

 <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@android:color/white"
    android:padding="8dp">

    <androidx.appcompat.widget.AppCompatImageView
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:src="@drawable/ic_launcher_background" />

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation="vertical"
        android:layout_marginStart="16dp">

        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-medium"
            tools:text="Text 1" />

        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:text="Text 1" />

        <androidx.appcompat.widget.AppCompatTextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:text="Text 1" />

    </LinearLayout>

</LinearLayout>
...