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

时间:2015-06-19 12:14:04

标签: android android-listview android-adapter

我想在我的自定义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.java类

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;
    }
}

以及我对listview的主要活动

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个项目的生成列表 enter image description here 现在,我该如何更改每个ListView行的文本。

5 个答案:

答案 0 :(得分:0)

CategoryAdapter.java课程中,将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>,现在这是一个全新的问题。

答案 1 :(得分:0)

答案 2 :(得分:0)

你应该在适配器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;
        }

答案 3 :(得分:0)

在适配器的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;
        }

答案 4 :(得分:0)

您需要改善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