如何在ListView中活性的研究实施CustomAdapter [英] How to implement CustomAdapter in ListView Acitivity

查看:181
本文介绍了如何在ListView中活性的研究实施CustomAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想TextView的前映像,并希望各行中定义的TextView,但它是我很难实施,因为已经有XML这样的布局文件的 simple_list_item_1管理作出内置。 请帮助我,我怎么能实现它。

下面是simple_list_item编码

 < XML版本=1.0编码=UTF-8&GT?;
<  - !版权所有(C)2006年的Andr​​oid开源项目

     Apache许可证下授权,版本2.0(以下简称许可证);
     你可能不使用这个文件除了在遵守许可。
     您可以在获得许可证的副本

          http://www.apache.org/licenses/LICENSE-2.0

     除非适用法律要求或书面同意,软件
     该许可证下发布分布在原样的基础上,
     无担保或任何形式的条件,无论是EX preSS或暗示的保证。
     查看许可证的特定语言的管理权限和
     该许可证下的限制。
 - >

< TextView中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:ID =@机器人:ID / text1中
    机器人:layout_width =match_parent
    机器人:layout_height =WRAP_CONTENT
        机器人:TEXTSIZE =20SP
            机器人:TEXTSTYLE =黑体
    机器人:textAppearance =机器人:ATTR / textAppearanceListItemSmall
    机器人:重力=center_vertical
    机器人:paddingStart =机器人:ATTR /列表preferredItemPaddingStart
    机器人:paddingEnd =机器人:ATTR /列表preferredItemPaddingEnd
    机器人:=了minHeight机器人:ATTR /列表preferredItemHeightSmall
/>
 

