项目中要求列表按照ABCD这种字母排序检索的功能,看了大神写的,瞬间崇拜了,接下来借大家参考参考了

首先是自定义view sidebar

 /**
* @author J
*一个自定义view 实现a-z的竖直绘制,和监听滑动事件
*/
public class SideBar extends View {
private OnTouchingLetterChangedListener onTouchingLetterChangedListener;
public static 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", "#" };
private int choose = -1;
private Paint paint = new Paint(); private TextView mTextDialog; public void setTextView(TextView mTextDialog) {
this.mTextDialog = mTextDialog;
} public SideBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
} public SideBar(Context context, AttributeSet attrs) {
super(context, attrs);
} public SideBar(Context context) {
super(context);
} protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int height = getHeight();
int width = getWidth();
int singleHeight = height / b.length; for (int i = 0; i < b.length; i++) {
paint.setColor(Color.parseColor("#333333"));
// paint.setColor(Color.WHITE);
paint.setAntiAlias(true);
paint.setTextSize(14);
if (i == choose) {
paint.setColor(Color.parseColor("#B8B8B8"));
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 int oldChoose = choose;
final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;
final int c = (int) (y / getHeight() * b.length); switch (action) {
case MotionEvent.ACTION_UP:
setBackgroundDrawable(new ColorDrawable(0x00000000));
choose = -1;//
invalidate();
if (mTextDialog != null) {
mTextDialog.setVisibility(View.INVISIBLE);
}
break; default:
// setBackgroundResource(R.drawable.sidebar_background);
if (oldChoose != c) {
if (c >= 0 && c < b.length) {
if (listener != null) {
listener.onTouchingLetterChanged(b[c]);
}
if (mTextDialog != null) {
mTextDialog.setText(b[c]);
mTextDialog.setVisibility(View.VISIBLE);
} choose = c;
invalidate();
}
} break;
}
return true;
} public void setOnTouchingLetterChangedListener(
OnTouchingLetterChangedListener onTouchingLetterChangedListener) {
this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;
} public interface OnTouchingLetterChangedListener {
void onTouchingLetterChanged(String s);
} }

接下来是整个布局的部署了activity_sortlist

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"> <ListView
android:id="@+id/country_lvcountry"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:divider="#eeeeee"
android:dividerHeight="1px" /> <LinearLayout
android:id="@+id/top_layout"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#f2f2f2"> <TextView
android:id="@+id/top_char"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="3dip"
android:paddingLeft="10dip"
android:paddingTop="3dip"
android:text=""
android:textColor="#333333"
android:textSize="14sp" />
</LinearLayout> <TextView
android:id="@+id/dialog"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:background="#999999"
android:gravity="center"
android:textColor="#ffffffff"
android:textSize="30dp"
android:visibility="invisible" /> <com.app.activitys.view.SideBar
android:id="@+id/sidrbar"
android:layout_width="25.0dip"
android:layout_height="fill_parent"
android:layout_gravity="right|center"
android:layout_marginBottom="10dp"
android:layout_marginTop="10dp" /> </FrameLayout>

接下来时使用了Sortlist

