android仿通讯录

代码部分抄袭

给出代码跟效果:

friend.xml

<?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"
    android:orientation="vertical" >
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <ListView
            android:id="@+id/list_view"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:scrollbars="none" >
        </ListView>

        <com.example.menu.MyLetterListView
            android:id="@+id/my_list_view"
            android:layout_width="30dip"
            android:layout_height="fill_parent"
            android:layout_alignParentRight="true"
             />
    </RelativeLayout>

</LinearLayout>

friend_header.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:paddingLeft="2dip"
    android:paddingRight="2dip" >

    <TextView
        android:id="@+id/friend_search_head_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:clickable="true"
        android:textSize="20sp" >
    </TextView>

    <ImageView
        android:id="@+id/friend_center_back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|center"
        android:clickable="true" >
    </ImageView>
</FrameLayout>

list_item.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" >

    <TextView
        android:id="@+id/alpha"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#333333"
        android:paddingLeft="10dip"
        android:textColor="#FFFFFF"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:background="@drawable/contact_list_icon"
        android:layout_below="@id/alpha" />

    <View
        android:id="@+id/divider"
        android:layout_width="1.0dip"
        android:layout_height="fill_parent"
        android:layout_below="@id/alpha"
        android:layout_marginRight="11.0dip"
        android:layout_toRightOf="@id/imageView" />

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignTop="@id/divider"
        android:layout_marginLeft="2.0dip"
        android:layout_marginRight="5.0dip"
        android:layout_marginTop="6.0dip"
        android:layout_toRightOf="@id/divider"
        android:singleLine="true"
        android:textAppearance="?android:textAppearanceMedium" />

    <TextView
        android:id="@+id/number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@id/name"
        android:layout_alignWithParentIfMissing="true"
        android:layout_below="@id/name"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:textAppearance="?android:textAppearanceSmall" />

</RelativeLayout>

overlay.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    

</TextView>
suspend_search.xml

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

</ImageView>

Friend.java

