1. 程式人生 > >Android 自定義Listview 與巢狀ScrollView

Android 自定義Listview 與巢狀ScrollView

本文講實現一個自定義列表的Android程式,程式將實現一個使用自定義的介面卡(Adapter)繫結資料,通過ontextView.setTag繫結資料有按鈕的ListView。 


系統顯示列表(ListView)時,首先會例項化一個介面卡,本文將例項化一個自定義的介面卡。實現自定義介面卡,必須手動對映資料,這時就需要重寫getView()方法,系統在繪製列表的每一行的時候將呼叫此方法。 


ListView在開始繪製的時候,系統自動呼叫getCount()函式,根據函式返回值得到ListView的長度,然後根據這個長度,呼叫getView()逐一畫出每一行。 

 

具體使用方法可以參考下面程式碼,只需記住Android自定義ListView三步驟: 
第一步:準備主佈局檔案、元件佈局檔案等 
第二步:獲取並整理資料 
第三部:繫結資料,這裡我們是通過自己編寫Adapter類來完成的 

核心思路:

ListView 由Adapter填充,由LayoutInflater渲染。

自定義Adapter:

package com.findai.xkk.ai_interviewer.job_fragment;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.findai.xkk.ai_interviewer.R;

import java.util.List;
import java.util.Map;

public class JobListView_Adapter extends BaseAdapter {
    private List<Map<String, Object>> data;
    private LayoutInflater layoutInflater;
    private Context context;


    public JobListView_Adapter(Context context, List<Map<String, Object>> data) {


        this.context=context;
        this.data=data;
        this.layoutInflater=LayoutInflater.from(context);


    }

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

    @Override
    public Object getItem(int position) {
        return data.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }
    public final class Zujian{
        public ImageView img_job_img;
        public TextView tv_job_name;
        public TextView tv_jbdesc;
    }
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        Zujian zujian = null;

        if(convertView==null) {
            zujian = new Zujian();
            convertView = layoutInflater.inflate(R.layout.job_listview_item, null);
            zujian.tv_job_name = convertView.findViewById(R.id.tv_jobname);
            zujian.tv_jbdesc = convertView.findViewById(R.id.tv_jbdesc);
            zujian.img_job_img = convertView.findViewById(R.id.img_job_img);
            convertView.setTag(zujian);
        }else {
            zujian = (Zujian)convertView.getTag();
        }

        zujian.tv_jbdesc.setText(data.get(position).get("jobdesc").toString());
        zujian.tv_job_name.setText(data.get(position).get("jobname").toString());
        return convertView;

    }
}

Activity呼叫:

package com.findai.xkk.ai_interviewer.job_fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.findai.xkk.ai_interviewer.Http.Commiuncate_Server;
import com.findai.xkk.ai_interviewer.JobinfoActivity;
import com.findai.xkk.ai_interviewer.R;
import com.findai.xkk.ai_interviewer.WelcomeIndexActivity;
import com.findai.xkk.ai_interviewer.domain.Job;
import com.findai.xkk.ai_interviewer.domain.Question;
import com.oragee.banners.BannerView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressLint("ValidFragment")
public class Job_Index_maintop_Fragment extends Fragment implements View.OnClickListener{

    BannerView bannerView;
    @Override
    public void onClick(View v) {
        Bundle bundle;
        Intent intent;
        switch (v.getId()){
            case R.id.btn_kj_interview:
                bundle = new Bundle();
                bundle.putInt("iid",1);
                intent = new Intent(getContext(),WelcomeIndexActivity.class);
                intent.putExtra("iid",bundle);
                startActivity(intent);
                break;
//            case R.id.ll_job:
//                bundle = new Bundle();
//                bundle.putInt("jid",1);
//                intent = new Intent(getContext(),JobinfoActivity.class);
//                intent.putExtra("jid",bundle);
//                startActivity(intent);
//                break;
        }
    }

    callbackQuestion_Choose_Fragment callbackQuestion_choose_fragment = null;
    private Button btn_kj;
    private LinearLayout ll_job;
    private ListView lv;
    private List<Map<String, Object>> data;
    public Job_Index_maintop_Fragment() {
    }

    public Job_Index_maintop_Fragment(callbackQuestion_Choose_Fragment callbackQuestionChooseFragment) {
        this.callbackQuestion_choose_fragment = callbackQuestionChooseFragment;

    }
    private int[] imgs = {R.mipmap.ad4,R.mipmap.ad3,R.mipmap.ad6,R.mipmap.ad7,R.mipmap.ad8,R.mipmap.ad1};
    private List<View> viewList;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.job_center_maintop_activity, container, false);
        lv = view.findViewById(R.id.lv_joblist);
        data = getData();
        System.out.println(data.size()+"----------------===");
        lv.setAdapter(new JobListView_Adapter(getContext(),data));
        fixListViewHeight(lv);

        viewList = new ArrayList<View>();
        for (int i = 0; i < imgs.length; i++) {
            ImageView image = new ImageView(getContext());
            image.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            //設定顯示格式
            image.setScaleType(ImageView.ScaleType.CENTER_CROP);
            image.setImageResource(imgs[i]);
            viewList.add(image);
        }
        bannerView = (BannerView) view.findViewById(R.id.banner_ad);
        bannerView.startLoop(true);
        bannerView.setLoopInterval(3000);
        bannerView.setViewList(viewList);

        btn_kj = view.findViewById(R.id.btn_kj_interview);
        btn_kj.setOnClickListener(this);
//        ll_job = view.findViewById(R.id.ll_job);
//        ll_job.setOnClickListener(this);



        return view;

    }
    private  List<Job> joblist = new ArrayList<>();

    public List<Map<String, Object>> getData(){
        final Commiuncate_Server cs = new Commiuncate_Server();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    joblist = cs.get_joblist(10);
//                    System.out.println(joblist.size()+"e21321=3=21=321=3");
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        });
        thread.start();
        while(joblist.size()==0){

        }

        List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
        for (Job job : joblist) {
            Map<String, Object> map=new HashMap<String, Object>();
//            map.put("image", R.drawable.ic_launcher);
            map.put("jobname", job.getJobName());
            map.put("jobdesc", job.getDegree()+"|"+job.getWorkPlace());
            list.add(map);
        }
        System.out.println(list.size());
        return list;
    }
    public interface callbackQuestion_Choose_Fragment {
        public int get_question_answer(int answer);
    }


    public void fixListViewHeight(ListView listView) {

        // 如果沒有設定資料介面卡,則ListView沒有子項,返回。

        JobListView_Adapter listAdapter = (JobListView_Adapter) listView.getAdapter();

        int totalHeight = 0;

        if (listAdapter == null) {

            return;

        }

        for (int index = 0, len = listAdapter.getCount(); index < len; index++) {

            View listViewItem = listAdapter.getView(index , null, listView);

            // 計運算元項View 的寬高

            listViewItem.measure(0, 0);

            // 計算所有子項的高度和

            totalHeight += listViewItem.getMeasuredHeight();

        }



        ViewGroup.LayoutParams params = listView.getLayoutParams();

        // listView.getDividerHeight()獲取子項間分隔符的高度

        // params.height設定ListView完全顯示需要的高度

        params.height = totalHeight+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));

        listView.setLayoutParams(params);

    }



}

Item佈局:

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

    <!--一個工作banner-->
    <LinearLayout
        android:id="@+id/ll_job"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:weightSum="12"
        android:orientation="horizontal">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_weight="8">
            <ImageView
                android:id="@+id/img_job_img"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:src="@mipmap/company_icon1"/>
        </LinearLayout>
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:layout_weight="4"
            android:orientation="vertical">
            <TextView
                android:id="@+id/tv_jobname"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#888888"
                android:text="自媒體商務(實習生)"
                android:textSize="15dp"/>
            <TextView
                android:id="@+id/tv_jbdesc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:textColor="#888888"
                android:layout_marginTop="5dp"
                android:textSize="12dp"
                android:text="本科 | 福建福州| 截止時間:02-03"/>
        </LinearLayout>
    </LinearLayout>
    <!--一個工作banner end-->

</LinearLayout>

Activity佈局:

<?xml version="1.0" encoding="utf-8"?>
<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="wrap_content"
    android:orientation="horizontal"
    android:background="#ececec"
    android:weightSum="12">
    <!--<ScrollView-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent">-->
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
            <com.oragee.banners.BannerView
                android:id="@+id/banner_ad"
                android:layout_width="match_parent"
                android:layout_height="212dp">

            </com.oragee.banners.BannerView>
            <!--<ImageView-->
                <!--android:id="@+id/img_ad1"-->
                <!--android:layout_width="match_parent"-->
                <!--android:layout_height="212dp"-->
                <!--android:src="@mipmap/ad1" />-->
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <Button
                    android:id="@+id/btn_kj_interview"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="4"
                    android:text="會計面試"
                    style="@style/job_tiku_btn_css"
                    />
                <Button
                    android:id="@+id/btn_jsj_interview"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="4"
                    android:text="醫療面試"
                    style="@style/job_tiku_btn_css"
                    />
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="4"
                    android:text="軟體面試"
                    style="@style/job_tiku_btn_css"
                    />
            </LinearLayout>
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="4"
                    android:text="網際網路面試"
                    style="@style/job_tiku_btn_css"
                    />
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="4"
                    android:text="土木面試"
                    style="@style/job_tiku_btn_css"
                    />
                <Button
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="4"
                    android:text="人力資源面試"
                    style="@style/job_tiku_btn_css"
                    />
            </LinearLayout>

            <ImageView
                android:layout_width="match_parent"
                android:layout_height="142dp"
                android:src="@mipmap/ad2" />
            <LinearLayout
                android:layout_marginTop="5dp"
                android:layout_marginBottom="5dp"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#ffffff"
                android:orientation="vertical">

                <ListView
                    android:id="@+id/lv_joblist"
                    android:layout_width="match_parent"
                    android:layout_height="300dp">
                </ListView>


            </LinearLayout>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="100dp"
                android:layout_marginTop="20dp"
                android:text="到底啦~"
                android:gravity="center"/>

        </LinearLayout>

    <!--</ScrollView>-->

</LinearLayout>