简体   繁体   English

如何在 View for BaseAdapter getView() 方法中使用 XML 设置布局

[英]How to set layout with XML in View for BaseAdapter getView() method

The following Java code (from https://www.intertech.com/Blog/android-adapters-adapterviews/ ) is from getView(), a method implementation from a Android Adapter class, and it builds a View in Java to populate items on a List.以下 Java 代码(来自https://www.intertech.com/Blog/android-adapters-adapterviews/ )来自 getView(),Android Adapter 类的方法实现,它在 Java 中构建了一个视图来填充项目在一个列表中。 I get how it works, but the same page says it can be built using an XML file, which makes sense to me, but I'm unable to find any examples.我知道它是如何工作的,但同一个页面说它可以使用 XML 文件构建,这对我来说很有意义,但我找不到任何示例。 I understand how to use XML resource files to set Activity layout using setContentView().我了解如何使用 XML 资源文件使用 setContentView() 设置 Activity 布局。 But how would I invoke an XML resource file to build the View in the getView() method?但是我将如何调用 XML 资源文件来在 getView() 方法中构建视图?

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        Context context = parent.getContext();
        LinearLayout view = new LinearLayout(context);
        view.setOrientation(LinearLayout.HORIZONTAL);
        view.addView(new CheckBox(context));
        TextView nameTextView = new TextView(context);
        nameTextView.setText(courses.get(position).getName());
        nameTextView.setPadding(0, 0, 10, 0);
        view.addView(nameTextView);
        TextView parTextView = new TextView(context);
        parTextView.setText(Integer.toString(courses.get(position).getPar()));
        view.addView(parTextView);
        return view;
    }
    return convertView;
}

like this像这样

item_test.xml item_test.xml

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

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="name" />
</LinearLayout>

adapter适配器

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Holder holder; // use holder
    if (convertView == null) {
        convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_test, parent, false);
        holder = new Holder(convertView);
        convertView.setTag(holder);
    } else {
        holder = (Holder) convertView.getTag();
    }
    holder.name.setText("name");
    return convertView;
}

public class Holder {
    private TextView name;

    public Holder(View view) {
        name = view.findViewById(R.id.name);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM