android 获取控件的高度或者宽度。

Android 获取控件高度宽度三种方法,防止0的出现 我们都知道在onCreate()里面获取控件的高度是0,这是为什么呢?我们来看一下示例:  首先我们自己写一个控件,这个控件非常简单: ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 阅读详情
开发的时候可能经常需要得到某个空间的高度或者宽度,比如一个textview,当你setText之后,就算你设置的再多的文字,调用getHeight方法他的高度也是为0(宽度同理)。这是因为view的绘制没有完成,所以控件的高度也是0,那么就需要我们自己进行手动绘制。直接上代码,简单粗暴,亲测可用,可以直接作为模板方法。网上也有类似的做法,但是这个比他们更加人性化。用过的都说好。
/**
     * 获取控件的高度或者宽度  isHeight=true则为测量该控件的高度,isHeight=false则为测量该控件的宽度
     * @param view
     * @param isHeight
     * @return
     */
    public static int getViewHeight(View view, boolean isHeight){
        int result;
        if(view==null)return 0;
        if(isHeight){
            int h = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
            view.measure(h,0);
            result =view.getMeasuredHeight();
        }else{
            int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
            view.measure(0,w);
            result =view.getMeasuredWidth();
        }
        return result;
    }




        
Android获得控件和状态栏高度 立即下载

相关推荐

android代码中获取控件高,宽度并修改

1、在代码中获取控件的高度,宽度 2、修改控件的高度,宽度,调整显示效果

怎样获取到Android控件的高度

onCreate里面调用getWidth、getMeasuredWidth获得长宽值的,始终为0。在onCreate中。我们的控件事实上还并没有画好,换句话说,等onCreate方法运行完了,我们定义的控件才会被度量(measure),所以我们在onCreate方法里面通过view.getHeight()获取控件的高度或者宽度肯定是0。 方法一、 int w = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int

JHC的博客 3万+

Android编程获取控件宽和高的方法总结分析

主要介绍了Android编程获取控件宽和高的方法,结合实例形式对比总结并分析了Android控件属性的相关操作技巧,需要的朋友可以参考下

Android中测量控件的宽和高

