簡體   English   中英

如何在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"/>

我有一個要通過循環添加到此LinearLayout中的注釋(用戶名,commentText,commentDate)的JSON數組。 我創建了comment_view.xml布局,並創建了一個LinearLine擴展的CommentWidget類。 坦白說,我不知道這是否是正確的方法,我也不認為這是因為我無法加載評論。

我的課是

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>

在我正在調用的活動的循環中:

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

但是什么都沒有出現。 有人可以指出我正確的方向嗎? 我已經正確地將JSON接收到數組中了。

更新:答案下面的Windsurfer答案使我走上了正確的道路,將ListView用於我要完成的工作。 通過他的鏈接和一些搜索,我發現擴展ArrayAdapter最適合JSON類型數據。 我最終通過以下鏈接關注了本教程

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的這個鏈接 ,他也介紹了ListViews。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM