1. 程式人生 > >安卓自定義下拉框---Spinner的實現

安卓自定義下拉框---Spinner的實現

最近專案中用到下拉列表,剛開始一頭霧水,後來在網上找了一個Demo,自己修改了一下,現在把它分享出來,給大家參考,寫的不好,多多關照!不過功能還是實現的了······先上圖給大家看看效果!

效果圖:

實現思路:

1.定義下拉控制元件佈局(ListView及子控制元件佈局)

2.自定義SpinerPopWindow類

3.定義填充資料的Adapter

一、定義控制元件佈局:

1.  activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f2f2f2"
    android:orientation="vertical"
    android:padding="5dp" >

    <LinearLayout
        android:id="@+id/layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:background="@drawable/bg_linearlayout"
        android:orientation="vertical"
        android:padding="0.2px" >

        <RelativeLayout
            android:id="@+id/relativelayout"
            android:padding="2dp"
            android:onClick="onClick"
            android:layout_width="wrap_content"
            android:layout_height="42dp" >

            <TextView
                android:id="@+id/tv_value"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_centerVertical="true"
                android:layout_marginRight="50dp"
                android:background="#fff"
                android:ellipsize="end"
                android:gravity="left|center"
                android:hint="請選擇"
                android:paddingLeft="10dp"
                android:singleLine="true"
                android:textColor="#ff000000"
                android:textSize="18sp" >
            </TextView>

            <LinearLayout
                android:id="@+id/bt_dropdown"
                android:layout_width="50dp"
                android:layout_height="match_parent"
                android:layout_alignParentRight="true"
                android:background="#fff"
                android:gravity="center"
                >

                <ImageView
                    android:layout_width="20dp"
                    android:layout_height="20dp"
                    android:background="@drawable/arrow_down" />
            </LinearLayout>
        </RelativeLayout>
    </LinearLayout>

</RelativeLayout>
2. spiner_window_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:background="#ffffff"
    android:orientation="vertical">

    <ListView
        android:id="@+id/listview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_linearlayout"
        android:cacheColorHint="#00000000"
        android:scrollbars="none"></ListView>

</LinearLayout>

3. spiner_item_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#00000000"
    android:gravity="center_vertical"
    android:minHeight="40dp">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00000000"
        android:gravity="center"
        android:textColor="@color/black"
        android:textSize="18sp" />

</LinearLayout>

二、定義SpinerPopWindow類

  SpinerPopWindow.java 類

package com.hykjsjkj.customspiner;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.PopupWindow;
import java.util.List;
/**
 * Copyright: Copyright (c) 2017-2025
 * Company:
 *
 * @author: 趙小賤
 * @date: 2017/8/23
 * describe:
 */
public class SpinerPopWindow extends PopupWindow implements OnItemClickListener {

    private Context mContext;
    private ListView mListView;
    private SpinerAdapter mAdapter;
    private SpinerAdapter.IOnItemSelectListener mItemSelectListener;
    
    public SpinerPopWindow(Context context) {
        super(context);

        mContext = context;
        init();
    }
    
    public void setItemListener(SpinerAdapter.IOnItemSelectListener listener) {
        mItemSelectListener = listener;
    }

    public void setAdatper(SpinerAdapter adapter) {
        mAdapter = adapter;
        mListView.setAdapter(mAdapter);
    }


    private void init() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.spiner_window_layout, null);
        setContentView(view);
        setWidth(LayoutParams.WRAP_CONTENT);
        setHeight(LayoutParams.WRAP_CONTENT);

        setFocusable(true);
        ColorDrawable dw = new ColorDrawable(0x00);
        setBackgroundDrawable(dw);


        mListView = (ListView) view.findViewById(R.id.listview);
        mListView.setOnItemClickListener(this);
    }


    public void refreshData(List<String> list, int selIndex) {
        if (list != null && selIndex != -1) {
            if (mAdapter != null) {
                mAdapter.refreshData(list, selIndex);
            }
        }
    }
    
    @Override
    public void onItemClick(AdapterView<?> arg0, View view, int pos, long arg3) {
        dismiss();
        if (mItemSelectListener != null) {
            mItemSelectListener.onItemClick(pos);
        }
    }
    
}

三、定義Adapter

SpinerAdapter.java
package com.hykjsjkj.customspiner;

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

import java.util.List;

/**
 * Copyright: Copyright (c) 2017-2025
 * Company:
 *
 * @author: 趙小賤
 * @date: 2017/8/23
 * describe:
 */
public class SpinerAdapter extends BaseAdapter {

    public static interface IOnItemSelectListener {
        public void onItemClick(int pos);
    }

    ;

    private List<String> mObjects;

    private LayoutInflater mInflater;

    public SpinerAdapter(Context context, List<String> mObjects) {
        this.mObjects = mObjects;
        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }


    public void refreshData(List<String> objects, int selIndex) {
        mObjects = objects;
        if (selIndex < 0) {
            selIndex = 0;
        }
        if (selIndex >= mObjects.size()) {
            selIndex = mObjects.size() - 1;
        }
    }


    @Override
    public int getCount() {

        return mObjects.size();
    }

    @Override
    public Object getItem(int pos) {
        return mObjects.get(pos).toString();
    }

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

    @Override
    public View getView(int pos, View convertView, ViewGroup arg2) {
        ViewHolder viewHolder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.spiner_item_layout, null);
            viewHolder = new ViewHolder();
            viewHolder.mTextView = (TextView) convertView.findViewById(R.id.textView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        //Object item =  getItem(pos);
        viewHolder.mTextView.setText(mObjects.get(pos));

        return convertView;
    }


    public static class ViewHolder {
        public TextView mTextView;
    }

}

四、呼叫示例

MainActivity
package com.hykjsjkj.customspiner;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright: Copyright (c) 2017-2025
 * Company:
 *
 * @author: 趙小賤
 * @date: 2017/8/23
 * describe:
 */
public class MainActivity extends Activity implements View.OnClickListener, SpinerAdapter.IOnItemSelectListener {

    private List<String> mListType = new ArrayList<String>();  //型別列表
    private TextView mTView;
    private SpinerAdapter mAdapter;
    private RelativeLayout relativeLayout;
    private SpinerPopWindow mSpinerPopWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTView = (TextView) findViewById(R.id.tv_value);
        relativeLayout = (RelativeLayout) findViewById(R.id.relativelayout);


        //初始化資料
        mListType.add("大家好!");
        mListType.add("老司機開車啦");
        mListType.add("快上車");
        mListType.add("快下班了");
        mListType.add("下班回家做好吃的");
        mListType.add("啦啦啦啦···");

        mAdapter = new SpinerAdapter(this, mListType);
        mAdapter.refreshData(mListType, 0);


        //初始化PopWindow
        mSpinerPopWindow = new SpinerPopWindow(this);
        mSpinerPopWindow.setAdatper(mAdapter);
        mSpinerPopWindow.setItemListener(this);

    }



    //設定PopWindow
    private void showSpinWindow() {
        //設定mSpinerPopWindow顯示的寬度
        mSpinerPopWindow.setWidth(relativeLayout.getWidth());
        //設定顯示的位置在哪個控制元件的下方
        mSpinerPopWindow.showAsDropDown(relativeLayout);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.relativelayout:
                showSpinWindow();//顯示SpinerPopWindow
                break;
        }
    }


    /**
     * SpinerPopWindow中的條目點選監聽
     * @param pos
     */
    @Override
    public void onItemClick(int pos) {

        String value = mListType.get(pos);
        mTView.setText(value.toString());

    }

}
以上就是所有的程式碼了,希望對大家有所幫助,下面會附上原始碼,有需要的可以下載來參考: