用RelativeLayout 实现简单的九宫格布局

 //RelativeLayout是item中内嵌的布局 
RelativeLayout mainLayout = (RelativeLayout) findViewById(R.id.activity_main);
	//获取屏幕宽度
        int screenWidth = getResources().getDisplayMetrics().widthPixels;
	//每行显示的imageview数量
        int lineCount = 2;
        //屏幕兩邊邊距10 圖片間距10
        int margin = 10;
        int size = (screenWidth - (lineCount - 1) * margin) / lineCount;

        for (int i=0;i<3;i++){
            ImageView iv = new ImageView(this);
            RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(size, size);;
            lp.leftMargin = i%lineCount*(size+margin);
            lp.topMargin = i/lineCount*(size+margin);

            iv.setImageBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher));

            iv.setScaleType(ImageView.ScaleType.FIT_XY);
            iv.setLayoutParams(lp);
            mainLayout.addView(iv);


        }
  

你可能感兴趣的:(Android基础知识)