目录
activity_main.xml
FruitAdapter
Fruit类
fruit_item.xml
Activity
运行截图
项目文件
activity_main.xml
FruitAdapter
(虽然是通讯录,但是因为书上是拿水果举的例子,所以文件的命名也就照搬了)在包内创建一个Java类并命名为FruitAdapter,输入代码如下:
public class FruitAdapter extends ArrayAdapter {
private int resouceId;
public FruitAdapter(Context context, int textViewResourceId, List objects) {
super(context, textViewResourceId, objects);
resouceId = textViewResourceId;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Fruit fruit = getItem(position);
View view;
if (convertView == null) {
view = LayoutInflater.from(getContext()).inflate(resouceId,parent,false);
} else {
view = convertView;
}
ImageView fruitImage = (ImageView) view.findViewById(R.id.fruit_image);
TextView fruitName = (TextView) view.findViewById(R.id.fruit_name);
fruitImage.setImageResource(fruit.getImageId());
fruitName.setText(fruit.getName());
return view;
}
}
Fruit类
在包里创建Java类并命名为Fruit,代码如下:
public class Fruit {
private String name;
private int imageId;
public Fruit(String name, int imageId) {
this.name = name;
this.imageId = imageId;
}
public String getName() {
return name;
}
public int getImageId() {
return imageId;
}
}
fruit_item.xml
创建layout文件并命名为fruit_item,代码如下:
Activity
public class MainActivity extends AppCompatActivity {
private List fruitList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFruits();//初始化水果数据
FruitAdapter adapter = new FruitAdapter(MainActivity.this,
R.layout.fruit_item,fruitList);
ListView listView = (ListView) findViewById(R.id.list_view);
listView.setAdapter(adapter);
}
//对图片进行加载,图片放在mian/res/drawable里面
private void initFruits() {
for(int i=0; i < 3; i++) {
Fruit apple = new Fruit("周杰伦",R.drawable.image04);
fruitList.add(apple);
Fruit banana = new Fruit("哆啦",R.drawable.image02);
fruitList.add(banana);
Fruit orange = new Fruit("天皇",R.drawable.image03);
fruitList.add(orange);
}
}
}
运行截图
项目文件
AndroidStudio实验四:手机通讯录(ListView的应用)-Android文档类资源-CSDN下载AndroidStudio实验四:手机通讯录(ListView的应用)更多下载资源、学习资料请访问CSDN下载频道.https://download.csdn.net/download/nazonomaster/85219538
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)