利用GridView实现九宫格

**主要布局





**item布局代码



**fragment部分的布局代码


**主文件中JAVA代码的实现

package com.example.mpyypm.zuoye;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

/**

  • Created by mpyypm on 2017/5/8.
    */

    public class MainActivity extends AppCompatActivity {
    private Fragment grid_viewFragment;
    private FragmentTransaction transction;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    FragmentManager manager = getFragmentManager() ;
    transction = manager.beginTransaction();
    if(grid_viewFragment ==null){
    grid_viewFragment = new Grid_ViewFragment();
    transction.add(R.id.show, grid_viewFragment);
    }
    transction.replace(R.id.show, grid_viewFragment);
    transction.commit();
    }
    }

**fragment部分的代码

package com.example.mpyypm.zuoye;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import java.util.ArrayList;
import java.util.List;

public class Grid_ViewFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_grid_view, container, false);

List datas = new ArrayList<>();
datas.add(new ClassInfo(R.drawable.cat_1));
datas.add(new ClassInfo(R.drawable.cat_2));
datas.add(new ClassInfo(R.drawable.cat_3));
datas.add(new ClassInfo(R.drawable.cat_4));
datas.add(new ClassInfo(R.drawable.cat_5));
datas.add(new ClassInfo(R.drawable.cat_6));
datas.add(new ClassInfo(R.drawable.cat_7));
datas.add(new ClassInfo(R.drawable.cat_8));
datas.add(new ClassInfo(R.drawable.cat_9));
final CustomGridViewAdapter adapter = new CustomGridViewAdapter(getActivity(), datas);

GridView gridview = (GridView) view.findViewById(R.id.GridView);
gridview.setAdapter(adapter);
return view;
}
}

posted @ 2017-05-08 17:41  mpy1611  阅读(326)  评论(1)    收藏  举报