package com.example.menu;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import com.example.menu.MyLetterListView.OnTouchingLetterChangedListener;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.PixelFormat;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class Friend extends Activity
{

	private BaseAdapter adapter;

	private ListView listview;

	private TextView overlay;

	private ImageView suspend_search;

	private MyLetterListView letterListView;

	private AsyncQueryHandler asyncQuery;

	private static final String NAME = "name", NUMBER = "number",
			SORT_KEY = "sort_key";

	private HashMap<String, Integer> alphaIndexer;

	private String[] sections;

	public List<ContentValues> list = new ArrayList<ContentValues>();

	private WindowManager windowManager;

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.friend);
		windowManager =
				(WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
		asyncQuery = new MyAsyncQueryHandler(getContentResolver());
		listview = (ListView) findViewById(R.id.list_view);
		letterListView = (MyLetterListView) findViewById(R.id.my_list_view);
		letterListView
				.setOnTouchingLetterChangedListener(new LetterListViewListener());

		alphaIndexer = new HashMap<String, Integer>();
		new Handler();
		new OverlayThread();
		initOverlay();
		initSuSearch();
		if (list.size() > 0)
		{
		}

		listview.setOnScrollListener(new OnScrollListener()
		{

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState)
			{
				suspend_search.setVisibility(View.VISIBLE);
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount)
			{
				suspend_search.setVisibility(View.GONE);
			}
		});
		suspend_search.setOnClickListener(new OnClickListener()
		{

			@Override
			public void onClick(View v)
			{
				ComponentName friendcName =
						new ComponentName(Friend.this,
								"com.example.test_intent.FriendSearch");
				Intent friend_viewIntent = new Intent();
				friend_viewIntent.setComponent(friendcName);
				startActivity(friend_viewIntent);
				Toast.makeText(getApplicationContext(), "sousuo",
						Toast.LENGTH_LONG).show();
				// TODO Auto-generated method stub
			}
		});
	}

	@SuppressWarnings("deprecation")
	public void getContent()
	{
		Cursor cur =
				getContentResolver().query(
						ContactsContract.Contacts.CONTENT_URI, null, null,
						null, null);
		startManagingCursor(cur);
	}

	@Override
	protected void onResume()
	{
		super.onResume();
		Uri uri = Uri.parse("content://com.android.contacts/data/phones");
		String[] projection = { "_id", "display_name", "data1", "sort_key" };
		asyncQuery.startQuery(0, null, uri, projection, null, null,
				"sort_key COLLATE LOCALIZED asc");
	}

	private class MyAsyncQueryHandler extends AsyncQueryHandler
	{

		public MyAsyncQueryHandler(ContentResolver cr)
		{
			super(cr);
		}

		@Override
		protected void onQueryComplete(int token, Object cookie, Cursor cursor)
		{

			cursor.moveToFirst();
			Log.d("ccccc",
					cursor.getString(0) + " 000 " + cursor.getString(1)
							+ " 000 " + cursor.getString(2) + " 000 "
							+ cursor.getString(3));

			while (cursor.moveToNext())
			{
				ContentValues cv = new ContentValues();
				cv.put(NAME, cursor.getString(1));
				cv.put(NUMBER, cursor.getString(2));
				cv.put(SORT_KEY, cursor.getString(3));
				list.add(cv);
			}
			if (list.size() > 0)
			{
				setAdapter(list);
			}
		}

	}

	private void setAdapter(List<ContentValues> list)
	{
		adapter = new ListAdapter(this, list);
		listview.setAdapter(adapter);

	}

	private class ListAdapter extends BaseAdapter
	{

		private LayoutInflater inflater;

		private List<ContentValues> list;

		public ListAdapter(Context context, List<ContentValues> list)
		{
			this.inflater = LayoutInflater.from(context);
			this.list = list;
			alphaIndexer = new HashMap<String, Integer>();
			sections = new String[list.size()];

			for (int i = 0; i < list.size(); i++)
			{
				String currentStr = getAlpha(list.get(i).getAsString(SORT_KEY));
				String previewStr =
						(i - 1) >= 0 ? getAlpha(list.get(i - 1).getAsString(
								SORT_KEY)) : " ";
				if (!previewStr.equals(currentStr))
				{
					String name = getAlpha(list.get(i).getAsString(SORT_KEY));
					alphaIndexer.put(name, i);
					sections[i] = name;
				}
			}
		}

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

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

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

		@Override
		public View getView(int position, View convertView, ViewGroup parent)
		{
			ViewHolder holder;

			if (convertView == null)
			{
				convertView = inflater.inflate(R.layout.list_item, null);
				holder = new ViewHolder();
				holder.alpha = (TextView) convertView.findViewById(R.id.alpha);
				holder.name = (TextView) convertView.findViewById(R.id.name);
				holder.number =
						(TextView) convertView.findViewById(R.id.number);
				convertView.setTag(holder);
			}
			else
			{
				holder = (ViewHolder) convertView.getTag();
			}

			ContentValues cv = list.get(position);
			holder.name.setText(cv.getAsString(NAME));
			holder.number.setText(cv.getAsString(NUMBER));
			String currentStr =
					getAlpha(list.get(position).getAsString(SORT_KEY));
			String previewStr =
					(position - 1) >= 0 ? getAlpha(list.get(position - 1)
							.getAsString(SORT_KEY)) : " ";

			if (!previewStr.equals(currentStr))
			{
				holder.alpha.setVisibility(View.VISIBLE);
				holder.alpha.setText(currentStr);
			}
			else
			{
				holder.alpha.setVisibility(View.GONE);
			}

			return convertView;
		}

		private class ViewHolder
		{

			TextView alpha;

			TextView name;

			TextView number;
		}
	}

	private void initSuSearch()// 搜索
	{
		LayoutInflater inflater = LayoutInflater.from(this);
		suspend_search =
				(ImageView) inflater.inflate(R.layout.suspend_search, null);
		WindowManager.LayoutParams lp =
				new WindowManager.LayoutParams(80, 80, 170, -280,
						WindowManager.LayoutParams.TYPE_APPLICATION,
						WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
						PixelFormat.TRANSLUCENT);
		windowManager.addView(suspend_search, lp);
	}

	private void initOverlay()
	{
		LayoutInflater inflater = LayoutInflater.from(this);
		overlay = (TextView) inflater.inflate(R.layout.overlay, null);
		WindowManager.LayoutParams lp =
				new WindowManager.LayoutParams(
						120,
						120,
						100,
						0,
						WindowManager.LayoutParams.TYPE_APPLICATION,
						WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
								| WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
						PixelFormat.TRANSLUCENT);
		// WindowManager windowManager = (WindowManager)
		// this.getSystemService(Context.WINDOW_SERVICE);
		windowManager.addView(overlay, lp);
	}

	private class LetterListViewListener implements
			OnTouchingLetterChangedListener
	{

		@Override
		public void onTouchingLetterChanged(final String s, float y, float x)
		{
			if (alphaIndexer.get(s) != null)
			{
				int position = alphaIndexer.get(s);

				listview.setSelection(position);
				overlay.setText(sections[position]);
				overlay.setVisibility(View.VISIBLE);

			}
		}

		@Override
		public void onTouchingLetterEnd()
		{
			overlay.setVisibility(View.GONE);
		}
	}

	private class OverlayThread implements Runnable
	{

		@Override
		public void run()
		{
			overlay.setVisibility(View.GONE);
		}
	}

	private String getAlpha(String str)
	{
		if (str == null)
		{
			return "#";
		}

		if (str.trim().length() == 0)
		{
			return "#";
		}

		char c = str.trim().substring(0, 1).charAt(0);

		Pattern pattern = Pattern.compile("^[A-Za-z]+$");
		if (pattern.matcher(c + "").matches())
		{
			return (c + "").toUpperCase();
		}
		else
		{
			return "#";
		}
	}

	@Override
	protected void onDestroy()
	{
		if (windowManager != null)// 防止内存泄露
		{
			windowManager.removeView(overlay);
			windowManager.removeView(suspend_search);
		}
		super.onDestroy();
	}

}

