jjzjj

android - 如何在屏幕中央布局 'grid' 图片

coder 2023-11-28 原文

我有一组 12 张图像要在布局中显示。这个数字是半任意选择的,但归结为纵向模式下水平方向为 3 个,垂直方向为 4 个,横向方向则相反。

第一个实现是使用 gridview。问题是不能强制高度适合屏幕。 对于解决方法,我当然可以(尝试)缩放图像,但几乎不可能计算 GridView 可用的空间:当然,总屏幕大小是已知的,但你必须“猜测”通知栏的大小,但事实并非如此。这似乎不是一个优雅的解决方案。测量的尺寸确实不可信:我没有在方向改变时完全重新启动(为了速度),但屏幕构建完整空间的方式在现场不可用。 最后的结论是我不想计算图像的大小然后相应地缩放它们:我认为最好说明 View 应该如何适合屏幕,对吧?

所以接下来的尝试就是使用 TableLayout。使用“ShrinkColumns =”*”图像拟合得很好,所以图像的大小现在是我们想要的。但是我们可能在高度上拥有的“额外”空间现在在表格行之间平均分配。这是可以预料的,但是很丑。

目前的代码似乎无关紧要,因为它不起作用,但最终看起来像这样: 我已经删除了所有的填充和其他看起来不相关的东西。 (肖像:)

<TableLayout
       android:shrinkColumns="*">
    <TableRow>
        <ImageView/>
        <ImageView/>
        <ImageView/>
    </TableRow>
    … (repeat 3 tablerows)
</TableLayout>

为了“缩放”过大的图像,TableLayout 具有“shrinkcolumns=”*””属性。

如何让三个 ImageView 在 TableRow 的中心对齐,而不是在宽度上均匀分布?垂直列也是如此,我们如何才能将所有内容放在一起而不是散布在屏幕的高度上? 基本上,“多余”空间应该作为填充/边距放在两侧,现在它位于图像之间。

例子: 左边的屏幕截图显示左/右距离太大,右边的顶部/底部太多

最佳答案

我认为使用自定义 View 应该不会太难,这应该是一个有趣的练习。这是我的第一个自定义 View ;欢迎反馈!

限制

  • AspectGrid 完全忽略了其子项想要的大小。出于您的目的,这似乎没问题。如果需要更高级的东西,onMeasure 需要做很多额外的工作。
  • AspectGrid 的父级建议的大小被使用时没有再考虑。这与上一期有关。

截图

Landscape screenshot http://tinypic.com/images/404.gif

工作原理

一个主要参数是列数。行数是自动计算的,因为我们知道 child 的数量。另一个主要参数是我们要为 child 使用的纵横比(对于正方形设置为 1)。

onLayout 中,我们收到网格的最终大小,因此我们可以计算子项的最大宽度和高度。

然后我们根据宽高比检查它。如果 child 太高,我们就让他们变矮(如肖像示例)。如果它们太宽,我们会让它们变窄(如风景示例)。

仅此而已;剩下的只是管道。

代码

com/photogrid/AspectGrid.java:实际的ViewGroup

package com.photogrid;

import android.content.Context;

public class AspectGrid extends ViewGroup {

    private int mNumColumns = 1;
    private int mHorizontalSpacing = 0;
    private int mVerticalSpacing = 0;
    private float mChildAspectRatio = 1.0f;

    public AspectGrid(Context context) {
        super(context);
    }

    public AspectGrid(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public AspectGrid(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        try {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AspectGrid);

            setNumColumns(a.getInt(R.styleable.AspectGrid_numColumns, mNumColumns));
            setHorizontalSpacing(a.getDimensionPixelSize(R.styleable.AspectGrid_horizontalSpacing, mHorizontalSpacing));
            setVerticalSpacing(a.getDimensionPixelSize(R.styleable.AspectGrid_verticalSpacing, mVerticalSpacing));
            setChildAspectRatio(a.getFloat(R.styleable.AspectGrid_childAspectRatio, mChildAspectRatio));

            a.recycle();
        } catch (RuntimeException ex) {
            throw ex;
        }
    }

    public int getNumColumns() {
        return mNumColumns;
    }

    public void setNumColumns(int numColumns) {
        if (numColumns < 1)
            throw new IllegalArgumentException("numColumns must be at least 1");
        if (numColumns != mNumColumns) {
            mNumColumns = numColumns;
            requestLayout();
        }
    }

    public int getHorizontalSpacing() {
        return mHorizontalSpacing;
    }

    public void setHorizontalSpacing(int horizontalSpacing) {
        mHorizontalSpacing = horizontalSpacing;
    }

    public int getVerticalSpacing() {
        return mVerticalSpacing;
    }

    public void setVerticalSpacing(int verticalSpacing) {
        mVerticalSpacing = verticalSpacing;
    }

    public float getChildAspectRatio() {
        return mChildAspectRatio;
    }

