【问题标题】:Implement a custom ListView in Android在 Android 中实现自定义 ListView
【发布时间】:2016-10-28 02:16:18
【问题描述】:

我在我的 MainActivity 中创建了一个 listView,并为行布局创建了另一个布局文件,如下所示:

问题是,我该如何实现呢?我在哪里设置所有必须在 text 中的字符串? 注意中的那些?

我在互联网上查看过,但我可以找到与我的 listView 相似的人。

我知道对于字符串我可以使用数组,但是我也可以设置一个 ImageViews 数组吗?

如果你能给我一个详细的答案,解释我如何在我的 listView 中“放东西”,我将不胜感激

编辑:添加了 row.xml

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

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="text"
        android:textAllCaps="true"
        android:textSize="36sp"
        android:layout_marginTop="10dp"
        android:fontFamily="sans-serif-condensed"
        android:textStyle="bold"
        android:textColor="@color/black" />

    <TextView
        android:id="@+id/note"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text"
        android:text="note note note"
        android:layout_marginTop="2dp"
        android:fontFamily="sans_serif_medium"
        android:textSize="24sp"/>

    <ImageView
        android:layout_width="200dp"
        android:layout_height="140dp"
        android:scaleType="fitCenter"
        android:layout_alignParentEnd="true"/>

</RelativeLayout>

【问题讨论】:

  • 你有没有用getview for listView或者gridView?
  • @janki 不,这是我第一次使用 listView
  • 阅读此tutorial

标签: java android listview android-studio


【解决方案1】:

您要做的是创建一个自定义类并让它扩展 ArrayAdapter 或 BaseAdapter。在它的构造函数中,您可以将文本和图像的字符串数组传递给它。在 getView 方法中,扩充您的自定义行:

 LayoutInflater layoutInflater = LayoutInflater.from(context);
    View yourView = layoutInflater.inflate(R.layout.added_row, parent, false);

然后,您可以使用传递给设置值的数组来设置行的值:

TextView text = (TextView) yourView.findViewById(R.id.text);
text.setText(text[position]);

【讨论】:

    【解决方案2】:

    你应该创建

    1. 一个类,(让我们将其命名为DataModel.java,您可以给出您希望的任何名称)代表您的数据:String text, note, image url; 以及getter 和setter 方法。
    2. 一个扩展ArrayAdapter的类。覆盖getView() 方法。将ArrayList&lt; DataModel &gt; 传递给创建的自定义数组适配器。创建构造函数并调用super调用ArrayAdapter的构造函数":ArrayAdapter(Context context, int resource, List&lt;T&gt; objects)

    在 getView 方法中填充行布局并设置数据[将 Arraylist 中的索引与 getView 方法的位置参数匹配]

    根据您的问题,我建议您更多地研究view holder patternRecyclerView,这将帮助您了解事情的运作方式以及应该如何有效地完成它们。

    【讨论】:

      【解决方案3】:

      使用自定义适配器方法在自定义列表视图中加载数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-21
        • 1970-01-01
        • 2012-06-01
        • 2011-09-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多