任務要求:javascript
使用GridView和SimpleAdapter實現手機界面常見的的九宮格,圖片能夠任意選擇,注意圖片的大小要一致java
思路:android
佈局就不說了,代碼實現部分先準備數據源 聲明一個List集合,集合中的對象是map對象,map對象調用方法傳入數據完成數據源準備 而後建立simpleaapter綁定,最後爲圖片添加了一個監聽器,點擊圖片後會在九宮格圖片下方顯示這張圖片。ide
佈局:
main_activity佈局
TextView android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" style="@style/hello" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content"> <fragment android:id="@+id/fragment" android:name="com.example.administrator.ninephoto.GridFragment" android:layout_width="match_parent" android:layout_height="match_parent" tools:layout="@layout/fragment_grid"/> </LinearLayout>
fragment_gridui
<GridView android:id="@+id/grid_photo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:numColumns="3"/> <LinearLayout android:layout_gravity="center" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> <ImageView android:id="@+id/img1" android:layout_width="180dp" android:layout_height="180dp" /> </LinearLayout>
grid_itemcode
<ImageView android:id="@+id/img" android:layout_width="wrap_content" android:layout_height="wrap_content" />
java代碼:
GridFragment:對象
public class GridFragment extends Fragment { private GridView grid_photo; private SimpleAdapter simpleAdapter; private ArrayList< HashMap<String, Object>> photo; private ImageView img1; //將圖片資源打包到集合中 private int []icon = { R.drawable.a1,R.drawable.a2,R.drawable.a3,R.drawable.a4,R.drawable.a5, R.drawable.a6,R.drawable.a7,R.drawable.a8,R.drawable.a9}; public GridFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_grid, container, false); //加載相關控件 grid_photo = (GridView)view.findViewById(R.id.grid_photo); img1 = (ImageView)view.findViewById(R.id.img1); //建立適配器並綁定 simpleAdapter = new SimpleAdapter(getActivity(),getData(), R.layout.grid_item,new String[]{"cat"},new int[]{R.id.img}); grid_photo.setAdapter(simpleAdapter); //爲九宮格圖片添加監聽器 grid_photo.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { img1.setImageResource(icon[position]); } }); return view; } //相關數據源的獲取 public ArrayList<HashMap<String, Object>> getData() { photo = new ArrayList<HashMap<String, Object>>(); for (int i=0;i<icon.length;i++){ HashMap<String, Object> map = new HashMap<String, Object>(); map.put("cat", icon[i]); photo.add(map); } return (ArrayList<HashMap<String, Object>>) photo; } }
在相關數據源的獲取這裏本來的添加數據的方法是一個個put,後面找到個是代碼簡潔的方法是利用一個for循環這樣只用寫一個put方法就能夠獲取9個數據源blog
完成效果
圖片