MyLetterListView.java

package com.example.menu;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class MyLetterListView extends View
{

	private OnTouchingLetterChangedListener onTouchingLetterChangedListener;

	private String[] b = { "@", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
			"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
			"Y", "Z", "#" };

	int choose = -1;

	private Paint paint = new Paint();

	boolean showBkg = false;

	public MyLetterListView(Context context, AttributeSet attrs, int defStyle)
	{
		super(context, attrs, defStyle);

	}

	public MyLetterListView(Context context, AttributeSet attrs)
	{
		super(context, attrs);

	}

	public MyLetterListView(Context context)
	{
		super(context);
	}

	protected void onDraw(Canvas canvas)
	{
		super.onDraw(canvas);
		if (showBkg)
		{
			canvas.drawColor(Color.parseColor("#40000000"));
		}

		int height = getHeight();
		int width = getWidth();
		int singleHeight = height / b.length;
		for (int i = 0; i < b.length; i++)
		{
			paint.setTextSize(18f);
			paint.setColor(Color.BLACK);
			paint.setTypeface(Typeface.DEFAULT_BOLD);
			paint.setAntiAlias(true);
			if (i == choose)
			{
				paint.setColor(Color.parseColor("#3399ff"));
				paint.setFakeBoldText(true);
			}
			float xPos = width / 2 - paint.measureText(b[i]) / 2;
			float yPos = singleHeight * i + singleHeight;

			canvas.drawText(b[i], xPos, yPos, paint);

			paint.reset();
		}

	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent event)
	{
		final int action = event.getAction();
		final float y = event.getY();
		final float x = event.getX();
		final int oldChoose = choose;
		final OnTouchingLetterChangedListener listener =
				onTouchingLetterChangedListener;
		final int c = (int) (y / getHeight() * b.length);

		switch (action)
		{
		case MotionEvent.ACTION_DOWN:
			showBkg = true;
			if (oldChoose != c && listener != null)
			{
				if (c > 0 && c < b.length)
				{
					listener.onTouchingLetterChanged(b[c], y, x);
					choose = c;
					invalidate();
				}
			}

			break;
		case MotionEvent.ACTION_MOVE:
			if (oldChoose != c && listener != null)
			{
				if (c > 0 && c < b.length)
				{
					listener.onTouchingLetterChanged(b[c], y, x);
					choose = c;
					invalidate();
				}
			}
			break;
		case MotionEvent.ACTION_UP:
			showBkg = false;
			choose = -1;
			listener.onTouchingLetterEnd();
			invalidate();
			break;
		}
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event)
	{
		return super.onTouchEvent(event);
	}

	public void setOnTouchingLetterChangedListener(
			OnTouchingLetterChangedListener onTouchingLetterChangedListener)
	{
		this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;
	}

	public interface OnTouchingLetterChangedListener
	{

		public void onTouchingLetterEnd();

		public void onTouchingLetterChanged(String s, float y, float x);
	}
}

别忘了加权限:
<uses-permission android:name="android.permission.READ_CONTACTS" />

效果图:


















  • 4
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 8
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值