如何创建自定义适配器列表视图 [英] How to create a listview with custom adapter

查看:145
本文介绍了如何创建自定义适配器列表视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code:

package com.example.myfirstapp;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;

public class FetchData extends Activity {
    private TextView textView;
    private JSONObject jObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fetch_data);
        textView = (TextView) findViewById(R.id.TextView1);

        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        readWebpage(message);
    }

    private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {
            String response = "";
            for (String url : urls) {
                DefaultHttpClient client = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                try {
                    HttpResponse execute = client.execute(httpGet);
                    InputStream content = execute.getEntity().getContent();

                    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                    String s = "";
                    while ((s = buffer.readLine()) != null) {
                        response += s;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return response;
            mParseResponse(response);
        }

        @Override
        protected void onPostExecute(String result) {
            textView.setText(result);
        }
    }

    public void readWebpage(String message) {

        //Intent intent = getIntent();
        //String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(new String[] {message});

    }

    ArrayList<String> year, title, details, director, rating, cover;
    // For Parse Login Response From Server
    public void mParseResponse(String response) throws UnknownHostException { 

        year=new ArrayList<String>();
        title=new ArrayList<String>();
        details=new ArrayList<String>();
        director=new ArrayList<String>();
        rating=new ArrayList<String>();
        cover=new ArrayList<String>();

        try {
            JSONObject jObject = new JSONObject(response);
            JSONObject jsonobjresults = jObject.getJSONObject("results");
            JSONArray jsonarrayresult = jsonobjresults.getJSONArray("result");
            for(int i=0;i<jsonarrayresult.length(); i++){
                JSONObject mJsonObj = jsonarrayresult.getJSONObject(i);
                year.add(mJsonObj.getString("year"));
                title.add(mJsonObj.getString("title"));
                details.add(mJsonObj.getString("details"));
                director.add(mJsonObj.getString("director"));
                rating.add(mJsonObj.getString("rating"));
                cover.add(mJsonObj.getString("cover"));
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

我越来越困惑,如何创建一个自定义的适配器。是的,我已经thoeugh教程,但仍然混乱退出。另外,我有一个错误,当我做出mParseResponse打电话。任何想法,我错了,我应该如何实现列表视图?

I am getting confused as to how to create a custom adapter. Yes, i have gone thoeugh tutorials but confusion still exits. Plus, I am having an error when i make a call to mParseResponse. Any ideas where I am going wrong and how should i implement list view?

推荐答案

也许这种简单的来样定制适配器列表视图会得到你的脚这个东西。
主要活动

Perhaps this simple sample custom adapter listview will get on your feet with this stuff. The main activity

public class MainActivity extends Activity {

    String [] children = {
            "Award 1",
            "Award 2",
            "Award 3",
            "Award 4",
            "Award 5",
            "Award 6",
            "Award 7",
            "Award 8",
            "Award 9",
            "Award 10",
            "Award 11",
            "Award 12",
            "Award 13",
            "Award 14",
            "Award 15"};

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView list = (ListView) findViewById(R.id.listview);
        CustomAdapter adapter = new CustomAdapter(this, children);
        list.setAdapter(adapter);
    }

自定义适配器

public class CustomAdapter extends BaseAdapter {
//  you could have instead extend ArrayAdapter if you wished, i find it less fickle but less flexible
//  extends CursorAdapter is available too for listviews backed by cursors
    private LayoutInflater inflator;
    private String[] children;

    public CustomAdapter(Context context, String[] children) {
        super();
//      pass what you need into the constructor. in this case the string array and context.
//      do as much as you can here and not in getView because getView acts for each row
//      --> it will greatly help performance
        this.children = children;
        inflator = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
//      v----  your listview won't show anything if this is left default (at 0).  
        return children.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
//      getView is where all the action takes place
//      first inflate the xml that holds the row and somehow connect it to convertView, the parameter
//      checking if null allows these views to be recycled when they go off-screen not just made one per row
//      ---> it will greatly help performance 
        if (convertView == null) {
            convertView = inflator.inflate(R.layout.row, parent, false);
        }
//      then find the individual views with this xml (everything just like onCreate)
        ImageView img = (ImageView) convertView.findViewById(R.id.imageView1);
        TextView tv = (TextView) convertView.findViewById(R.id.textView1);
//      then perform your actions to the your views
//      each textView is set to an element in the array based on position. this is my listview limiter here.
//      each imageview is set to the same picture but you should now have an idea how to set different images (based on position)
//      using listview position in correspondence with array/arraylist positions is a very useful technique.
        img.setImageResource(R.drawable.ic_launcher);
        tv.setText(children[position]);
//      v---- return your view, it's important.
        return convertView;
    }

}

row.xml

row.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="TextView" />

</RelativeLayout>

结果

The result

要获得与列表视图超级熟悉看看这个视频:
http://www.youtube.com/watch?v=wDBM6wVEO70

To get super acquainted with listview check out this video: http://www.youtube.com/watch?v=wDBM6wVEO70

至于你的其他问题,你得来发布logcat的更好的响应。

As for your other issue, you're gonna have to post a logcat for better responses.

这篇关于如何创建自定义适配器列表视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