ImageLoader、GET、データを取得する POST、マルチアイテムのロード、XListView

//メイン アクティビティ XListView (3 つの Java コードがあります) のビューは、MainActivity と同じレベルに配置するのが最適です
public class MainActivity extends AppCompatActivity implements XListView.IXListViewListener {
    //定义的页数int num = 0 ;
    プライベートList<UserBean.ResultBean.ListBean> list = new ArrayList<>();
    プライベートMyAdapterアダプター;
    プライベートXListView xListView ; @Override
 protected void onCreate(Bundle savedInstanceState) {
         super .onCreate(savedInstanceState); 
        setContentView(R.layout. activity_main );
        
    

        //xlistviewコントロール
xListView = (XListView) findViewById(R.id.x_list_view ) ;
         //設定        
	//プルダウン
xListView .setPullRefreshEnable( true );        
	//プルアップ
        xListView .setPullLoadEnable( true );
	//設定すると、プルアップおよびプルダウン メソッドを返すことができます
        xListView .setXListViewListener( this ); 
        getPost(); 
    } 
    //POST をプルダウンしてデータを取得しますprivate void getPost() { 
        AsyncTask<Void, Void, String > asyncTask = new AsyncTask< Void, Void, String>() {
             @Override
 protected String doInBackground(Void... voids) { 
                String path = "http://v.juhe.cn/weixin/query" ;
                 try { 
                    URL url =新しいURL(パス); 
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //
                
                    リクエストを設定する
                    connection.setRequestMethod( "POST" );
                    connection.setReadTimeout( 5000 );
                    connection.setConnectTimeout( 5000 );
                     //パラメータをサーバーに送信するポストメソッド...ストリーム接続の形式でサーバーに送信します
                    。 setDoOutput( true ) ;
                     //リクエスト パラメータのタイプを設定します
                    connection.setRequestProperty( "Content-Type" , "application/x-www-form-urlencoded" );

                    String pathstring = "key=88f7bbc507e3ecacfaeab2b47dd8936f&ps=10&pno=" + num ;
                    connection.getOutputStream().write(pathstring.getBytes( "utf-8" ));
                    //响対応
int responseCode = connection.getResponseCode();
                    if (responseCode == 200 ) { 
                        InputStream inputStream = connection.getInputStream(); 
                        文字列 json = StreamToString(inputStream, "utf-8" ); 
                        ログ。i ( "json" , "json---->" + json); jsonを返します。
                    キャッチ
                _ _                    

                        
                    e.printStackTrace(); 
                } return null ; 
            }     // ここで解析し、アダプタを追加
            @Override
 protected void onPostExecute(String s) {
                 super .onPostExecute(s);
                 // Gsonを解析
gson = new Gson(); 
                UserBean userBean = gson .fromJson(s, UserBean.class );
                 list .addAll ( 0 , userBean.getResult().getList());
                 //アダプタを設定
setadapter();
                 // xListViewを停止
.stopRefresh();
                
	                                                            
                Date date = new Date(System.currentTimeMillis ( )); 
                SimpleDateFormat dateFormat = new SimpleDateFormat( "HH:mm" );
                 //時刻を設定
xListView .setRefreshTime(dateFormat.format(date)); 
            } 
        }; 
        asyncTask.execute() ; 
    } //アダプターをプライベートに設定します
void setadapter() {
         if ( adapter == null ){
             adapter = new MyAdapter(MainActivity. this , list                
        );
            xListView .setAdapter(アダプタ); 
        } else {
            アダプター.notifyDataSetChanged(); 
        } 
    } //プライベート文字列を解析する
StreamToString(InputStream inputStream, String s) {
         try { 
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, s); 
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
            StringBuilder ビルダー =新しいStringBuilder(); 
            文字列文字列 = ""
        ;
            while ((string = bufferedReader.readLine()) != null ){ 
                builder.append(string); 
            } 
            bufferedReader.close(); 
            ログ。i ( "ビルダー" , "ビルダー------>" + builder.toString());
            builder.toString();を返します。
        } catch (例外 e) { 
            e.printStackTrace(); null を返し
        ます
    } 
    //上拉GET获取数据
        
    public void getPostLoadMore() {
        AsyncTask<Void, Void, String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                String path = "http://v.juhe.cn/weixin/query?key=88f7bbc507e3ecacfaeab2b47dd8936f&ps=10&pno=" + num;
                try {
                    URL url = new URL(path);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    //设置
                      connection.setRequestMethod("GET");
                    connection.setReadTimeout(5000);
                    connection.setConnectTimeout(5000);
                    //获取
                    int responseCode = connection.getResponseCode();
                    if (responseCode == 200){
                        InputStream inputStream = connection.getInputStream();
                        String json = StreamToString(inputStream,"utf-8");
                        return json;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return "";
            }
            @Override
            protected void onPostExecute(String json) {
                Gson gson = new Gson();
                UserBean userBean = gson.fromJson(json, UserBean.class);
                //dataDataBean.getResults();
                //数据要添加到集合的最前边
                 list.addAll(userBean.getResult().getList());
               setadapter();
               //停止刷新
                xListView.stopLoadMore();
            }
        };
        asyncTask.execute();
    }
    //下拉加载
    @Override
    public void onRefresh() {
        num ++;
        Log.i("num" , "下拉num---->" + num);
        getPost();//加载到数据之后停止
    }