    public void setChildAspectRatio(float childAspectRatio) {
        if (childAspectRatio <= 0)
            throw new IllegalArgumentException("childAspectRatio must be positive");
        if (childAspectRatio != mChildAspectRatio) {
            mChildAspectRatio = childAspectRatio;
            requestLayout();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int measuredWidth = widthSize;
        int measuredHeight = heightSize;
        int width = Math.max(measuredWidth, getSuggestedMinimumWidth());
        int height = Math.max(measuredHeight, getSuggestedMinimumHeight());
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        if (childCount <= 0)
            return;

        int innerWidth = r - l - getPaddingLeft() - getPaddingRight();
        int innerHeight = b - t - getPaddingBottom() - getPaddingTop();
        int numRows = (childCount + mNumColumns - 1) / mNumColumns;

        int leftEdge = getPaddingLeft();
        int topEdge = getPaddingTop();
        int horizontalStride = (innerWidth + mHorizontalSpacing) / mNumColumns;
        int verticalStride = (innerHeight + mVerticalSpacing) / numRows;
        int childWidth = horizontalStride - mHorizontalSpacing;
        int childHeight = verticalStride - mVerticalSpacing;

        if (childHeight * mChildAspectRatio > childWidth) {
            childHeight = (int)(childWidth / mChildAspectRatio);
            verticalStride = childHeight + mVerticalSpacing;
            topEdge = (innerHeight + mVerticalSpacing - numRows * verticalStride) / 2; 
        } else {
            childWidth = (int)(childHeight * mChildAspectRatio);
            horizontalStride = childHeight + mHorizontalSpacing;
            leftEdge = (innerWidth + mHorizontalSpacing - mNumColumns * horizontalStride) / 2;
        }

        for (int i = 0; i < childCount; ++i) {
            View child = getChildAt(i);
            int row = i / mNumColumns;
            int column = i % mNumColumns;
            int left = leftEdge + column * horizontalStride;
            int top = topEdge + row * verticalStride;
            child.layout(
                left,
                top,
                left + childWidth,
                top + childHeight);
        }
    }

}

res/values/attrs.xml:在 XML 中使用的属性声明

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="AspectGrid">
        <attr name="numColumns" format="integer"/>
        <attr name="horizontalSpacing" format="dimension"/>
        <attr name="verticalSpacing" format="dimension"/>
        <attr name="childAspectRatio" format="float"/>
    </declare-styleable>
</resources>

res/layout/main.xml:上面截图中使用的例子

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res/com.photogrid"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <com.photogrid.AspectGrid
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:padding="5dp"
        app:numColumns="3"
        app:horizontalSpacing="5dp"
        app:verticalSpacing="5dp"
        app:childAspectRatio="1.0"
        >
        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:background="#ffcccc" 
            android:text="Item 1"
            />
        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:background="#ccffcc" 
            android:text="Item 2"
            />
        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:background="#ccccff" 
            android:text="Item 3"
            />
        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:background="#ffffcc" 
            android:text="Item 4"
            />
        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:background="#ffccff" 
            android:text="Item 5"
            />
        <TextView  
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content"
            android:background="#ccffff" 
            android:text="Item 6"
            />
    </com.photogrid.AspectGrid>
</LinearLayout>

关于android - 如何在屏幕中央布局 'grid' 图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4592065/

有关android - 如何在屏幕中央布局 'grid' 图片的更多相关文章

  1. ruby - 如何在 Ruby 中顺序创建 PI - 2

    出于纯粹的兴趣,我很好奇如何按顺序创建PI,而不是在过程结果之后生成数字,而是让数字在过程本身生成时显示。如果是这种情况,那么数字可以自行产生,我可以对以前看到的数字实现垃圾收集,从而创建一个无限系列。结果只是在Pi系列之后每秒生成一个数字。这是我通过互联网筛选的结果:这是流行的计算机友好算法,类机器算法:defarccot(x,unity)xpow=unity/xn=1sign=1sum=0loopdoterm=xpow/nbreakifterm==0sum+=sign*(xpow/n)xpow/=x*xn+=2sign=-signendsumenddefcalc_pi(digits

  2. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  3. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  4. ruby - 如何在 buildr 项目中使用 Ruby 代码? - 2

    如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby​​

  5. ruby - 什么是填充的 Base64 编码字符串以及如何在 ruby​​ 中生成它们? - 2

    我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  8. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  9. ruby - 如何在续集中重新加载表模式? - 2

    鉴于我有以下迁移:Sequel.migrationdoupdoalter_table:usersdoadd_column:is_admin,:default=>falseend#SequelrunsaDESCRIBEtablestatement,whenthemodelisloaded.#Atthispoint,itdoesnotknowthatusershaveais_adminflag.#Soitfails.@user=User.find(:email=>"admin@fancy-startup.example")@user.is_admin=true@user.save!ende

  10. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

随机推荐