@ContentView(R.layout.activity_sortlist)
public class Sortlist extends BaseAppActivity {
private String[] strzimu = {"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", " "};
private CharacterParser characterParser;
private PinyinComparator pinyinComparator;
private List<MyBrandListSortModel> SourceDateList; // 数据
private BrandSortAdapter adapter; // 排序的适配器
String staus="";
private int lastFirstVisibleItem = -1;
@ViewInject(R.id.country_lvcountry)
private ListView sortListView;
@ViewInject(R.id.sidrbar)
private SideBar sideBar;
@ViewInject(R.id.dialog)
private TextView dialog;
@ViewInject(R.id.top_layout)
private LinearLayout xuanfuLayout;
@ViewInject(R.id.top_char)
private TextView xuanfaText;
@Override
protected void init() {
characterParser = CharacterParser.getInstance();
pinyinComparator = new PinyinComparator();
sideBar.setTextView(dialog);
SourceDateList = new ArrayList<>();
SourceDateList = filledData(SourceDateList);
Collections.sort(SourceDateList, pinyinComparator);
//这是设置adapter
adapter = new BrandSortAdapter(this, SourceDateList);
sortListView.setAdapter(adapter);
initEvent();
}
@Override
public void onResume() {
super.onResume();
getData();
}
private void initEvent() {
//listview的监听事件
sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() { @Override
public void onTouchingLetterChanged(String s) {
int position = adapter.getPositionForSection(s.charAt(0));
if (position != -1) {
sortListView.setSelection(position);
} }
});
sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//这边是点击处理的事件,大家自己随意写啊
} });
/**
* 设置滚动监听, 实时跟新悬浮的字母的值
*/
sortListView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub } @Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// Log.e("zzzzzzzz", "-----firstVisibleItem--->" + firstVisibleItem);
int section = adapter.getSectionForPosition(firstVisibleItem);
int nextSecPosition = -1;
if (!String.valueOf((char) section).equals(" ")) {
for (int i = 1; i < 26; i++) {
if (adapter.getPositionForSection(section + i) == -1) { } else {
nextSecPosition = adapter.getPositionForSection(section + i);
// Log.e("nextSecPosition", "-----nextSecPosition--->"+nextSecPosition );
break;
}
if (i == 25) {
nextSecPosition = firstVisibleItem + 1;
// Log.e("nextSecPosition2", "-----nextSecPosition2--->"+nextSecPosition );
}
}
} if ((firstVisibleItem != lastFirstVisibleItem) && adapter.getCount() > 0) {
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) xuanfuLayout
.getLayoutParams();
params.topMargin = 0;
xuanfuLayout.setLayoutParams(params);
xuanfaText.setText(String.valueOf((char) section));
}
if (nextSecPosition == firstVisibleItem + 1) {
// Log.e("nextSecPosition", "-----nextSecPosition--->" );
View childView = view.getChildAt(0);
if (childView != null) {
int titleHeight = xuanfuLayout.getHeight();
int bottom = childView.getBottom();
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) xuanfuLayout
.getLayoutParams();
if (bottom < titleHeight) {
float pushedDistance = bottom - titleHeight;
params.topMargin = (int) pushedDistance;
xuanfuLayout.setLayoutParams(params);
} else {
if (params.topMargin != 0) {
params.topMargin = 0;
xuanfuLayout.setLayoutParams(params);
}
}
}
}
lastFirstVisibleItem = firstVisibleItem;
}
});
} void getData(){
//获取数据
EGRequestParams params=new EGRequestParams();
String url="";//这边是接口
HttpUtil.post(this, url, params, new HttpUtil.Ok() {
@Override
public void success(String str) {
//通过modle将数据放入SourceDateList中
SourceDateList = JSON.parseArray(str, MyBrandListSortModel.class);
if (SourceDateList.size() > 0) {
SourceDateList = filledData(SourceDateList);
Collections.sort(SourceDateList, pinyinComparator);
}
updataview();
}
@Override
public void complete(String str) { }
});
}
private void updataview() {
adapter = new BrandSortAdapter(this, SourceDateList);
sortListView.setAdapter(adapter);
int section = adapter.getSectionForPosition(0);
ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) xuanfuLayout
.getLayoutParams();
params.topMargin = 0;
xuanfuLayout.setLayoutParams(params);
xuanfaText.setText(String.valueOf((char) section));
}
public class PinyinComparator implements Comparator<MyBrandListSortModel> { public int compare(MyBrandListSortModel o1, MyBrandListSortModel o2) {
if (o1.getSortLetters().equals(" ") || !o2.getSortLetters().equals(" ")) {
return 1;
} else if (!o1.getSortLetters().equals(" ")
|| o2.getSortLetters().equals(" ")) {
return -1;
} else {
return o1.getSortLetters().compareTo(o2.getSortLetters());
}
} }
/**
* 填充数据
*
* @param date
* @return
*/
private List<MyBrandListSortModel> filledData(List<MyBrandListSortModel> date) {
List<MyBrandListSortModel> mSortList = new ArrayList<MyBrandListSortModel>();
List<MyBrandListSortModel> mSortListTemp = new ArrayList<MyBrandListSortModel>();
mSortListTemp = date;
if (date.size() == 0) {
return mSortList;
}
for (int i = 0; i < date.size(); i++) {
String pinyin = characterParser.getSelling(date.get(i).getName());
String sortString = pinyin.substring(0, 1).toUpperCase();
if (sortString.matches("[A-Z]")) {
date.get(i).setSortLetters(sortString.toUpperCase());
} else {
date.get(i).setSortLetters(" ");
}
}
for (int i = 0; i < 27; i++) {
MyBrandListSortModel tempmodel = new MyBrandListSortModel();
for (int j = 0; j < date.size(); j++) {
Integer current = Integer.valueOf(mSortListTemp.get(j).getSortLetters().charAt(0));
Integer current2 = Integer.valueOf(strzimu[i].charAt(0));
if (current == current2) {
mSortList.add(date.get(j));
}
}
} return mSortList; }
}

