简体   繁体   中英

How to set data to custom row TextView in ListView

I want to show data which i get from server, in my custom ListView

This is my row_category.xml for custom row

<?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>

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

My Category.java class

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

and my mainactivity with 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());
        }
   }

It is generating list with 3 items as I get it from response 在此处输入图片说明 Now, how can i change the text of each ListView row.

In your CategoryAdapter.java class, change your getView function to:

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

EDIT : To set the text from a List<String>

Change your CategoryAdapter to:

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

And how to get List<String> from a Http request, now that's a whole new question.

You should do that in adapter 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;
        }

In getView() method of your adapter declare and initialise textview and set text to it. and change in your constructor also

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

You'll need to improve your ArrayAdapter .

Currently you're not setting the data to the TextView . Try the following, I didn't test it but it should work.

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

Change this loop in your getdeals method to look like this

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

NOTE

You should consider using the RecyclerView . It's a lot more powerful than ListView and will give you more control over animations of individual list items. You can read up on it here if you'd like

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM