其他分享
首页 > 其他分享> > Android 简单适配器(SimpleAdapter)

Android 简单适配器(SimpleAdapter)

作者:互联网

1.介绍

2.简单适配器的实现方法

3.XML文件

(1)主页面布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listview1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>

</LinearLayout>

(2)子项布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="TextView" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:srcCompat="@mipmap/img01" />
</LinearLayout>

4.java后台

package com.lucky.test29simpleadapter;

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 {

    ListView listView;  //列表视图
    SimpleAdapter simpleAdapter; //简单适配器可以将图片和文件组合起来
    List<Map<String,Object>> list1;
    //Android studio工程将图片转变为的数字
    int[] images={R.mipmap.img01,R.mipmap.img02,R.mipmap.img03,R.mipmap.img04,R.mipmap.img05,R.mipmap.img06,R.mipmap.img07,R.mipmap.img08};
    String[] contentstr={"虎扑","头条","QQ","微信","百度","起点","美团","滴滴"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView=findViewById(R.id.listview1);
        list1=new ArrayList<>();  //实例化list1
        for (int i = 0; i <images.length ; i++) {
            Map<String,Object> map=new HashMap<>();  //实例化map
            map.put("001",images[i]);   //给map添加值,参数1为代号,参数2为数据值
            map.put("002",contentstr[i]);
            list1.add(map);
        }
        //实例化simpleAdapter,并设置参数,参数2为数据,参数3为子项的布局文件,参数4为数据的代号,参数5为组件的id
        simpleAdapter=new SimpleAdapter(MainActivity.this,list1,R.layout.itemsimple,new String[]{"001","002"},new int[]{R.id.imageView,R.id.textView});
        listView.setAdapter(simpleAdapter); //设置适配器


    }
}

 

标签:map,java,适配器,list1,mipmap,new,import,Android,SimpleAdapter
来源: https://www.cnblogs.com/luckyplj/p/10512674.html