網頁

2022年2月6日 星期日

Android Studio - ListView 加上圖像和 CheckBox(三十二)

Android Studio - ListView 加上圖像和 CheckBox(三十二):

ListView(列表)主要是用來把數據用列表方式顯示出來,如果只是簡單的列表呈現,可以利用 ArrayAdapter、SimpleCursorAdapter、SimpleAdapter 來達成目的,但如果要做到更複雜的列表,就必須使用 BaseAdapter 來客製化 ListView,如加入圖片、Checkbox… 等等,利用 BaseAdapter 來控制 ListView 每個 Item 的內容與樣式,使到 ListView 的可讀性和功能提升。

Android Studio ListView 加上圖像和 CheckBox
操作系統:Windows 7 64-bit 版本
開發環境:Android Studio 4.0.1 版本
原程式:C:\Development\Development_Android\Android_Project\DIY-Android-007-17 ListView Icon CheckBox
程式:C:\Development\Development_Android\Android_Project\DIY-Android-007-17 ListView Icon CheckBox

ListView 加上圖像和 CheckBox 編程步驟:
  • 將 ListView(Mainactivity.java)實體化
  • 創建 BaseAdapter,根據資料來改變 ListView Item
  • 取得清單資料放到 BaseAdapter
  • 在 Layout 配置檔(custom_list_item.xml)裡面放一個自行定義的 ListView

MainActivity.java:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import android.app.Activity;

import android.content.Context;

import android.util.SparseBooleanArray;

import android.view.LayoutInflater;

import android.view.View;

import android.view.View.OnClickListener;

import android.view.ViewGroup;

import android.widget.AdapterView;

import android.widget.AdapterView.OnItemClickListener;

import android.widget.BaseAdapter;

import android.widget.CheckBox;

import android.widget.CompoundButton;

import android.widget.CompoundButton.OnCheckedChangeListener;

import android.widget.ImageView;

import android.widget.ListView;

import android.widget.TextView;

 

public class MainActivity extends AppCompatActivity {

    //public class MainActivity extends Activity {

    private ListView mListView;

    private static int count = 0;

    private static boolean isNotAdded = true;

    private CheckBox checkBox_header;

    final CustomAdapter adapter = new CustomAdapter(this);

 

    final static String[] mLvData = {

            "Resistor", "Capacitor", "Inductor", "Diode", "Transistor",

            "IC", "Sensor", "Fuse", "Connector", "PCB", "Crystal",

            "LED", "LCD", "Battery"

            };

    SparseBooleanArray mChecked = new SparseBooleanArray();

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mListView = (ListView) findViewById(R.id.list_view);

 

        // To avoid adding multiple times

        if (isNotAdded) {

            final View headerView = getLayoutInflater().inflate(R.layout.custom_list_view,

                    mListView, false);

            checkBox_header = (CheckBox) headerView.findViewById(

                    R.id.checkBox);

            checkBox_header.setOnClickListener(new OnClickListener() {

 

                @Override

                public void onClick(View v) {

                    for (int i = 0; i < count; i++) {

                        mChecked.put(i, checkBox_header.isChecked());

                    }

                    adapter.notifyDataSetChanged();

                }

            });

           

            mListView.addHeaderView(headerView);

            isNotAdded = false;

        }

       

        mListView.setAdapter(adapter);

       

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position == 0) {

                } else {

                    position = position - 1; // "-1" If Header is Added

                }

            }

        });

    }

 

    // CustomAdapter

    public class CustomAdapter extends BaseAdapter {

        Activity sActivity;

 

        public CustomAdapter(final Activity mActivity) {

            this.sActivity = mActivity;

        }

        @Override

        public int getCount() {

            count = MainActivity.mLvData.length;

            return count;

        }

 

        @Override

        public Object getItem(int position) {

            return position;

        }

 

        @Override

        public long getItemId(int position) {

            return position;

        }

 

        @Override

        public View getView(final int position, View convertView, ViewGroup parent) {

            View mView = convertView;

            if (mView == null) {

                final LayoutInflater sInflater = (LayoutInflater) sActivity.getSystemService(

                        Context.LAYOUT_INFLATER_SERVICE);

                mView = sInflater.inflate(R.layout.custom_list_view, null, false);

            }

           

            final TextView sTV1 = (TextView) mView.findViewById(R.id.textView);

            final ImageView sIMG = (ImageView) mView.findViewById(R.id.imageView);

            final CheckBox mCheckBox = (CheckBox) mView.findViewById(

                    R.id.checkBox);

           

            sTV1.setText(MainActivity.mLvData[position]);

            sIMG.setImageResource(R.drawable.logo2);

 

            mCheckBox.setOnCheckedChangeListener(

                    new OnCheckedChangeListener() {

                        @Override

                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                            if (isChecked) {

                                mChecked.put(position, isChecked);

                                if (isAllValuesChecked()) {

                                    checkBox_header.setChecked(isChecked);

                                }

                            } else {

                                mChecked.delete(position);

                                checkBox_header.setChecked(isChecked);

                            }

 

                        }

                    });

           

            mCheckBox.setChecked((mChecked.get(position) == true ? true : false));

            return mView;

        }

 

        protected boolean isAllValuesChecked() {

            for (int i = 0; i < count; i++) {

                if (!mChecked.get(i)) {

                    return false;

                }

            }

            return true;

        }

    }

}


activity_main.xml:

<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="vertical"

    android:padding="8dp"

    tools:context=".MainActivity">

 

    <ListView

        android:id="@+id/list_view"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:cacheColorHint="@android:color/transparent"

        android:dividerHeight="4dp" />

</LinearLayout>


custom_list_item.xml:

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="fill_parent"

    android:layout_height="wrap_content"

    android:background="@android:color/holo_green_light"

    android:minHeight="40dp"

    android:padding="4dp"

    tools:ignore="HardcodedText,ContentDescription">

 

    <!-- ListView Contents -->

    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerVertical="true"

        android:layout_marginLeft="31dp"

        android:layout_toRightOf="@+id/imageView"

        android:text="All Components"

        android:textSize="21sp" />

 

    <ImageView

        android:id="@+id/imageView"

        android:layout_width="wrap_content"

        android:layout_height="40dp"

        android:layout_alignParentLeft="true"

        android:layout_centerVertical="true"

        android:layout_marginLeft="15dp"

        android:maxWidth="40dp"

        android:maxHeight="40dp"

        android:scaleType="fitXY"

        android:src="@drawable/logo2" />

 

    <CheckBox

        android:id="@+id/checkBox"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentRight="true"

        android:layout_centerVertical="true"

        android:focusable="false"

        android:focusableInTouchMode="false"

        android:padding="16dp" />

 

</RelativeLayout>


ListView 加上圖像和 CheckBox
2022年 2月 6日(Sun)天氣報告
氣溫:38.0°F / 3.0°C @ 07:00
風速:每小時 5公里
降雨機會:3%
相對濕度:百分之 91%
天氣:霧

沒有留言:

張貼留言