接下来把Adapter也送上吧!(BrandSortAdapter)

 public class BrandSortAdapter extends BaseListAdapter {
private List<MyBrandListSortModel> list = null;
private Context mContext; public BrandSortAdapter(Context context, List<MyBrandListSortModel> list) {
super(context, list);
this.list=list;
this.mContext=context;
} public int getCount() {
return this.list.size();
} public Object getItem(int position) {
return list.get(position);
} public long getItemId(int position) {
return position;
} public View getView(final int position, View view, ViewGroup arg2) {
ViewHolder viewHolder = null;
final MyBrandListSortModel mContent = list.get(position);
if (view == null) {
viewHolder = new ViewHolder();
view = LayoutInflater.from(mContext).inflate(R.layout.list_item_mycarbrand, null);
viewHolder.tvTitle = (TextView) view
.findViewById(R.id.tv_user_item_name);
viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
int section;
if (list.size()>0){
section = getSectionForPosition(position);
}else{
section = 0;
}
if (position == getPositionForSection(section)) {
viewHolder.tvLetter.setVisibility(View.VISIBLE);
viewHolder.tvLetter.setText(mContent.getSortLetters());
} else {
viewHolder.tvLetter.setVisibility(View.GONE);
}
MyBrandListSortModel model = list.get(position);
String realname="- -";
if (!StringUtils.isEmpty(model.getName())){
realname=model.getName();
}
viewHolder.tvTitle.setText(realname);
// 头像采用imageloader加载 return view; } final static class ViewHolder {
TextView tvLetter;
TextView tvTitle;
} /**
* 得到首字母的ascii值
*/
public int getSectionForPosition(int position) {
return list.size()>0?list.get(position).
getSortLetters().
charAt(0):Integer.valueOf(' '); } public int getPositionForSection(int section) {
for (int i = 0; i < getCount(); i++) {
String sortStr = list.get(i).getSortLetters();
char firstChar = sortStr.toUpperCase().charAt(0);
if (firstChar == section) {
return i;
}
} return -1;
} public String getAlpha(String str) {
String sortStr = str.trim().substring(0, 1).toUpperCase();
if (sortStr.matches("[A-Z]")) {
return sortStr;
} else {
return " ";
}
} public Object[] getSections() {
return null;
}
}

modle也送给大家吧!MyBrandListSortModel

 public class MyBrandListSortModel extends Entity implements Serializable{

     private String id;
private String children;
private String name;
private String parentid;
private String parentids;
private String parentname;
private String type;
private String value;
private String sortLetters; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getSortLetters() {
return sortLetters;
} public void setSortLetters(String sortLetters) {
this.sortLetters = sortLetters;
} public void setChildren(String children) {
this.children = children;
}
public String getChildren() {
return children;
} public void setName(String name) {
this.name = name;
} public String getName() {
return name;
} public void setParentid(String parentid) {
this.parentid = parentid;
} public String getParentid() {
return parentid;
} public void setParentids(String parentids) {
this.parentids = parentids;
} public String getParentids() {
return parentids;
} public void setParentname(String parentname) {
this.parentname = parentname;
} public String getParentname() {
return parentname;
} public void setType(String type) {
this.type = type;
} public String getType() {
return type;
} public void setValue(String value) {
this.value = value;
} public String getValue() {
return value;
}
}

大家参考吧!

https://shop61408405.taobao.com/?spm=a1z10.5-c.0.0.cAfZMN&qq-pf-to=pcqq.group

上面链接都是一下技术视频,欢迎大家kan

05-11 11:13