码迷,mamicode.com
首页 > 其他好文 > 详细

代码写个九宫格布局显示图片

时间:2015-04-01 17:53:17      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:android   布局   代码   

不在xml中设置布局,在代码中直接写个布局,显示下载的图片,如下图所示,图片有点丑
技术分享

XML中添加个linearLayout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="九宫格显示图片" />
     <LinearLayout
         android:id="@+id/report_photo_layout"
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_margin="10dip"
         android:orientation="vertical" 
         android:layout_below="@+id/text"/>
</RelativeLayout>

另外加个布局,显示图片view_files_image.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center" >
    <ImageView
        android:id="@+id/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true"
        android:scaleType="centerCrop" />
</RelativeLayout>

其他就是代码了:

public class MainActivity extends Activity {
    private LinearLayout layoutPhotos;//
    private LinkedHashMap<String, String> choosePhotos = new LinkedHashMap<String, String>();//已选择的照片
    private DisplayMetrics dm = new DisplayMetrics();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        layoutPhotos = (LinearLayout) findViewById(R.id.report_photo_layout);
        //choosePhotos哦让其中添加图片地址
        choosePhotos.put("1", "http://lllqmw.qiniudn.com/1.png");
        choosePhotos.put("2", "http://lllqmw.qiniudn.com/2.png");
        choosePhotos.put("3", "http://lllqmw.qiniudn.com/3.png");
        choosePhotos.put("4", "http://lllqmw.qiniudn.com/4.png");
        choosePhotos.put("5", "http://lllqmw.qiniudn.com/5.png");
        choosePhotos.put("6", "http://lllqmw.qiniudn.com/6.png");
        choosePhotos.put("7", "http://lllqmw.qiniudn.com/7.png");
        choosePhotos.put("8", "http://lllqmw.qiniudn.com/8.png");
        //显示图片
        layoutShowFiles();
    }
    /**
     * 九宫格的方式显示下载的图片
     */
    private void layoutShowFiles() {

        layoutPhotos.removeAllViews();

        // 每行四张视图,计算一下第个的宽高
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int margins = (int) dm.density * 2;
        int photoWidth = (int) (((dm.widthPixels - dm.density * 30) / 3) - margins * 2.5);
        Log.i("info", "每个view的尺寸为:" + photoWidth + ",间距为:" + margins);

        LinearLayout subLayout = new LinearLayout(this);
        subLayout.setOrientation(LinearLayout.HORIZONTAL);
        LayoutParams subParams = new LayoutParams(photoWidth, photoWidth);
        subParams.setMargins(margins, margins, margins, margins);

        int i = 0;
        Iterator<Entry<String, String>> iter = choosePhotos.entrySet().iterator();
        while (iter.hasNext()) {
            subLayout.addView(createLayoutPhoto(i, iter.next().getValue(), subParams));

            if (i % 3 == 2) {
                layoutPhotos.addView(subLayout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                subLayout = new LinearLayout(this);
                subLayout.setOrientation(LinearLayout.HORIZONTAL);
            }

            i++;
        }

        // 计算一下sublayout还能放几个view,如果已经摆満了4个,刚新起一行
        if ((3 - choosePhotos.size() % 3) == 3) {
            subLayout = new LinearLayout(this);
            subLayout.setOrientation(LinearLayout.HORIZONTAL);
        }
        layoutPhotos.addView(subLayout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    }

    /**
     * 生成一个图片
     * @param id
     * @param path
     * @param params
     * @return
     */
    private View createLayoutPhoto(final int imagePosition, final String path, LayoutParams params) {
        View v = getLayoutInflater().inflate(R.layout.view_files_image, null);
        v.setLayoutParams(params);
        ImageLoader.getInstance().displayImage(path, (ImageView) v.findViewById(R.id.image),SoftApplication.imageOptions);
        return v;
    }

}

下载图片需要的application

public class SoftApplication extends Application {  
    public static DisplayImageOptions imageOptions ;

    @Override
    public void onCreate() {
        super.onCreate();
        initImageLoader(getApplicationContext());
        //设置图片属性:下载时的图片,下载失败的图片,是否圆角
        imageOptions = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true)
                .showImageOnLoading(R.drawable.default_loading)     // 加载开始默认的图片
                .showImageForEmptyUri(R.drawable.default_loading)   // url爲空會显示该图片,自己放在drawable里面的
                .showImageOnFail(R.drawable.default_loading)        // 加载图片出现问题,会显示该图片
                .imageScaleType(ImageScaleType.IN_SAMPLE_INT).bitmapConfig(Bitmap.Config.RGB_565).build();
    }
    public static void initImageLoader(Context context) {
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO)
                .writeDebugLogs() // Remove for release app
                .build();
        ImageLoader.getInstance().init(config);
    }   

}

有个地方容易忘记:AndroidManifest.xml 声明

  <application
        android:name="com.example.demo_imagedisplay.SoftApplication"

ok了,点击Demo_imageDisplay下载完整代码。


更多交流可加技术讨论群:71262831
扫一扫,一起坐看风云变幻。扫描下方二维码关注it达人(也可微信搜索:it达人)。
为您推送最新开发资源、分享it牛人职业发展经验:
技术分享

代码写个九宫格布局显示图片

标签:android   布局   代码   

原文地址:http://blog.csdn.net/metis100/article/details/44807637

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!