SimpleAdapter主要用于图文结合的内容
1.在主布局中添加<ListView>标签
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/lnlayout_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/lv_main"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
2.编写行布局
<?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="70dp"
>
<ImageView
android:id="@+id/im_logo"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="@mipmap/ic_launcher_round"
android:layout_alignParentLeft="true"
/>
<TextView
android:id="@+id/text_simple"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:gravity="center"
android:layout_alignParentRight="true"
android:text="实例"
android:textSize="24sp" />
</RelativeLayout>
行布局效果:
3.编写代码
package com.example.learningandroid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
//1.获取ListView对象
ListView listView ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = findViewById(R.id.lv_main);
//2.准备数据源
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> map = new HashMap<String,Object>();
map.put("im_logo",R.drawable.test);//键值对中,key为行布局xml中对应控件id,不是一定要一致,只是为了记忆方便
map.put("text_simple","实例1");
list.add(map);
map = new HashMap<String, Object>();
map.put("im_logo",R.drawable.test);
map.put("text_simple","实例2");
list.add(map);
//3.准备适配器
SimpleAdapter adapter = new SimpleAdapter(
this,//上下文
list,//数据库
R.layout.simplelo,//行布局xml名称
new String[]{"im_logo","text_simple"},//Map中的keys
new int[]{R.id.im_logo,R.id.text_simple}//行布局中的id,要对应上面的key的顺序
);
//4.关联listView
listView.setAdapter(adapter);
}
}