如何使用我的xml布局文件创建自定义ListView?

时间:2017-09-15 19:42:49

标签: java android android-layout listview firebase

Java code

list view layout #1

如何插入更改ListView的图形,将此布局文件添加到列表视图中?我应该在我的java代码中写一下我的ListView的每一行就像我的布局文件一样。谢谢大家!!

1 个答案:

答案 0 :(得分:1)

首先,您需要为所需的自定义行创建xml(custom_row.xml):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

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

然后您需要创建自定义适配器:

public class CustomAdapter extends BaseAdapter {
Context context;
List<String> textArray;
LayoutInflater inflater;

public RutinaAdapter(Context context, List<String> textarray) {
    this.context = context;
    inflater = LayoutInflater.from(context);
    this.textArray = textarray;

}

@Override
public int getCount() {
    return textArray.size();
}

@Override
public Object getItem(int position) {
    return textArray.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewGroup vg;

    if (convertView != null) {
        vg = (ViewGroup) convertView;
    } else {
        vg = (ViewGroup) inflater.inflate(R.layout.custom_row, null);
    }

    String text = textArray.get(position);

    final TextView text = ((TextView) vg.findViewById(R.id.text));

    return vg;
} }

然后您需要将适配器添加到ListView:

list = (ListView) view.findViewById(R.id.list);  
CustomAdapter adapter = new CustomAdapter(getContext(),textArray);
list.setAdapter(adapter1);

向textArray添加信息,并通知适配器数据已更改,就是这样。