前言:在Android开发中,有时候我们需要测量控件的宽和高,而直接调用getHeight(),getWidth(),getMeasureHeight(),getMeasureWidth()方法, 得到的值都是0,这其实就涉及到view的绘制流程了.View绘制流程:(简单分析) measure(强制系统测量控件的宽和高)—>layout(确定控件在父布局中的位置)—>draw(绘制view

listeners_Gao的专栏 5760

别再为STM32F407的USB高速通信发愁了!手把手教你用USB3320(ULPI接口)搞定硬件设计

本文详细介绍了STM32F407通过USB3320(ULPI接口)实现高速USB通信的硬件设计实战。从USB3320的选型优势到原理图设计避坑,再到PCB布局和固件配置,提供了一套完整的解决方案。特别针对USB PHY芯片的常见问题,如供电处理、信号完整性和初始化代码,给出了专业建议和调试技巧,帮助工程师高效完成高速USB通信设计。

weixin_42527401的博客 389

手把手教你用运放搭建方波三角波发生器(附Multisim仿真文件)

本文详细解析了使用运算放大器搭建方波和三角波发生器的核心原理与设计步骤。通过剖析迟滞比较器与积分器的联动机制,指导读者进行电路设计、元件选型,并借助Multisim仿真进行参数调优与波形优化。文章提供了从理论分析、虚拟仿真到实物焊接调试的完整实践指南,并附有仿真文件,帮助硬件爱好者与初学者深入掌握这一经典模拟电路设计。

weixin_29165725的博客 642

2024年安卓最新安卓学习笔记---开篇(目录结构),2024年最新软件开发面试题及答案

找到一套好的视频资料,紧跟大牛梳理好的知识框架进行学习。多练。(视频优势是互动感强,容易集中注意力)你不需要是天才,也不需要具备强悍的天赋,只要做到这两点,短期内成功的概率是非常高的。对于很多初中级Android工程师而言,想要提升技能,往往是自己摸索成长,不成体系的学习效果低效漫长且无助。

2301_82244182的博客 654

SSE消息推送避坑指南:从Chrome兼容性到Spring超时配置

本文深入探讨了在Java Spring Boot项目中实现SSE消息推送时,从浏览器兼容性到后端配置的完整避坑指南。针对Chrome并发连接限制、Safari自动断开、Nginx代理缓冲以及Spring SseEmitter内存泄漏与超时管理等生产环境常见问题,提供了具体的解决方案和最佳实践配置,帮助开发者构建稳定可靠的实时推送系统。

work3的博客 452

Android 获取控件的宽度和高度的几种方式

【代码】Android 获取控件的宽度和高度的几种方式。

2501_90425213的博客 426

Matlab在线性代数中的应用(一):向量组的线性相关性

求列向量组A的一个最大线性无关组可用命令rref(A)将A化成行最简形,其中单位向量对应的列向量即为最大线性无关组所含向量,其它列向量的坐标即为其对应向量用最大线性无关组线性表示的系数。 01 — 例1 求下列矩阵列向量组的一个最大无关组。 解:编写脚本文件如下: >>format rat a=[1,-2,-1,0,2;-2,4,2,6,-6;2,-1,0,2,3;3,3,3,3,4]; b=rref(a) 求得: b...

wenyusuran的专栏 3237

OCS2 入门教程(一)

OCS2 是专为切换系统优化控制(ptimalontrol forwitchedystems,OCS2)定制的 C++ 工具箱。该工具箱提供以下算法的高效实现:SLQ:连续时间域约束 DDPiLQR:离散时域约束 DDPSQP:基于 HPIPM 的多重打靶算法IPM: 基于非线性内点法的多重搜索算法SLP:基于 PIPG 的顺序线性规划算法OCS2 通过增强拉格朗日法(Augmented Lagrangian)或松弛障碍法(relaxed barrier methods)处理一般路径约束。

机器人控制与仿真应用 7837

android-如何关闭AlertDialog(1)

**设置dialog的出现*/watertype.setText(“地下水”);watertype.setText(“地表水”);/***/

2401_84519718的博客 1254

从 0 到 1 打造一个“超级 IP 智能体”

这篇文章介绍了一个"超级IP智能体"的技术架构和实现方案。该项目构建了一个多模态内容生成流水线,主要流程包括:1)视频下载和音频提取;2)语音识别转换为文字稿;3)使用大语言模型对文案进行仿写和润色;4)语音合成;5)数字人口型同步;6)视频后期处理。文章详细介绍了如何使用Python和Hugging Face开源模型搭建环境,并重点展示了视频下载、语音识别(采用Whisper模型)以及文案仿写(使用Qwen1.5-7B-Chat模型)等核心模块的代码实现。所有处理均针对M3芯片Mac优

AI天才研究院 1150

Android 获取控件的高度或者宽度的方法

