1. 程式人生 > >android-下拉更多列表

android-下拉更多列表

現在很多的登入介面都有記住賬號的的這個功能,在點選輸入賬號的時候會出現一個列表供使用者選擇。點選其中的條目後會自動把資訊填充到文字框當中。

然後我用PopupWindow元件實現了一個點選更多按鈕實現更多列表的一個功能,這個下拉更多列表的效果如下:

接下來我們就開始一步一步的實現下拉更多列表功能。

1、首先新建一個對話方塊,佈局檔案login_layout.xml如下:`

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

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="50dp" >

        <TextView
            android:id="@+id/xygame_login_title_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="登入"
            android:textSize="20sp" />
    </RelativeLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0.1dp"
        android:background="@android:color/darker_gray" />

    <TextView
        android:id="@+id/xygame_login_accountPrompt_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center_vertical"
        android:paddingLeft="10dp"
        android:text="請登入"
        android:textSize="15sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:paddingLeft="10dp"
        android:paddingRight="10dp" >

        <LinearLayout
            android:id="@+id/login_account_ll"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

            <EditText
                android:id="@+id/login_account_et"
                android:layout_width="0dp"
                android:layout_height="match_parent"
                android:layout_margin="0.1dp"
                android:layout_weight="1"
                android:hint="使用者名稱/手機號"
                android:singleLine="true"
                android:textSize="15sp" />

            <RelativeLayout
                android:id="@+id/login_down_more_rl"
                android:layout_width="50dp"
                android:layout_height="match_parent" >

                <ImageView
                    android:id="@+id/login_down_more_iv"
                    android:background="@drawable/down_more_icon"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_centerInParent="true" />
            </RelativeLayout>
        </LinearLayout>

        <EditText
            android:id="@+id/login_password_et"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="0.1dp"
            android:gravity="center_vertical"
            android:hint="請輸入密碼"
            android:inputType="textPassword"
            android:singleLine="true"
            android:textSize="15dp" />

        <Button
            android:id="@+id/login_in_btn"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:text="登入"
            android:textColor="#ffffff"
            android:textSize="15sp" />

    </LinearLayout>

</LinearLayout>

2、繼承自DialogFragment實現一個對話方塊,並把佈局檔案加進去
<pre name="code" class="java">import java.util.ArrayList;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DialogFragment;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow.OnDismissListener;

@SuppressLint("NewApi") 
public class LoginDialog extends DialogFragment implements OnClickListener{
	private View mDialog;
	private ImageView mMoreAccountIV;//更多列表的圖示
	private RelativeLayout mMoreAccountRL;//更多賬號的RelativeLayout
	private LinearLayout moreAccountParentView;	
	private LinearLayout mMoreAccountLL;
	private int mAccountPopWidth;	//賬號列表的長度
	private ListView mAccountListView; //更多列表的listview
	private PopupWindow mAccountPopWindow;
	private AccountAdapter mAdapter;
	private Button mLoginBtn;
	private EditText mAccountET,mPasswordET;
	private ArrayList<String> mAccountData; 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
		mDialog = inflater.inflate(R.layout.login_layout, null);
		initView();
		initData();
		return mDialog;
	}
	/**
	 * 初始化資料
	 */
	private void initData() {
		//當以前有登入過的話則顯示更多按鈕
		mAccountData = new ArrayList<String>();
		mAccountData.add("123456");
		mAccountData.add("12345");
		mAccountData.add("1234");
		mAccountData.add("123");
		if (mAccountData.size() > 0) {
			mMoreAccountRL.setVisibility(View.VISIBLE);
		}else {
			mMoreAccountRL.setVisibility(View.GONE);
		}
	}
	private void initView() {
		
		mLoginBtn = (Button) mDialog.findViewById(R.id.login_in_btn);
		mMoreAccountRL = (RelativeLayout) mDialog.findViewById(R.id.login_down_more_rl);
		mMoreAccountLL = (LinearLayout) mDialog.findViewById(R.id.login_account_ll);
		mMoreAccountIV = (ImageView) mDialog.findViewById(R.id.login_down_more_iv);
		mAccountET = (EditText) mDialog.findViewById(R.id.login_account_et);
		mPasswordET = (EditText) mDialog.findViewById(R.id.login_password_et);
		
		mLoginBtn.setOnClickListener(this);
		mMoreAccountRL.setOnClickListener(this);
	}
	
	/**
	 * 初始化更多列表
	 */
	private void initWidget() {
		//沒有在initData有賬號的時候就初始化更多列表是因為那個時候無法獲取賬號列表的長度
		if (mAdapter == null) {
			mAdapter = new AccountAdapter(getActivity(),mAccountData);
		}
		//設定在更多列表裡的Listview
		mAccountListView = new ListView(getActivity());
		LayoutParams moreParam = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		mAccountListView.setLayoutParams(moreParam);
		moreAccountParentView = new LinearLayout(getActivity());
		LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
				ViewGroup.LayoutParams.WRAP_CONTENT);
		moreAccountParentView.setLayoutParams(params);
		moreAccountParentView.addView(mAccountListView);
		mAccountListView.setAdapter(mAdapter);

		if (mAccountPopWindow == null){
			mAccountPopWidth = mMoreAccountLL.getWidth();
			mAccountPopWindow = new PopupWindow(moreAccountParentView, mAccountPopWidth, ViewGroup.LayoutParams.WRAP_CONTENT,true);
		}
		initPopupWindowHeight();
		mAccountPopWindow.setOutsideTouchable(false);
		mAccountPopWindow.setBackgroundDrawable(new BitmapDrawable());
	}
	

	/**
	 * 設定顯示下拉高度 為三個item高度
	 */
	private void initPopupWindowHeight() {
		// 獲取ListView對應的Adapter
		ListAdapter listAdapter = mAccountListView.getAdapter();
		if (listAdapter == null) {
			return;
		}
		int totalHeight = 0;
		ViewGroup.LayoutParams params = mAccountListView.getLayoutParams();

		View listItem = listAdapter.getView(0, null, mAccountListView);
		listItem.measure(0, 0); // 計運算元項View 的寬高
		totalHeight += (listItem.getMeasuredHeight()) * 3; // 3個item的總高度
		params.height = totalHeight
				+ (mAccountListView.getDividerHeight() * (listAdapter.getCount() - 1));
		// listView.getDividerHeight()獲取子項間分隔符佔用的高度
		// params.height最後得到整個ListView完整顯示需要的高度
		mAccountListView.setLayoutParams(params);
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.login_down_more_rl:	//點選下拉更多按鈕
			initWidget();
			showList();
			mMoreAccountIV.setBackgroundResource(R.drawable.pull_icon);
			break;
		case R.id.login_in_btn:	//點選登入
			
			break;

		}
	}
	/**
	 * 顯示列表
	 */
	private void showList() {
		mAccountPopWindow.showAsDropDown(mMoreAccountLL, 0, 0);
		mAccountPopWindow.setOnDismissListener(new OnDismissListener() {

			@Override
			public void onDismiss() {
				mMoreAccountIV.setBackgroundResource(R.drawable.down_more_icon);
			}
		});
	}
	/**
	 * dp轉化成px
	 */
	private int dip2px(Context context, float dpValue) {
		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dpValue * scale + 0.5f);
	}

	private class AccountAdapter extends BaseAdapter{
		private ArrayList<String> mMoreAccountList;
		private Activity mActivity;

		public AccountAdapter(Activity activity, ArrayList<String> moreAccount) {
			mActivity = activity;
			mMoreAccountList = moreAccount;
		}

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

		@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) {
			MoreAccountHolder mHolder;
			if (convertView == null) {
				mHolder = new MoreAccountHolder();
				LinearLayout mainLinearLayout = new LinearLayout(mActivity);
				// mainLinearLayout.setBackgroundResource();

				LinearLayout mainLayout = new LinearLayout(mActivity);
				LinearLayout.LayoutParams mainParams = new LinearLayout.LayoutParams(
						ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.WRAP_CONTENT);
				mainLayout.setBackgroundResource(android.R.color.white);
				
				//account text
				TextView itemText = new TextView(mActivity);
				LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(
						ViewGroup.LayoutParams.MATCH_PARENT,
						ViewGroup.LayoutParams.WRAP_CONTENT, 1);
				textParams.setMargins(dip2px(getActivity(),6) ,
						dip2px(getActivity(),6), 0,dip2px(getActivity(),6));
				itemText.setTextSize(12);
				itemText.setPadding(dip2px(getActivity(),10) , 0, 0, 0);
				mainLayout.addView(itemText, textParams);
				
				//delete icon
				ImageView deleteIcon = new ImageView(mActivity);
	            LinearLayout.LayoutParams iconParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
	                    ViewGroup.LayoutParams.WRAP_CONTENT);
	            iconParams.gravity = Gravity.CENTER;
	            iconParams.setMargins(0, 0, dip2px(getActivity(),30), 0);
	            deleteIcon.setBackgroundResource(R.drawable.delete_icon);//設定刪除圖示
	            mainLayout.addView(deleteIcon, iconParams);
	            mainLinearLayout.addView(mainLayout, mainParams);
	            
	            convertView = mainLinearLayout;
	            mHolder.popupAccountContent = itemText;
	            mHolder.popupAccountDelete = deleteIcon;
	            
	            convertView.setTag(mHolder);
			}else{
				mHolder = (MoreAccountHolder) convertView.getTag();
			}
			mHolder.popupAccountContent.setText(mMoreAccountList.get(position));
			mHolder.popupAccountContent.setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View v) {
	                mAccountET.setText(mMoreAccountList.get(position));
	                mPasswordET.setText("123456");
	                mAccountPopWindow.dismiss();
	            }
	        });
			//點選刪除icon的時候操作  這個時候最好是顯示一個刪除的對話方塊 
	        mHolder.popupAccountDelete.setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View v) {
	            	mMoreAccountList.remove(position);
	            }
	        });
	        return convertView;
		}

		class MoreAccountHolder {
			TextView popupAccountContent;
			ImageView popupAccountDelete;
		}
	}
	
}


3、MainActivity如下:

import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
	private Button showDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        showDialog = (Button) findViewById(R.id.showDialog);
        showDialog.setOnClickListener(new OnClickListener() {
			
			@SuppressLint("NewApi") @Override
			public void onClick(View v) {
				LoginDialog dialog = new LoginDialog();
				dialog.show(getFragmentManager(), "LoginDialog");
			}
		});
    }
    
}