您的位置:首页 > 移动开发 > Android开发

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>


结果

看图很清楚

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: