1.在主布局定义一个listView
2.自定义一个布局,用来显示listView的列表单项 图文结构,2个键值对分别用来存储图片,文本,在加入集合。因此需要list
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"
android:dividerHeight="30dp"
android:divider="@color/colorAccent"
android:listSelector="#91ea93"/>
自定义布局,来存储选项
<LinearLayout
android:id="@+id/line"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@mipmap/ic_launcher"/>
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="20sp"
android:text="好好学习"
android:gravity="center"/>
</LinearLayout>
3..提供数据,SimpleAdapter适配器,通过适配器把数据绑定到listView上,绑定布局,对listView绑定事件,
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
private ArrayList<Map<String,Object>> data=new ArrayList<>();
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
listView.setOnItemClickListener(this);
String [] from =new String[]{"image","text"};
int [] to =new int[]{R.id.image,R.id.textView};
data = initdata(); //得到数据
//上下文 list组合map的数据,每个选项的布局,map的key值,选项布局中的组件id,后两个参数需要一一对应
SimpleAdapter adapter =new SimpleAdapter(this,data,R.layout.image_text,
from,to);
listView.setAdapter(adapter);
}
//数据得到方法
private ArrayList<Map<String,Object>> initdata() {
int count=0;
for (int i = 0; i <20 ; i++) {
Map<String,Object> map =new HashMap<>();
map.put("image",R.mipmap.ic_launcher);
map.put("text","罗贯中"+count);
count++;
data.add(map);
}
return data;
}
//listView的点击事件 view 是子类
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
LinearLayout line = (LinearLayout) view;
TextView textView = (TextView) line.findViewById(R.id.textView);
Toast.makeText(MainActivity.this, textView.getText().toString(), Toast.LENGTH_SHORT).show();
}