<?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" android:padding="16dp"> <ImageView android:id="@+id/iv" android:layout_width="40dp" android:layout_height="40dp" android:layout_centerVertical="true"/> <RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_toRightOf="@+id/iv" android:layout_centerVertical="true"> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="25sp" android:textColor="#000000" /> </RelativeLayout> </RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.listview.MainActivity" > <ListView android:id="@+id/listView1" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" > </ListView> </RelativeLayout>
package com.example.listview; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; public class MainActivity extends ActionBarActivity { private String[] title = { "京东商城", "QQ", "QQ斗地主", "新浪微博", "天猫", "UC浏览器", "微信" }; private int[] icons = { R.drawable.jingdong, R.drawable.qq, R.drawable.doudizhu, R.drawable.weibo, R.drawable.tianmao, R.drawable.uc, R.drawable.weixin }; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView lv = (ListView) findViewById(R.id.listView1); // 创建adapter对象 MyBaseAdapter md = new MyBaseAdapter(); // Listview绑定adapter lv.setAdapter(md); } class MyBaseAdapter extends BaseAdapter { @Override public int getCount() { // TODO Auto-generated method stub return title.length; } @Override public Object getItem(int position) { // TODO Auto-generated method stub return title[position]; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View view = View.inflate(MainActivity.this, R.layout.list_item, null); TextView tv1 = (TextView) view.findViewById(R.id.title); ImageView iv1 = (ImageView) view.findViewById(R.id.iv); tv1.setText(title[position]); iv1.setBackgroundResource(icons[position]); return view; } } }