Android中正确获得View控件的宽和高——使用篇
2015-09-20 17:15
471 查看
我自己回顾自己写的文章,有时候感觉看起来颇为吃力,第一就是太长,第二太注重原理而轻使用,而为了方便同行的阅读,我决定对于自己研究的东西,先写一个使用篇,然后再写一个原理篇。使用篇尽量简单易学易用,而原理篇尽量详细的介绍源码实现过程。
布局文件:
背景
这是今天一个同学去面试被问到的问题。正确方法
要在onWindowFocusChanged()回调中获得组建的宽和高。通过getwidth(),和getMeasureWidth()都可以;最常见的错误时在onCreate()中调用上面的方法。那样你会获得的都是0;代码
public class MainActivity extends AppCompatActivity { private static final String TAG = MainActivity.class.getSimpleName(); ImageView imageView ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "oncreate") ; setContentView(R.layout.activity_main); imageView = (ImageView)findViewById(R.id.test_imageView) ; Log.d(TAG, "getHeight:" + imageView.getHeight() + ""); Log.d(TAG, "getWidth:"+imageView.getWidth() + "") ; Log.d(TAG, "getMeasuredHeight:"+imageView.getMeasuredHeight() + ""); Log.d(TAG, "getMeasuredHeight:"+imageView.getMeasuredWidth() + "") ; } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); Log.d(TAG,"onWindowFocusChanged") ; Log.d(TAG, "getHeight:" + imageView.getHeight() + ""); Log.d(TAG, "getWidth:"+imageView.getWidth() + "") ; Log.d(TAG, "getMeasuredHeight:" + imageView.getMeasuredHeight() + ""); Log.d(TAG, "getMeasuredHeight:"+imageView.getMeasuredWidth() + "") ; } }
布局文件:
<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=".MainActivity"> <ImageView android:id="@+id/test_imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@android:drawable/ic_input_add" /> </RelativeLayout>
结果
看图很清楚相关文章推荐
- 使用ToggleButton
- Android 动画——Frame Animation与Tween Animation
- java4Android(21)类集框架->Collection and Iterator(hasNext方法和next方法)
- Android JNI环境要SQLite加密模块简介
- Android 寻找xutils上传图片失败办法的路径
- Android 裁剪图片为圆形图片
- Android Layout 优化
- android AsyncTask介绍
- Android中四种通知--notification
- 浅析Android-ViewPagerIndicator
- android studio 中的编码问题
- Android Studio常用快捷键
- Android之viewstub用法详解及实现延迟加载
- Android 动画之三 Property Animation—— 属性(Property)动画 【Animator提供基类】
- Fragment 深究
- Android服务之Service(其一)
- Android应用开发Camera系列(一):SurfaceView实现相机预览demo--新手上路
- Android Studio JNI NDK编程(一)
- Android贴吧系统学习-----悬浮布局出现的bug--android.view.WindowManager$BadTokenException:
- Android(异步任务) AsyncTask