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, 就可以通过了.

  • 相关阅读:
    记一道乘法&加法线段树(模版题)
    2021CCPC网络赛(重赛)题解
    Codeforces Round #747 (Div. 2)题解
    F. Mattress Run 题解
    Codeforces Round #744 (Div. 3) G题题解
    AtCoder Beginner Contest 220部分题(G,H)题解
    Educational Codeforces Round 114 (Rated for Div. 2)题解
    Codeforces Global Round 16题解
    Educational Codeforces Round 113 (Rated for Div. 2)题解
    AtCoder Beginner Contest 182 F
  • 原文地址:https://www.cnblogs.com/huangZ-H/p/10636278.html
Copyright © 2011-2022 走看看