    //上拉刷新
    @Override
    public void onLoadMore() {
        if (num > 0){
            num --;
            getPostLoadMore();
        }else{
            Toast.makeText(MainActivity.this,"没有最新数据了",Toast.LENGTH_SHORT).show();
            xListView.stopLoadMore();
        }
        Log.i("num" , "上拉num---->" + num);
    }
}
//Adapter   listview的适配器
public class MyAdapter extends BaseAdapter {

    private static final int IMAGE_ITEM_LEFT = 0;
    private static final int IMAGE_ITEM_RIGHT = 1;
    Context context;
    List<UserBean.ResultBean.ListBean> list;

    public MyAdapter(Context context, List<UserBean.ResultBean.ListBean> list) {
        this.context = context;
        this.list = list;
        ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(context));
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }
    //多条目加载 所需get(1)getViewTypeCount
    @Override
    public int getViewTypeCount() {
        return 2;
    }
    //多条目加载 所需get(2)getItemViewType
    @Override
    public int getItemViewType(int position) {
        if ((position%2) == 0){
            return IMAGE_ITEM_LEFT;
        }
        return IMAGE_ITEM_RIGHT;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        if (getItemViewType(i) == IMAGE_ITEM_LEFT){
            ViewHolderLeft holderLeft;
            if (view == null){
                holderLeft = new ViewHolderLeft();
                view = View.inflate(context , R.layout.image_left , null);
                holderLeft.textView = view.findViewById(R.id.text_title);
                holderLeft.imageView = view.findViewById(R.id.iamge_01);
                view.setTag(holderLeft);
            }else{
                holderLeft = (ViewHolderLeft) view.getTag();
            }
            holderLeft.textView.setText(list.get(i).getTitle());
            ImageLoader.getInstance().displayImage(list.get(i).getFirstImg() , holderLeft.imageView , getOption());
        }else{
            ViewHolderRight holderRight;
            if (view == null){
                holderRight = new ViewHolderRight();
                view = View.inflate(context , R.layout.image_right , null);
                holderRight.textView = view.findViewById(R.id.text_title);
                holderRight.imageView = view.findViewById(R.id.iamge_02);
                view.setTag(holderRight);
            }else{
                holderRight = (ViewHolderRight) view.getTag();
            }
            holderRight.textView.setText(list.get(i).getTitle());
            ImageLoader.getInstance().displayImage(list.get(i).getFirstImg() , holderRight.imageView , getOption());
        }
        return view;
    }

    public DisplayImageOptions getOption() {
        DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
                .showImageForEmptyUri(R.mipmap.ic_launcher)
                .showImageOnFail(R.mipmap.ic_launcher)
                .showImageOnLoading(R.mipmap.ic_launcher)
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
                .resetViewBeforeLoading(true)//在加载之前复位一下显示
                .bitmapConfig(Bitmap.Config.RGB_565)//图片的质量
                .considerExifParams(true)//是否考虑JPEG图像EXIF参数(旋转,翻转)
                .build();
        return imageOptions;
    }

    class ViewHolderLeft{
        ImageView imageView;
        TextView textView;
    }
    class ViewHolderRight{
        TextView textView;
        ImageView imageView;
    }
}
//XML布局 footer
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <RelativeLayout
        android:id="@+id/xlistview_footer_content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp" >

        <ProgressBar
            android:id="@+id/xlistview_footer_progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="invisible" />

        <TextView
            android:id="@+id/xlistview_footer_hint_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/xlistview_footer_hint_normal" />
    </RelativeLayout>

</LinearLayout>
//XML布局 header
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="bottom" >

    <RelativeLayout
        android:id="@+id/xlistview_header_content"
        android:layout_width="fill_parent"
        android:layout_height="60dp" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical" android:id="@+id/xlistview_header_text">

            <TextView
                android:id="@+id/xlistview_header_hint_textview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/xlistview_header_hint_normal" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dp" >

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/xlistview_header_last_time"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/xlistview_header_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/xlistview_header_arrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-35dp"
            android:src="@drawable/xlistview_arrow" />

        <ProgressBar
            android:id="@+id/xlistview_header_progressbar"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-40dp"
            android:visibility="invisible" />
    </RelativeLayout>

</LinearLayout>

おすすめ

転載: blog.csdn.net/qq_40071033/article/details/77924965