如何在 Android 中创建自定义小部件?

How to create custom widget in Android?

我对 Android 编程完全陌生,所以我不太确定我应该搜索什么。我的一项活动中有一个 LinearLayout 元素。

<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:layout_marginTop="15dp"
            android:id="@+id/comment_area"
            android:orientation="vertical"/>

我有一个 JSON 注释数组(userName、commentText、commentDate),我想通过循环将其添加到此 LinearLayout 中。我创建了一个 comment_view.xml 布局并创建了一个扩展 LinearLayout 的 CommentWidget class。坦率地说,我不知道这是否是正确的方法,我也不认为这是因为我无法加载评论。

我的class是

public class CommentWidget extends LinearLayout {
    private String text;

    public void setText(String text) {
        this.text = text;
    }

    public CommentWidget(Context context){
        super(context);
    }
    public CommentWidget(Context context,AttributeSet attrs){
        super(context,attrs);
    }

    @Override
    protected void onFinishInflate(){
        super.onFinishInflate();
        TextView textView=(TextView) findViewById(R.id.comment_text);
        textView.setText(text);
    }
}

我的小部件布局是

<?xml version="1.0" encoding="utf-8"?>
<com.myproject.CommentWidget 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="wrap_content"
        android:id="@+id/comment_text"/>


</com.myproject.CommentWidget>

在 activity 的循环中,我正在调用:

    CommentWidget w = new CommentWidget(this);
    w.setText(comment.getText());
    mtxtArea.addView(w);

但是什么也没有出现。有人能指出我正确的方向吗?我已经正确地将 JSON 接收到一个数组中。

更新:回答 Windsurfer 在下面的回答让我走上了正确的轨道,使用 ListView 来完成我想要完成的事情。通过使用他的 links 和一些搜索,我发现扩展 ArrayAdapter 最适合 JSON 类型的数据。我最终遵循了以下 link

中的教程

https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/

您可以很好地扩展 LinearLayout 来执行此操作,但是 Android 已经有几个为此设计的小部件。我相信您正在寻找一个 ListView 来显示一组数据。与其创建一个新的小部件,不如看看 ListView 是如何工作的。 ListView 使用适配器将数据绑定到它。您仍然需要为单个评论项设计布局,但很多繁重的工作都由 ListView 及其适配器完成。

这里有一些帮助您入门的链接:

http://developer.android.com/guide/topics/ui/layout/listview.html http://www.vogella.com/tutorials/AndroidListView/article.html

看看 Romain Guy 的 this link,他也介绍了 ListViews。