如何在ListView中设置数据到自定义行TextView

How to set data to custom row TextView in ListView

我想在我的自定义 ListView 中显示从服务器获取的数据

这是我的 row_category.xml 自定义行

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

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:src="@drawable/messenger_bubble_large_blue" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginLeft="10dp" >

        <TextView
            android:id="@+id/txtTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:text="Large Text"
            android:textAppearance="?android:attr/textAppearanceLarge" />

    </LinearLayout>

</LinearLayout>

我的CategoryAdapter.java

public class CategoryAdapter extends ArrayAdapter{
    private LayoutInflater inflater;

    public CategoryAdapter(Activity activity, ArrayList<Category> items){
        super(activity, R.layout.row_category, items);
        inflater = activity.getWindow().getLayoutInflater();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        return inflater.inflate(R.layout.row_category, parent, false);
    }
}

我的Category.javaclass

public class Category {
    private String name,url;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

我的主要活动是列表视图

private ListView categorylist;
    private CategoryAdapter categoryitemadapter;
    private Intent intent;
    JSONArray jArray;
    ArrayList<Category> list;
    String uri="http://demopurpose.com/Quiz/API/";
    InputStream is;
    JSONObject json_data;
    int len;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_categories);

         list = new ArrayList<Category>();
         categoryitemadapter = new CategoryAdapter(this, list);
         getdata();
         setListAdapter(categoryitemadapter);
         categoryitemadapter.notifyDataSetChanged();
    }
    public void getdata(){
        Thread t = new Thread() {
            public void run() {
                getdeals();
            }
            };
        t.start();

    }

    public void getdeals() {

        String result = "";

        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(uri+"getcategories.php");
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                is = entity.getContent();
        }
        catch(Exception e){
                Log.e("log_tag", "Error in http connection "+e.toString());
        }
        //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                }
                is.close();

                result=sb.toString();
                Log.i("result...",result);
        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }

        //parse json data
        try{
                jArray = new JSONArray(result);
                //Log.i("result", result);
                len=jArray.length();


                        runOnUiThread(new Runnable() {
                            public void run() {
                                try{
                                    Category c = new Category();

                                    for(int i=0;i<jArray.length();i++){
                                        json_data = jArray.getJSONObject(i);
                                        c.setName(json_data.getString("name"));
                                        list.add(c);
                                        categoryitemadapter.notifyDataSetChanged();
                                    }
                                }
                                catch(JSONException je){
                                    je.printStackTrace();
                                }
                            }
                        });

        }
        catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
   }

它正在生成包含 3 个项目的列表,因为我从响应中得到它 现在,我如何更改每个 ListView 行的文本。

在您的 CategoryAdapter.java class 中,将您的 getView 函数更改为:

@Override
public View getView(int position, View convertView, ViewGroup parent){
    View v = inflater.inflate(R.layout.row_category, parent, false);
    TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
    txtTitle.setText("The text you want");
    return v;
}

编辑:设置来自List<String>

的文本

将您的 CategoryAdapter 更改为:

public class CategoryAdapter extends ArrayAdapter{
    private LayoutInflater inflater;
    private List<String> titleList;

    public CategoryAdapter(Activity activity, ArrayList<Category> items, List<String> titleList){
        super(activity, R.layout.row_category, items);
        inflater = activity.getWindow().getLayoutInflater();
        this.titleList = titleList
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent){
        View v = convertView
        if(v == null)
            v = inflater.inflate(R.layout.row_category, parent, false);
        TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle);
        txtTitle.setText(titleList.get(position));
        return v;
    }
}

以及如何从 Http 请求中获取 List<String>,这是一个全新的问题。

您必须在 getView() 中更改每一行的文本视图数据。看到这个 http://androidexample.com/How_To_Create_A_Custom_Listview_-_Android_Example/index.php?view=article_discription&aid=67&aaid=92

您应该在适配器 getview 中执行此操作

@Override
public View getView(int position, View convertView, ViewGroup parent){
    View row = convertView;
            if (row == null) {
                LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.row_category, parent, false);
            }
            TextView rowText = (TextView) row.findViewById(R.id.txtTitle);

            rowText.setText("Custom Text");

            return row;
        }

在您的适配器的 getView() 方法中声明并初始化 textview 并为其设置文本。并改变你的构造函数

     ArrayList<Category> items;

     public CategoryAdapter(Activity activity, ArrayList<Category> items){
        super(activity, R.layout.row_category, items);
        inflater = activity.getWindow().getLayoutInflater();
        this.items = items;
    }

    @Override
        public View getView(int position, View convertView, ViewGroup parent){
          if (convertView == null) {
                convertView = (View) inflater.inflate(R.layout.row_category, parent, false);
          }
          TextView textView = (TextView) convertView
                    .findViewById(R.id.txtTitle);
          textView.setText(items.get(position).getName());
         return convertView;
        }

您需要提高 ArrayAdapter

目前您没有将数据设置到 TextView。试试下面的方法,我没有测试过,但应该可以。

 public class CategoryAdapter extends ArrayAdapter {

    private LayoutInflater inflater;

    public CategoryAdapter(Activity activity, ArrayList<Category> items){
        super(activity, R.layout.row_category, items);

        inflater = activity.getWindow().getLayoutInflater();
    }

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

        ViewHolder viewHolder;

        if (convertView == null) {

            viewHolder = new ViewHolder();

            convertView = inflater.inflate(R.layout.row_category, parent, false);
            viewHolder.textTile = (TextView) convertView.findViewById(R.id.txtTitle);

            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        Category category = (Category) getItem(position);
        viewHolder.textTile.setText(category.getName());

        return convertView;
    }

    public void refresh(ArrayList<Category> items) {
        clear();
        addAll(items);
        notifyDataSetChanged();
    }

    private class ViewHolder {
        public TextView textTile;
    }
}

getdeals 方法中的循环更改为如下所示

try {
    Category c = new Category();

    for(int i=0;i<jArray.length();i++){
        json_data = jArray.getJSONObject(i);
        c.setName(json_data.getString("name"));
        list.add(c);
    }

    categoryitemadapter.refresh(list);
} catch(JSONException je){
    je.printStackTrace();
}

注意

您应该考虑使用 RecyclerView。它比 ListView 强大得多,可以让您更好地控制单个列表项的动画。如果您愿意,可以继续阅读 here