方法一:DisplayMetrics dm = getResources().getDisplayMetrics();int width = dm.widthPixels;int height = dm.heightPixels;方法二:/** * 获取控件的高度或者宽度 isHeight=true则为测量该控件的高度,isHeight=false则为测量该控件的宽度 * @param vi...

kinderkindme的博客 2686

2026年全国青少年信息素养大赛复赛真题(算法应用主题赛C++初中组:带解析)(7月4日试卷一)【文末附答案和解析】

2026年全国青少年信息素养大赛复赛真题(算法应用主题赛C++初中组:带解析)(7月4日试卷一)【文末附答案和解析】

王老师青少年编程 1740

使用 MATLAB/Simulink + Simscape Electrical + Simulink Design Optimization,构建一个基于SiC/GaN的Z源逆变器在储能系统中的软启

《手把手教你学Simulink:Z源逆变器在储能系统中的应用》摘要 本文详细介绍了使用MATLAB/Simulink构建Z源逆变器储能系统仿真模型的全过程。Z源逆变器凭借其独特的阻抗网络结构,解决了传统逆变器在直通保护和升压能力方面的痛点。文章通过6个关键步骤:主电路搭建、调制策略设计、软启动实现、仿真分析、效率对比和工程问题解决方案,完整展示了Z源逆变器从理论到仿真的实现路径。重点讲解了直通零矢量SPWM调制策略和渐进式升压比控制方法,验证了系统93.3%的效率和优异的抗扰性能。该模型为光伏储能、电动汽车

MHD0815的博客 122

android 动态设置获取控件大小,并设置宽度等于高度,或者高度等于宽度。

public static void setViewWidthByHeight(View view) { final View mv = view; final ViewTreeObserver vto = mv.getViewTreeObserver(); final ViewTreeObserver.OnPreDrawListener preDrawListener = new V

xizhao88的专栏 2817

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

android如何计算控件高度和宽度,android 动态设置获取控件大小,并设置宽度等于高度,或者高度等于宽度。...

public static void setViewWidthByHeight(View view) {final View mv = view;final ViewTreeObserver vto = mv.getViewTreeObserver();final ViewTreeObserver.OnPreDrawListener preDrawListener = new ViewTreeOb...

weixin_39662432的博客 439

数学建模模型总结

这是本人在两年内准备参加数学建模竞赛搜集到的模型资料,已经经过了本人的筛选和整理,希望能够对准备参加数学建模竞赛的学弟学妹们提供一些帮助!

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

android绘制控件,Android控件绘制完成原来是这样的

实际开发中经常会碰到需要获取某个控件的宽度和高度的情况,但是在实际测试中我们在Activity的启动中期函数中废了老大劲了,我们发现是这样的OnCreate=>>>>>>>>>width==0,height==0 onStart=>>>>>>>>>width==0,height==0onRe...

weixin_29628611的博客 247

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Android获取屏幕宽度高度并动态设置控件宽度,比例等

1、Android获取屏幕宽度的几种方法: //1、通过WindowManager获取 DisplayMetrics dm = new DisplayMetrics(); int heigth = dm.heightPixels;// 表示屏幕的像素高度,单位是px(像素) int width = dm.widthPixels;/...

冷冷清清里风风火火是我 2788

android 获取屏幕的高度和宽度、获取控件在屏幕中的位置、获取屏幕中控件的高度和宽度...

(一)获取屏幕的高度和宽度 有两种方法: 方法1: WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE); int width = wm.getDefaultDisplay().getWidth(); int height = wm.getDefaultDi...

weixin_30321709的博客 1251

Android Studio 获取屏幕宽度跟高度

两个函数直接反馈当前手机的宽度跟高度 // 获得屏幕的宽度 public static int getScreenWidth(Context ctx) { // 从系统服务中获取窗口管理器 WindowManager wm = (WindowManager) ctx.getSystemService(Context.WINDOW_SERVICE)...

weixin_chen的专栏 2867

Android获得标题栏和状态栏高度,以及立即获取控件的高度

直接看代码注释吧   package com.test01; import android.app.Activity; import android.graphics.Rect; import android.os.Bundle; import android.view.ViewTreeObserver; import android.view.Window; import android.

9763

Android获取文本的宽度和高度

在文本数据绘制时获取文本的宽度和高度

a307326984的博客 5606

android 代码中获取控件宽度高度并修改

如何获取一个控件的长和高,相信很多朋友第一眼看见这个问题都会觉得很简单,直接在onCreate里面调用getWidth、getMeasuredWidth不就可以获得了吗,但是,事实上是并没有简单的,不信的话,你可以去试一下,在onCreate里面,你是无法获得长宽值的,始终为0。原因这是为什么呢,其实熟悉view绘制流程的朋友应该一眼就看出来了,在onCreate中,我们的控件其实还并没有画好,换...

pxcz110112的博客 1427
上一篇: android 查看本地数据库
下一篇: java.lang.IllegalStateException: The ImageView's ScaleType has been changed
DreamCarMustang
博客等级 码龄12年 10粉丝 20原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值