主要活动

 公共类MainActivity扩展ListActivity {

    私人ListActivity的活动;
    最终静态字符串ScreenName链接=谷歌;
    最终静态字符串LOG_TAG =RNC;
     ListView控件列表视图;
      TextView的文字;
    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.twit_list);


          列表视图= this.getListView();

         活动=这一点;

        downloadTweets();


          listview.setOnItemClickListener(新OnItemClickListener(){
              @覆盖
              公共无效onItemClick(适配器视图<>母公司视图中查看,
                           INT位置,长的id){
                 //选择的项目
                 。字符串lst_txt = parent.getItemAtPosition(位置)的ToString()修剪();


                 //启动新的活动上选择单个列表项
                 意图I =新的意图(MainActivity.this,SingleListItem.class);
                 //将数据发送到新活动
                 i.putExtra(产品,lst_txt);
                 startActivity(ⅰ);
               }
            });
    }

    //后首先检查是否有一个网络连接下载twitter上的时间表
    公共无效downloadTweets(){
        ConnectivityManager connMgr =(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
        的NetworkInfo的NetworkInfo = connMgr.getActiveNetworkInfo();

        如果(的NetworkInfo =空&安培;!&安培; networkInfo.isConnected()){
            新DownloadTwitterTask()执行(ScreenName链接);
        } 其他 {
            Log.v(LOG_TAG,没有网络连接可用。);
        }
    }

    //采用的AsyncTask下载一个Twitter用户的时间表
    私有类DownloadTwitterTask扩展的AsyncTask<字符串,太虚,字符串> {
        最终静态字符串CONSUMER_KEY =keyvaluexxxxx;
        最终静态字符串CONSUMER_SECRET =secretkeyxxxxxxx;
        最终静态字符串TwitterTokenURL =htt​​ps://api.twitter.com/oauth2/token;
        最终静态字符串TwitterStreamURL =htt​​ps://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=;


        私人ProgressDialog progressDialog;
        @覆盖
        //这里可以使用UI线程
        在preExecute保护无效(){
        //this.progressDialog = ProgressDialog.show(Boys.this,,看他的背!好让我看看,我有你);
            尝试{
            progressDialog =新ProgressDialog(MainActivity.this,AlertDialog.THEME_HOLO_DARK);
            progressDialog.setIndeterminate(真正的);
            progressDialog.setIndeterminateDrawable(getResources()getDrawable(R.drawable.loader_2));
            progressDialog.setMessage(请等待通过拆东西给你......!);
            progressDialog.show();
            progressDialog.setCancelable(假);
            progressDialog.setCanceledOnTouchOutside(假);
            }
            赶上(例外五)
            {
                this.progressDialog.dismiss();
                Toast.makeText(getApplicationContext(),e.​​toString(),Toast.LENGTH_LONG).show();

            }
        }

        @覆盖
        保护字符串doInBackground(字符串...的昵称){
            字符串结果= NULL;

            如果(screenNames.length大于0){
                结果= getTwitterStream(的昵称[0]);
            }
            返回结果;
        }

        // onPostExecute转换JSON结果到Twitter的目标(这是微博的一个数组列表
        @覆盖
        保护无效onPostExecute(字符串结果){
            Twitter的蠢特夫妇= jsonToTwitter(结果);

            //让结果写入控制台以及
            对于(资料Tweet鸣叫:蠢特夫妇){
                Log.i(LOG_TAG,tweet.getText());
            }

            //发送鸣叫适配器进行渲染
            ArrayAdapter<分享Tweet>适配器=新的ArrayAdapter<分享Tweet>(活动,android.R.layout.simple_list_item_1,蠢特夫妇);
            setListAdapter(适配器);
            this.progressDialog.dismiss();
        }

        // JSON数据的字符串转换成一个Twitter对象
        私人微博jsonToTwitter(字符串结果){
            Twitter的蠢特夫妇= NULL;
            如果(结果=空&安培;!&安培; result.length()大于0){
                尝试 {
                    GSON GSON =新GSON();
                    蠢特夫妇= gson.fromJson(结果,Twitter.class);
                }赶上(IllegalStateException异常前){
                    //只是吃了异常
                }
            }
            返回蠢特夫妇;
        }

        //转换一个JSON验证对象为经过身份验证的对象
        私人认证jsonToAuthenticated(字符串rawAuthorization){
            经过身份验证的权威性= NULL;
            如果(rawAuthorization =空&安培;!&安培; rawAuthorization.length()大于0){
                尝试 {
                    GSON GSON =新GSON();
                    AUTH = gson.fromJson(rawAuthorization,Authenticated.class);
                }赶上(IllegalStateException异常前){
                    //只是吃了异常
                }
            }
            返回身份验证;
        }

        私人字符串getResponseBody(Htt的prequestBase要求){
            StringBuilder的SB =新的StringBuilder();
            尝试 {

                DefaultHttpClient的HttpClient =新DefaultHttpClient(新BasicHttpParams());
                HTT presponse响应= httpClient.execute(要求);
                。INT状态code = response.getStatusLine()的getStatus code();
                字符串原因= response.getStatusLine()getReasonPhrase()。

                如果(状态code == 200){

                    HttpEntity实体= response.getEntity();
                    InputStream中的InputStream = entity.getContent();

                    的BufferedReader面包屑=新的BufferedReader(新的InputStreamReader(InputStream中,UTF-8),8);
                    串线= NULL;
                    而((行= bReader.readLine())!= NULL){
                        sb.append(线);
                    }
                } 其他 {
                    sb.append(原因);
                }
            }赶上(UnsupportedEncodingException前){
            }赶上(ClientProtocolException EX1){
            }赶上(IOException异常EX2){
            }
            返回sb.toString();
        }

        私人字符串getTwitterStream(字符串屏幕名){
            字符串结果= NULL;

            //第1步:恩code消费者密钥和秘密
            尝试 {
                // URL连接code消费者密钥和秘密
                字符串urlApiKey = URLEn coder.en code(CONSUMER_KEY,UTF-8);
                字符串urlApiSecret = URLEn coder.en code(CONSUMER_SECRET,UTF-8);

                //并置EN codeD的消费者的关键,一个冒号,以及
                // EN codeD的消费者的秘密
                串组合= urlApiKey +:+ urlApiSecret;

                // Base64的EN code中的字符串
                字符串base64En codeD = Base64.en codeToString(combined.getBytes(),Base64.NO_WRAP);

                //第2步:获取承载令牌
                HttpPost httpPost =新HttpPost(TwitterTokenURL);
                httpPost.setHeader(授权,基本+ base64En codeD);
                httpPost.setHeader(内容类型,应用程序/ x-WWW的形式urlen codeD;字符集= UTF-8);
                httpPost.setEntity(新StringEntity(grant_type = client_credentials));
                字符串rawAuthorization = getResponseBody(httpPost);
                经过身份验证的AUTH = jsonToAuthenticated(rawAuthorization);

                //应用程序应验证该值与关联
                //返回对象的token_type关键是承载
                如果(AUTH = NULL和放大器;!&安培; auth.token_type.equals(旗手)){

                    //第3步:验证API与承载令牌请求
                    HTTPGET HTTPGET =新HTTPGET(TwitterStreamURL +屏幕名);

                    //构建一个正常的HTTPS请求,并包括授权
                    >在承载&所述的值//报头;
                    httpGet.setHeader(授权,承载+ auth.access_token);
                    httpGet.setHeader(内容类型,应用/ JSON);
                    //更新结果与响应的主体
                    结果= getResponseBody(HTTPGET);
                }
            }赶上(UnsupportedEncodingException前){
            }赶上(IllegalStateException异常EX1){
            }
            返回结果;
        }
    }
}
 

