zoukankan      html  css  js  c++  java
  • 安卓-06-使用XML和Java设置UI--实例--03--QQ相册

    XML不灵活

    Java太复杂

    布局和简单组件代码放在XML中

    复杂的组件放在Java代码中


     修改初始化的activity_main.xml为下面的xml文件

     1 <?xml version="1.0" encoding="utf-8"?>
     2 <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
     3     xmlns:app="http://schemas.android.com/apk/res-auto"
     4     xmlns:tools="http://schemas.android.com/tools"
     5     android:id="@+id/layout"
     6     android:orientation="horizontal"
     7     android:rowCount="3"
     8     android:columnCount="4"
     9     android:layout_width="match_parent"
    10     android:layout_height="match_parent"
    11     tools:context=".MainActivity">
    12 
    13 </GridLayout>

    设置 MainActivity.java 文件

    package com.example.java_and_xml_ui;
    
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.ViewGroup;
    import android.widget.GridLayout;
    import android.widget.ImageView;
    
    public class MainActivity extends AppCompatActivity {
        private ImageView[] img = new ImageView[12];
        private int[] imgPath = new int[]{
                R.mipmap.img01, R.mipmap.img02, R.mipmap.img03, R.mipmap.img04,
                R.mipmap.img05, R.mipmap.img06, R.mipmap.img07, R.mipmap.img08,
                R.mipmap.img09, R.mipmap.img10, R.mipmap.img11, R.mipmap.img12,
        };
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            setContentView(R.layout.activity_main);
            GridLayout layout = findViewById(R.id.layout);
            for(int i=0; i<imgPath.length; i++) {
                img[i] = new ImageView(MainActivity.this);
                img[i].setImageResource(imgPath[i]);
                img[i].setPadding(2, 2, 2, 2);
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(300, 120);  // 设置图片的宽度和高度
                img[i].setLayoutParams(params);
                layout.addView(img[i]);
    
            }
        }
    }
    

      


    神坑, 添加图片到数组的时候, 一直出错, 最终发现是因为我的图片的资源的名字是01.jpg, 02.jpg......

    android studio要求图片的名称必须是字母开头的.......

    我把资源的名称前加上img, 就可以通过了.

  • 相关阅读:
    【Android】3.13 路径规划功能
    【Android】3.12 兴趣点( POI)搜索功能
    【Android】3.11 地理编码功能
    【Android】3.10 热力图功能
    【Android】3.9 覆盖物功能
    Java并发工具类之CountDownLatch
    GitHub项目加入Travis-CI的自动集成
    一种基于zookeeper的分布式队列的设计与实现
    常用的限流算法
    zookeeper客户端命令详解
  • 原文地址:https://www.cnblogs.com/huangZ-H/p/10636278.html
Copyright © 2011-2022 走看看