【问题标题】:How can i create a custom ListView with my xml layout file?如何使用我的 xml 布局文件创建自定义 ListView?
【发布时间】:2017-09-15 19:42:48
【问题描述】:

Java code

list view layout #1

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

【问题讨论】:

  • 问题有点令人困惑,但如果我理解正确,您必须创建一个自定义适配器并扩展您的布局。
  • 是的,你是对的,对不起我的误解
  • 我该怎么做?
  • 您想要为您的 ListView 项目自定义布局?
  • 您可以在互联网上找到许多使用自定义适配器实现ListView 的示例。

标签: java android android-layout listview firebase


【解决方案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添加信息,并通知适配器数据发生变化,就是这样。

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多