下面的 twit_list.xml MainActivity.java

 < XML版本=1.0编码=UTF-8&GT?;
< LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
              机器人:方向=垂直
              机器人:layout_width =FILL_PARENT
              机器人:layout_height =FILL_PARENT
    机器人:背景=@可绘制/双

        >

<的ListView
          机器人:ID =@机器人:ID /列表
          机器人:layout_width =match_parent
          机器人:layout_height =WRAP_CONTENT>

< / ListView控件>


< / LinearLayout中>
 

解决方案

创建一个 custom_item 布局文件夹内

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent
    机器人:方向=横向>

    < ImageView的
        机器人:ID =@ + ID / listItemImgView
        机器人:layout_width =WRAP_CONTENT
        机器人:layout_height =WRAP_CONTENT
        机器人:contentDescription =@字符串/完成
        机器人:SRC =@可绘制/ ic_launcher/>

    <的TextView
        机器人:ID =@ + ID / listItemTxtView
        机器人:layout_width =0dp
        机器人:layout_height =WRAP_CONTENT
        机器人:layout_weight =1/>

< / LinearLayout中>
 

像这样创建一个自定义的适配器

 公共类CustomAdapter扩展ArrayAdapter<分享Tweet> {

    私人语境mContext;
    私人诠释layoutId;
    私人的ArrayList<分享Tweet>数据列表;

    公共CustomAdapter(上下文的背景下,INT RESOURCEID,
            ArrayList的<分享Tweet>对象){
        超(背景下,RESOURCEID,对象);
        // TODO自动生成构造函数存根
        mContext =背景;
        layoutId = RESOURCEID;
        DataList控件=物体;
    }

    @覆盖
    公共查看getView(INT位置,查看convertView,ViewGroup中父){
        // TODO自动生成方法存根
        ViewHolder viewHolder;
        如果(convertView == NULL){
            LayoutInflater充气=(LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(layoutId,NULL);
            viewHolder =新ViewHolder();
            viewHolder.listItemTxtView =(TextView中)convertView.findViewById(R.id.listItemTxtView);
            viewHolder.listItemImgView =(ImageView的)convertView.findViewById(R.id.listItemImgView);

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

        viewHolder.listItemTxtView.setText(dataList.get(位置)的ToString());
        //地方毕加索的jar到项目的libs文件夹,并用它来下载和设置这样的图片
        Picasso.with(上下文).load(URL的图像要载入)到(viewHolder.listItemImgView)。
        返回convertView;
    }

    私有类ViewHolder {
        TextView的listItemTxtView;
        ImageView的listItemImgView;
    }
}
 

下载毕加索从这里 <罐子/ P>

,而不是这个

  ArrayAdapter&LT;分享Tweet&GT;适配器=新的ArrayAdapter&LT;分享Tweet&GT;(活动,android.R.layout.simple_list_item_1,蠢特夫妇);
setListAdapter(适配器);
 

使用该

  CustomAdapter适配器=新CustomAdapter(MainActivity.this,R.layout.custom_item,蠢特夫妇);
setListAdapter(适配器);
 

I want image before textview and want to customize TextView in each row but it is hard for me to implement it because there is already xml such layout file simple_list_item_1 made inbuilt. Please help me how can i implement it.

Here is simple_list_item coding

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2006 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
        android:textSize="20sp"
            android:textStyle="bold"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
/>

Main Activity

public class MainActivity extends ListActivity {

    private ListActivity activity;
    final static String ScreenName = "google";
    final static String LOG_TAG = "rnc";
     ListView listview;
      TextView text;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.twit_list);


          listview = this.getListView();

         activity = this;

        downloadTweets();


          listview.setOnItemClickListener(new OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> parent, View view,
                           int position, long id) {   
                 // selected item
                 String lst_txt = parent.getItemAtPosition(position).toString().trim();


                 // Launching new Activity on selecting single List Item
                 Intent i = new Intent(MainActivity.this, SingleListItem.class);
                 // sending data to new activity
                 i.putExtra("product",lst_txt );
                 startActivity(i);
               }
            });
    }

    // download twitter timeline after first checking to see if there is a network connection
    public void downloadTweets() {
        ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

        if (networkInfo != null && networkInfo.isConnected()) {
            new DownloadTwitterTask().execute(ScreenName);
        } else {
            Log.v(LOG_TAG, "No network connection available.");
        }
    }

    // Uses an AsyncTask to download a Twitter user's timeline
    private class DownloadTwitterTask extends AsyncTask<String, Void, String> {
        final static String CONSUMER_KEY = "keyvaluexxxxx";
        final static String CONSUMER_SECRET = "secretkeyxxxxxxx";
        final static String TwitterTokenURL = "https://api.twitter.com/oauth2/token";
        final static String TwitterStreamURL = "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=";


        private ProgressDialog progressDialog;  
        @Override
        // can use UI thread here
        protected void onPreExecute() {
        //this.progressDialog = ProgressDialog.show(Boys.this, ""," Look whose back !! Ok Let me see what i have for you ");  
            try{
            progressDialog = new ProgressDialog(MainActivity.this,AlertDialog.THEME_HOLO_DARK);
            progressDialog.setIndeterminate(true);
            progressDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.loader_2));
            progressDialog.setMessage("Please Wait ! Unwrapping Something for You...");
            progressDialog.show();
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
            }
            catch(Exception e)
            {
                this.progressDialog.dismiss();
                Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();

            }
        }

        @Override
        protected String doInBackground(String... screenNames) {
            String result = null;

            if (screenNames.length > 0) {
                result = getTwitterStream(screenNames[0]);
            }
            return result;
        }

        // onPostExecute convert the JSON results into a Twitter object (which is an Array list of tweets
        @Override
        protected void onPostExecute(String result) {
            Twitter twits = jsonToTwitter(result);

            // lets write the results to the console as well
            for (Tweet tweet : twits) {
                Log.i(LOG_TAG, tweet.getText());
            }

            // send the tweets to the adapter for rendering
            ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
            setListAdapter(adapter);
            this.progressDialog.dismiss();
        }

        // converts a string of JSON data into a Twitter object
        private Twitter jsonToTwitter(String result) {
            Twitter twits = null;
            if (result != null && result.length() > 0) {
                try {
                    Gson gson = new Gson();
                    twits = gson.fromJson(result, Twitter.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return twits;
        }

        // convert a JSON authentication object into an Authenticated object
        private Authenticated jsonToAuthenticated(String rawAuthorization) {
            Authenticated auth = null;
            if (rawAuthorization != null && rawAuthorization.length() > 0) {
                try {
                    Gson gson = new Gson();
                    auth = gson.fromJson(rawAuthorization, Authenticated.class);
                } catch (IllegalStateException ex) {
                    // just eat the exception
                }
            }
            return auth;
        }

        private String getResponseBody(HttpRequestBase request) {
            StringBuilder sb = new StringBuilder();
            try {

                DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                String reason = response.getStatusLine().getReasonPhrase();

                if (statusCode == 200) {

                    HttpEntity entity = response.getEntity();
                    InputStream inputStream = entity.getContent();

                    BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    String line = null;
                    while ((line = bReader.readLine()) != null) {
                        sb.append(line);
                    }
                } else {
                    sb.append(reason);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (ClientProtocolException ex1) {
            } catch (IOException ex2) {
            }
            return sb.toString();
        }

        private String getTwitterStream(String screenName) {
            String results = null;

            // Step 1: Encode consumer key and secret
            try {
                // URL encode the consumer key and secret
                String urlApiKey = URLEncoder.encode(CONSUMER_KEY, "UTF-8");
                String urlApiSecret = URLEncoder.encode(CONSUMER_SECRET, "UTF-8");

                // Concatenate the encoded consumer key, a colon character, and the
                // encoded consumer secret
                String combined = urlApiKey + ":" + urlApiSecret;

                // Base64 encode the string
                String base64Encoded = Base64.encodeToString(combined.getBytes(), Base64.NO_WRAP);

                // Step 2: Obtain a bearer token
                HttpPost httpPost = new HttpPost(TwitterTokenURL);
                httpPost.setHeader("Authorization", "Basic " + base64Encoded);
                httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
                httpPost.setEntity(new StringEntity("grant_type=client_credentials"));
                String rawAuthorization = getResponseBody(httpPost);
                Authenticated auth = jsonToAuthenticated(rawAuthorization);

                // Applications should verify that the value associated with the
                // token_type key of the returned object is bearer
                if (auth != null && auth.token_type.equals("bearer")) {

                    // Step 3: Authenticate API requests with bearer token
                    HttpGet httpGet = new HttpGet(TwitterStreamURL + screenName);

                    // construct a normal HTTPS request and include an Authorization
                    // header with the value of Bearer <>
                    httpGet.setHeader("Authorization", "Bearer " + auth.access_token);
                    httpGet.setHeader("Content-Type", "application/json");
                    // update the results with the body of the response
                    results = getResponseBody(httpGet);
                }
            } catch (UnsupportedEncodingException ex) {
            } catch (IllegalStateException ex1) {
            }
            return results;
        }
    }
}

Here twit_list.xml attached with MainActivity.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
    android:background="@drawable/bis" 

        >

<ListView  
          android:id="@android:id/list"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">

</ListView>


</LinearLayout>

解决方案

Create a custom_item inside layout folder

<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="match_parent"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/listItemImgView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/done"
        android:src="@drawable/ic_launcher" />

    <TextView
        android:id="@+id/listItemTxtView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1" />

</LinearLayout>

Create a custom adapter like this

public class CustomAdapter extends ArrayAdapter<Tweet> {

    private Context mContext;
    private int layoutId;
    private ArrayList<Tweet> dataList;

    public CustomAdapter(Context context, int resourceId,
            ArrayList<Tweet> objects) {
        super(context, resourceId, objects);
        // TODO Auto-generated constructor stub
        mContext = context;
        layoutId = resourceId;
        dataList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder viewHolder;
        if(convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(layoutId, null);
            viewHolder = new ViewHolder();
            viewHolder.listItemTxtView = (TextView) convertView.findViewById(R.id.listItemTxtView);
            viewHolder.listItemImgView = (ImageView) convertView.findViewById(R.id.listItemImgView);

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

        viewHolder.listItemTxtView.setText(dataList.get(position).toString());
        //place picasso jar into libs folder of your project and use it for download and  set images like this
        Picasso.with(context).load("url of image you want to load").into(viewHolder.listItemImgView);
        return convertView;
    }

    private class ViewHolder {
        TextView listItemTxtView;
        ImageView listItemImgView;
    }
}

download picasso jar from here

instead of this

ArrayAdapter<Tweet> adapter = new ArrayAdapter<Tweet>(activity, android.R.layout.simple_list_item_1, twits);
setListAdapter(adapter);

Use this

CustomAdapter adapter = new CustomAdapter(MainActivity.this, R.layout.custom_item, twits);
setListAdapter(adapter);

这篇关于如何在ListView中活性的研究实施CustomAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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