Android studio 九宫格显示 gridview 适配器实现九宫格

Android studio 九宫格显示 gridview 适配器实现九宫格
显示效果
在这里插入图片描述
Index.xml

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

    <GridView
        android:id="@+id/gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:horizontalSpacing="10dp"
        android:numColumns="3"
        android:paddingBottom="10dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:verticalSpacing="10dp"/>

</RelativeLayout>

Item.xml

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

    <ImageView
            android:id="@+id/imageView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal" />

    <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="New Text" />
</LinearLayout>

IndexActivity.java

public class IndexActivity extends AppCompatActivity {
    GridView gridView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);//对应的要显示的页面
        gridView = findViewById(R.id.gridView);
        //生成动态数组,并且转入数据
        ArrayList<HashMap<String, Object>> listItem;
        listItem = new ArrayList<>();
        for (int i = 0; i < 9; i++) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("image", R.drawable.give);
            hashMap.put("text", "出库");
            listItem.add(
                    hashMap);
        }
        //生成适配器的Item <====> 动态数组的元素,两者一一对应
        SimpleAdapter adapter = new SimpleAdapter(
                this,
                listItem, // 数据来源
                R.layout.item, // item 的XML实现
                new String[]{"image", "text"}, // 动态数组与Item对应的子项
                new int[]{R.id.imageView, R.id.textView} // Item的XML文件里面的一个ImageView,一个TextView ID
        );
        gridView.setAdapter(adapter);
    }
}```

发布了5 篇原创文章 · 获赞 17 · 访问量 977

猜你喜欢

转载自blog.csdn.net/cui_xiaoyu/article/details/105434394