首页 > 代码库 > GridView和SimpleAdapter九宫格作业

GridView和SimpleAdapter九宫格作业

安卓作业:

使用GridView和SimpleAdapter实现手机界面常见的九宫格,图片可以任意选择,注意图片大小

1,主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"
android:id="@+id/activity_qiu"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="cn.edu.niit.jiugongge.QiuActivity">

<GridView
android:id="@+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="auto_fit"/><!--定义每行显示的列数,auto_fit自定义-->
/>
</RelativeLayout>
2.建立一个新的activity_imageview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageView
android:id="@+id/img"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:paddingTop="10dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:layout_gravity="center"
android:scaleType="fitXY" />

</LinearLayout>
3.java文件代码
package cn.edu.niit.jiugongge;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class QiuActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qiu)

public class DzzyFragment extends Fragment {  

    private GridView gridView;  

    private int[] imgs = { };//图片资源  

    public View onCreateView(LayoutInflater inflater, ViewGroup container,  

            Bundle savedInstanceState) {  

        View view = inflater.inflate(R.layout.activity_dzzy, container, false);  

        setHasOptionsMenu(true);  

        gridView = (GridView) view.findViewById(R.id.gridView);  

     

        ArrayList<HashMap<String, Object>> imagelist = new ArrayList<HashMap<String, Object>>();  

        for (int i = 0; i < imgs.length; i++) {  

                HashMap<String, Object> map = new HashMap<String, Object>();  

                map.put("img", imgs[i]);  

                imagelist.add(map);  

       }  

 

       SimpleAdapter sa = new SimpleAdapter(getActivity()  

            .getApplicationContext(), imagelist,  

            R.layout.activity_dzzy_item2, new String[] { "img" },

            new int[] { R.id.img });  

      gridView.setAdapter(sa);

      return view;  

    }  

}  

GridView和SimpleAdapter九宫格作业