基础部分:为ListView的每一个项都设置成文字
1.定义一下Adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(context , android.R.layout.simple_list_item_1 , data);
context: 上下文环境
第二个参数: 布局样式
data数组文件: 如String [] data = {"张三","李四","王五","赵六","田七","钱八"};
2.找到对应的控件,设置它的adapter
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter( adapter);
扩展部分:使用自定义的界面设计
1.首先定义一个布局文件,这个布局文件用来设计你的ListView每一项的样式,一般是横向的LinearLayout
2.定义一个类,统一管理新样式中用到的资源
public class Fruit
{
int image;
string text;
public Fruit(int image,string content)
{
this.image =image;
this.content =content;
}
public string GetContext()
{
return text;
}
public int GetImage()
{
return image;
}
}
3.新建一个Adapter,继承自ArrayAdapter<Fruit>这里的泛型使用Fruit是因为在Fruit中定义了每个子项更新的时候用到的资源
public class FruitAdapter extends ArrayAdapter<Fruit>
{
int resourceId;
public FruitAdapter(Context context,int textViewResourceId ,List<Fruit> list)
{
super(context,textViewResourceId ,list);
resourceId = textViewResourceId ;
}
public View getView(int position ,View ConvertView,ViewGroup parent)
{
Fruit f = getItem(position); //获取当前位置的存储的子项的信息。所有信息已经封装在Fruit中
View view = LayoutInflater.from(getContext()).inflater(resourceId,parent,false);
ImageView image = (ImageView) view.findViewById(R.id.image);
TextView text = (TextView) view.findViewById(R.id.text);
image.setTmageResource(f.getImage());
text .setText(f.getContent());
return view;
}
}
FruitAdapter adapter = new FruitAdapter(context,R.layout.style,list);
listView.setAdapter(adapter);
优化滑动效率:
优化解释//实际上,在刷新ListView的时候,都需要代码中返回一个View,这个View的格式就是你自己定义的那个格式,所以会用到 view = LayoutInflater.from(getContext()).inflater(resourceId,parent,false);
其次,设置这个ViewHolder的作用是为了暂时保存ImageView和TextView的信息,当convertView不为空的时候,这个时候TextView和ImageView返回的还是上一次返回的数据,所以不需要改动。
public class ViewHolder
{
ImageView image;
TextView text;
}
public View getView(int position ,View ConvertView,ViewGroup parent)
{
Fruit f = getItem(position); //获取当前位置的存储的子项的信息。所有信息已经封装在Fruit中
View view ;
ViewHolder holder;
if(convertView==null)
{
view = LayoutInflater.from(getContext()).inflater(resourceId,parent,false);
holder = new ViewHolder();
holder.image = (ImageView) view.findViewById(R.id.image);
holder.text= (TextView) view.findViewById(R.id.text);
view.setTag(holder);
}
else
{
view = convertView;
holder = (ViewHolder)view.getTag();
}
holder.image.setTmageResource(f.getImage());
holder.text .setText(f.getContent());
return view;
}
点击事件:
setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent ,View view,int position,long id)
{
Fruit f = fruitlist.get(position);
····
}
}
)