Android之Adapter总结
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<Spinner
android:id="@+id/subway_lines"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Spinner>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/subway_lines"
android:layout_alignLeft="@id/subway_lines"
android:id="@+id/select_line"
/>
</RelativeLayout>
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/station_listView"
/>
</LinearLayout>
然后是ListView布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_width="200px"
android:layout_height="fill_parent"
android:textSize="20px"
android:gravity="center_horizontal"
android:id="@+id/station_name"
/>
<TextView
android:layout_width="200px"
android:layout_height="fill_parent"
android:layout_toRightOf="@id/station_name"
android:textSize="20px"
android:layout_alignTop="@id/station_name"
android:id="@+id/station_info"
/>
</RelativeLayout>
接下来是Activity
public class SubwayActivity extends Activity {
private static final String TAG = "SubwayActivity";
private SubwayService subwayService;
private TextView selectLine;
private Spinner subwayLines;
private ArrayAdapter<String> linesAdapter;
private List<String> linesNames;
private ListView stationListView;
private SimpleAdapter stationsAdapter;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
stationListView = (ListView) findViewById(R.id.station_listView);
subwayService = new SubwayService(this);
//初始化数据
// subwayService.init();
List<SubwayLine> listLines = subwayService.getLineScrollData();
linesNames = new ArrayList<String>();
for (SubwayLine subwayLine : listLines) {
linesNames.add(subwayLine.getLineName());
}
// 第一步:添加一个下拉列表项的list,这里添加的项就是下拉列表的菜单项
selectLine = (TextView) findViewById(R.id.select_line);
subwayLines = (Spinner) findViewById(R.id.subway_lines);
// 第二步:为下拉列表定义一个适配器,这里就用到里前面定义的list。
linesAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,linesNames);
// 第三步:为适配器设置下拉列表下拉时的菜单样式。
linesAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// 第四步:将适配器添加到下拉列表上
subwayLines.setAdapter(linesAdapter);
//第五步:为下拉列表设置各种事件的响应,这个事响应菜单被选中
subwayLines.setOnItemSelectedListener(selectedListener);
/*下拉菜单弹出的内容选项触屏事件处理*/
subwayLines.setOnTouchListener(onTouchListener);
/*下拉菜单弹出的内容选项焦点改变事件处理*/
subwayLines.setOnFocusChangeListener(onFocusChangeListener);
}
/**
* 为下拉列表设置各种事件的响应,这个事响应菜单被选中
*/
private OnItemSelectedListener selectedListener = new Spinner.OnItemSelectedListener(){
@SuppressWarnings("unchecked")
public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {
String lineName = linesAdapter.getItem(arg2);
SubwayLine line = subwayService.findLine(lineName);
/*根据lineId查询出stations*/
List<SubwayStation> stations = subwayService.getStationLineScrollData(line.getLineId());
/*把stations的属性值放到List<HashMap<String, String>>中*/
List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>();
for (SubwayStation station : stations) {
HashMap<String, String> map = new HashMap<String, String>();
if(station.getIsChange() == 1){
map.put("stationName", station.getStationName());
List<SubwayStation> changeStations = subwayService.getChangeStationExceptThis(station.getStationName(), line.getLineId());
StringBuilder builder = new StringBuilder();
builder.append("换乘 ");
if(changeStations != null && changeStations.size() > 0){
for (SubwayStation changeStation : changeStations) {
SubwayLine changeLine = subwayService.findLine(changeStation.getLineId());
builder.append(changeLine.getLineName()).append(",");
}
builder.deleteCharAt(builder.length()-1);
}
map.put("stationInfo",builder.toString());
}else{
map.put("stationName", station.getStationName());
map.put("stationInfo", station.getStationInfo());
}
data.add(map);
}
/*设置stationsAdapter适配器*/
stationsAdapter = new SimpleAdapter(
SubwayActivity.this,
data,
R.layout.stationitem,
new String[] { "stationName", "stationInfo" },
new int[] { R.id.station_name, R.id.station_info });
stationListView.setAdapter(stationsAdapter);
/* 将所选mySpinner 的值带入myTextView 中*/
selectLine.setText("以下是:"+ lineName +" 车站列表...");
/* 将mySpinner 显示*/
arg0.setVisibility(View.VISIBLE);
}
@SuppressWarnings("unchecked")
public void onNothingSelected(AdapterView arg0) {
selectLine.setText("");
arg0.setVisibility(View.VISIBLE);
}
};
/**
* 下拉菜单弹出的内容选项触屏事件处理
*/
private OnTouchListener onTouchListener = new Spinner.OnTouchListener(){
public boolean onTouch(View v, MotionEvent event) {
/* 将mySpinner 隐藏,不隐藏也可以,看自己爱好*/
// v.setVisibility(View.INVISIBLE);
return false;
}
};
/**
* 下拉菜单弹出的内容选项焦点改变事件处理
*/
private OnFocusChangeListener onFocusChangeListener = new Spinner.OnFocusChangeListener(){
public void onFocusChange(View v, boolean hasFocus) {
v.setVisibility(View.VISIBLE);
}
};
}
其中,核心的是
stationsAdapter = new SimpleAdapter(
SubwayActivity.this,
data,
R.layout.stationitem,
new String[] { "stationName", "stationInfo" },
new int[] { R.id.station_name, R.id.station_info });
stationListView.setAdapter(stationsAdapter);
以上是简单的使用adapter的方法,一般情况下这样就够用了.接下来是自定义adapter.
private Context context;
private List<Weather> weatherList; //这就是adapter关联的List,用来存储数据.还记的ArrayList
public WeatherAdapter(Context context, List<Weather> weatherList ) {
this.context = context;
this.weatherList = weatherList;
}
public int getCount() {
return weatherList.size();
}
public Object getItem(int position) {
return weatherList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Weather weather = weatherList.get(position);
return new WeatherAdapterView(this.context, weather );
}
}
public static final String LOG_TAG = "WeatherAdapterView";
public WeatherAdapterView(Context context,
Weather weather ) {
super( context );
this.setOrientation(HORIZONTAL);
LinearLayout.LayoutParams cityParams =
new LinearLayout.LayoutParams(100, LayoutParams.WRAP_CONTENT);
cityParams.setMargins(1, 1, 1, 1);
TextView cityControl = new TextView( context );
cityControl.setText( weather.getCity() );
addView( cityControl, cityParams);
LinearLayout.LayoutParams temperatureParams =
new LinearLayout.LayoutParams(20, LayoutParams.WRAP_CONTENT);
temperatureParams.setMargins(1, 1, 1, 1);
TextView temperatureControl = new TextView(context);
temperatureControl.setText( Integer.toString( weather.temperature ) );
addView( temperatureControl, temperatureParams);
LinearLayout.LayoutParams skyParams =
new LinearLayout.LayoutParams(25, LayoutParams.WRAP_CONTENT);
ImageView skyControl = new ImageView( context );
Log.d( LOG_TAG, weather.getCity()+" -> "+weather.sky );
skyControl.setImageResource( weather.getSkyResource() );
addView( skyControl, skyParams );
}
}
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<Weather> weatherList = new ArrayList<Weather>();
Weather w = new Weather( "London", 17, Weather.OVERCAST );
weatherList.add( w );
w = new Weather( "Paris", 22, Weather.OVERCAST );
weatherList.add( w );
w = new Weather( "Athens", 29, Weather.SUNNY );
weatherList.add( w );
w = new Weather( "Stockholm", 12, Weather.RAIN );
weatherList.add( w );
WeatherAdapter weatherAdapter = new WeatherAdapter(
this,
weatherList );
setListAdapter( weatherAdapter );
}
}
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.topic_list, null);
holder.title = (TextView) convertView.findViewById(R.id.title);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
}
public class ViewHolder {
public TextView getTitle() {
if (title == null) {
title = (TextView) baseView.findViewById(R.id.title);
}
return title;
}
}
public View getView(int position, View view, ViewGroup parent) {
View convertView = m.get(position);
if (convertView != null) {
return convertView;
} else {
convertView = inflater.inflate(R.layout.topic_list, null);
TextView title = (TextView) convertView.findViewById(R.id.title);
m.put(position, convertView);
}
}
Adapter是用来帮助填充数据的中间桥梁,比如通过它将数据填充到ListView, GridView, Gallery.而android 提供了几种Adapter:ArrayAdapter<T>, BaseAdapter, CursorAdapter, HeaderViewListAdapter, ListAdapter, ResourceCursorAdapter, SimpleAdapter, SimpleCursorAdapter, SpinnerAdapter, WrapperListAdapter.我猜想这些Adapter的区别在于你的数据来源不一样:比如若你的数据来源于一个Arraylist 就使用BaseAdapter,SimpleAdapter,而数据来源于通过查询数据库获得Cursor那就使用SimpleCursorAdapter等。就目前我经常使用的BaseAdapter和SimpleCursorAdapter。
1,BaseAdapter:---数据来源于Arraylist-->MyArraylist
当你继承BaseAdapter客制化你的Adapter时,你必须OverWrite以下函数:
Java代码
@Override
public int getCount() {
// TODO Auto-generated method stub
System.out.println("the size is\t" + MyArraylist.size());
return MyArraylist.size();
}
@Override
public int getCount() {
// TODO Auto-generated method stub
System.out.println("the size is\t" + MyArraylist.size());
return MyArraylist.size();
}
getCount返回的就是你的有多少条数据需要绑定的,也就是需要多少个View.比如这里返回的就是MyArraylist的Size.
Java代码
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
if (v == null) {
view = mInflater.inflate(R.layout.track_list_item, null);
} else {
view = v;
}}
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
View view;
if (v == null) {
view = mInflater.inflate(R.layout.track_list_item, null);
} else {
view = v;
}}
通过getView就获得了view来显示数据了。在这里你就可以自定义你的View了,但你通过XML定义可以通过LayoutInflater来inflater你的XML。getView里面就可以将MyArraylist的数据通过position 这个来将数据一条绑定一个View了。
2,SimpleCursorAdapter:---数据来源于数据库--->MyCursor
要实现bindView()和newView()这两个抽象方法需要实现的内容。
public void bindView(View view, Context context, Cursor cursor),重用一个已有的view,使其显示当前cursor所指向的数据。
public View newView(Context context, Cursor cursor, ViewGroup parent),为cursor所指向的数据新建一个View对象,并显示其数据。
通俗的说:比如你一个listview在一个屏幕里一次只能显示8条数据,那么第一次显示的时候就会newView 8次生成8个View,调用bindView绑定8条数据,而你有16条数据,但你拖动滚动条看9-16条时,此时不会再调用newView了,而只能调用了bindView去绑定新的数据而了。这样就省了空间了。
注意:传入到CursorAdapter中的Cursor结果集必须包含有列名为_id的列,否则SimpleCursorAdapter将不会起作用。
对于SimpleCursorAdapter中的newView与bindView的作用在BaseAdapter中的getView中也有这样的意义:getView里面我们必须做判断才能达到这种效果,就是要判断第二个参数View的是否为空:当空时就Infalte新的View,但不为空时就要就用它,这样就第一屏幕Infate 8个View,后面就直接使用这个8个view了。
注意:getView中是返回一个view,必须返回的是你infalte之后不为空的View,不然会报空指针异常
Android之Adapter总结相关推荐
- Android之Adapter用法总结
本文转自http://kb.cnblogs.com/a/2328334/,转载请注明原出处. Android之Adapter用法总结 作者:Devin Zhang 来源:博客园 发布时间:2012 ...
- Android的Adapter用法总结
Android之Adapter用法总结 1.Adapter概念 定义为将一个类的接口变换成客户端所期待的一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作. 在androi ...
- Android自定义Adapter的ListView的思路及代码
Android自定义Adapter的ListView的思路及代码,需要的朋友可以参考一下 width="650" height="200" align=&quo ...
- android中Adapter适配器的讲解
android中Adapter适配器的讲解 Adapter(适配器的讲解) 适配器就我自己来看,我觉得这是一个非常重要的知识点,Adapter是用来帮助填出数据的中间桥梁,简单点说吧:将各种数据以合适 ...
- android 自定义adapter
Adapter是用来帮助填充数据的中间桥梁,比如通过它将数据填充到ListView, GridView, Gallery等,而android的adapter又有很多种(ArrayAdapter, Ba ...
- android适配器Adapter
一.什么是适配器,适配器有什么用? 适配器是AdapterView视图(如ListView - 列表视图控件.Gallery - 缩略图浏览器控件.GridView - 网格控件.Spinner - ...
- Android 使用Adapter适配器模式实现无线轮播BannerView
###代码实现 自定义ViewPager public class BannerViewPager extends ViewPager {private BannerAdapter mAdapter; ...
- Android 自定义Adapter以实现自定义填充ListView的Item
1>实体类---即ListView中各个Item中填充的内容 package com.demo.cxc.compoundview.com.demo.cxc.entity;import java. ...
- Android中Adapter适配器的介绍以及用法的总结
Adapter(适配器的讲解) 适配器就我自己来看,我觉得这是一个非常重要的知识点,Adapter是用来帮助填出数据的中间桥梁,简单点说吧:将各种数据以合适的形式显示在View中给用户看.Adapte ...
- android通用adapter,Android通用ListViewAdapter的编写。
一般来说,一个ListView的Adapter是继承自BaseAdapter,然后改写其中的getCount().getItem().getItemId().getView()等方法.其中最重要的是g ...
最新文章
- mysql中的输出,mysql-将输出结果作为SQL中的列
- vs2013缺少Mvc 怎么办?
- mc显示服务器生命值,[1.7-1.8]CombatIndicator — 全息显示攻击伤害的数值 让我的世界服务器更有游戏感...
- 使用SAP Analytics Cloud统计SAP C4C系统创建Lead里包含的产品信息分布情况
- win7桌面便签。自带的
- 常用的echo和cat,这次让我折在了特殊字符丢失问题上
- python怎样填充颜色_python – 使用颜色填充Tkinter画布对象之间的空间
- android gridview隐藏滚动条,如何禁用GridView中的ScrollViewer的滚动
- notifier chain — 内核通知链【转】
- C++编程语言中const关键字介绍
- 身为华人,我再一次不淡定了,中文输入项目启动
- CSS color设置与调色板
- Asp.net web api 知多少
- 11.30 如何取得当事人的银行账号?
- 记录-如何测试服务器是否支持ipv6
- 迁移oracle数据库,简简单单的Oracle数据库迁移方法
- kibana 7.5.1 + apm 7.5.1实现应用性能(apm)监控
- mysql远程主机强迫关闭了_HAProxy出现远程主机强迫关闭了一个现有的连接 的错误及解决...
- python的文本编辑器atom_python的各种编辑器-PyScripter、pycharm 、atom、vscode、Sublime Text等等...
- Python全栈(三)数据库优化之10.MySQL高级-表优化和索引优化
热门文章
- snmp是什么层协议_率先拥抱TSN——CC-Link发布新一代网络协议CC-Link IE TSN
- 指针01:指针的定义与使用
- 常见的网页布局(HTML、CSS)
- C# 委托事件传递参数
- java 走马灯程序,详解微信小程序实现跑马灯效果(附完整代码)
- 【收藏干货】axios配置大全
- @PathVariable、@RequestHeader与@CookieValue注解的使用案例
- 【Computer Organization笔记03】信息编码与码制转换,数据表示:检错与纠错、码距、汉明码等
- 【数据结构笔记43】C实现:寻找通话次数最多的电话号(散列表例题)
- 使用react-native做一个简单的应用-03欢迎界面