Android 关于view的getLayoutParams().width,getWidth(),getMeasuredWidth();

习惯了使用xml的布局方式,当动态布局的时候就有许多疑点,记录一下,帮助我这老头一样的记忆力.


网上也有许多解析这getLayoutParams().width,getWidth(),getMeasuredWidth();三种方式的获取区别,参考并理解了下:


getLayoutParams().width:

这里顺便提下,LayoutParams,每个view都需要一个LayoutParams,告诉父容器的一些规则和方式,这时候该view的LayoutParams要与父容器的LayoutParam相相对应,比如该view的父容器使用的LinearLayout.LayoutParam,该view的布局类型也要对应着LinearLayout.LayoutParam,不然的话回报类型转换错误.好了LayoutParam就提到这里.

getLayoutParams().width获取的宽度是条件是你地xml中定义该view的时候,android:widt="150dp",就是固定值,注意:返回的值都是px单位.

如果你设置了"match_parent","wrap_content",返回的值是-1,其实是定义的常量:


public static final int FILL_PARENT = -1;

public static final int MATCH_PARENT = -1;

public static final int WRAP_CONTENT = -2;

getLayoutParams().width返回的是该view向父view请求的最大宽度,不是view实际绘画的宽度.怎么说呢,其实应该是接近实际宽度.

getWidth()

getWidth()大多人使用的时候返回都是0,因为在oncreat()中view还没被绘制的,在制onWindowFocusChanged()开始绘制的,getWidth()获取的就是该view的实际宽度.所以要想获取该高度在oncreat():


 ViewTreeObserver vto2 = firstAd.getViewTreeObserver();
        vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                firstAd.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                RelativeLayout.LayoutParams lp= (RelativeLayout.LayoutParams) 	firstAd.getLayoutParams();
                
            }
        });

getMeasuredWidth()

在onMeasure()执行完后才会有值 ,该方法就是getLayoutParams().width所说的父容器寄给的最大宽度.
View的大小由width和height决定。一个View实际上同时有两种width和height值 
• 第一种是measure width和measure height。他们定义了view想要在父View中占用多少width和height(详情见Layout)。measured height和width可以通过getMeasuredWidth() 和 getMeasuredHeight()获得。 
• 
• 第二种是width和height,有时候也叫做drawing width和drawing height。这些值定义了view在屏幕上绘制和Layout完成后的实际大小。这些值有可能跟measure width和height不同。width和height可以通过getWidth()和getHeight()获得。 
这两个方法所获取的width和height可能跟实际draw后的不一样。 


发布了20 篇原创文章 · 获赞 11 · 访问量 2万+
展开阅读全文

layoutparams设置宽度和高度填充父容器无效啊

02-23

在initData()对list集合添加imageview的时候发现我设置的imageView的宽和高无效 谢谢了 帮帮小白的我 布局文件 ``` <FrameLayout 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" > <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent" > </android.support.v4.view.ViewPager> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal|bottom" android:orientation="horizontal" android:padding="20dp" > <ImageView android:id="@+id/img_choose1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_choose" /> <ImageView android:id="@+id/img_choose2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_unchoose" /> <ImageView android:id="@+id/img_choose3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_unchoose" /> <ImageView android:id="@+id/img_choose4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_unchoose" /> <ImageView android:id="@+id/img_choose5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_unchoose" /> <ImageView android:id="@+id/img_choose6" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_unchoose" /> <ImageView android:id="@+id/img_choose7" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_unchoose" /> <ImageView android:id="@+id/img_choose8" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_unchoose" /> <ImageView android:id="@+id/img_choose9" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="5dp" android:src="@drawable/page_unchoose" /> </LinearLayout> </FrameLayout> ``` MainActivity ``` package com.example.viewpager; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.app.Activity; import android.support.v4.view.ViewPager; import android.view.Menu; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; public class MainActivity extends Activity { private List<View> list_image = new ArrayList<View>(); private ViewPager pager; private int img[] = { R.drawable.beauty1, R.drawable.beauty2, R.drawable.beauty3, R.drawable.beauty4, R.drawable.beauty5, R.drawable.beauty6, R.drawable.beauty7, R.drawable.beauty8, R.drawable.beauty9 }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); pager = (ViewPager) findViewById(R.id.pager); initData(); MyViewPagerAdapter adapter = new MyViewPagerAdapter(list_image); pager.setAdapter(adapter); } private void initData() { // TODO Auto-generated method stub for (int i : img) { ImageView imageView = new ImageView(this); //这里无效啊 怎么办。。 //想设置图片填充容器的。 LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); imageView.setImageResource(i); imageView.setLayoutParams(params); list_image.add(imageView); } } } ``` MyViewPagerAdapter ``` package com.example.viewpager; import java.util.ArrayList; import java.util.List; import android.support.v4.view.PagerAdapter; import android.view.View; import android.view.ViewGroup; public class MyViewPagerAdapter extends PagerAdapter{ private List<View> list_image = new ArrayList<View>(); public MyViewPagerAdapter(List<View> list_image){ this.list_image=list_image; } @Override public int getCount() { // TODO Auto-generated method stub return list_image.size(); } @Override public boolean isViewFromObject(View arg0, Object arg1) { // TODO Auto-generated method stub return arg0==arg1; } @Override public Object instantiateItem(ViewGroup container, int position) { // TODO Auto-generated method stub container.addView(list_image.get(position)); return list_image.get(position); } @Override public void destroyItem(ViewGroup container, int position, Object object) { // TODO Auto-generated method stub container.removeView(list_image.get(position)); } } ``` ![图片说明](https://img-ask.csdn.net/upload/201602/23/1456192784_647590.png) ![图片说明](https://img-ask.csdn.net/upload/201602/23/1456192798_220271.png) 问答

关于getMeasuredWidth()和getWidth()方法

10-06

package com.example.customview01.view; import java.util.HashSet; import java.util.Random; import java.util.Set; import android.R.integer; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.util.AttributeSet; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import com.example.customview01.R; public class CustomTitleView extends View { private String mTitleText; private int mTitleTextColor; private int mTitleTextSize; private Rect mBound; private Paint mPaint; private View customvView; public CustomTitleView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomTitleView(Context context) { this(context, null); } public CustomTitleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); /*LayoutInflater inflater = LayoutInflater.from(context); customvView = inflater.inflate(R.layout.activity_main, null);*/ TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.CustomTitleView, defStyle, 0); int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.CustomTitleView_titleText: mTitleText = a.getString(attr); break; case R.styleable.CustomTitleView_titleTextColor: mTitleTextColor = a.getColor(attr, Color.BLACK); break; case R.styleable.CustomTitleView_titleTextSize: mTitleTextSize = a.getDimensionPixelSize(attr, (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 16, getResources().getDisplayMetrics())); break; } } a.recycle(); mPaint = new Paint(); mPaint.setTextSize(mTitleTextSize); // mPaint.setColor(mTitleTextColor); mBound = new Rect(); mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound); this.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mTitleText = randomText(); postInvalidate(); } }); System.out.println("45678duiehjwfgiywehbWI"); } private String randomText() { Random random = new Random(); Set<Integer> set = new HashSet<Integer>(); while (set.size() < 4) { int randomInt = random.nextInt(10); set.add(randomInt); } StringBuffer sb = new StringBuffer(); for (Integer i : set) { sb.append("" + i); } return sb.toString(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); System.out.println("widthMeasureSpec= "+widthMeasureSpec+" heightMeasureSpec= "+heightMeasureSpec); int width = 0; int height = 0; int specMode = MeasureSpec.getMode(widthMeasureSpec); int specSize = MeasureSpec.getSize(widthMeasureSpec); System.out.println(specMode+" --- "+specSize); switch (specMode) { case MeasureSpec.EXACTLY: width = getPaddingLeft() + getPaddingRight() + specSize; break; case MeasureSpec.AT_MOST: int a=getPaddingLeft(); int b=getPaddingRight(); int c=mBound.width(); width = a+b+c; break; } specMode = MeasureSpec.getMode(heightMeasureSpec); specSize = MeasureSpec.getSize(heightMeasureSpec); switch (specMode) { case MeasureSpec.EXACTLY: height = getPaddingTop() + getPaddingBottom() + specSize; break; case MeasureSpec.AT_MOST: int a=getPaddingTop(); int b=getPaddingBottom(); int c=mBound.height(); height = a+b+c; break; } int i=0; setMeasuredDimension(width, height); } @Override protected void onDraw(Canvas canvas) { mPaint.setColor(Color.YELLOW); System.out.println(getMeasuredHeight()+"************************"+getMeasuredWidth()); System.out.println(getHeight()+" /////////////////////////// "+getWidth()); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint); mPaint.setColor(mTitleTextColor); canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint); } } 这是一个自定义View的代码,很简单,中间利用onMeasure()对View大小进行重绘,我的问题是,在onDraw()方法里面getMeasuredWidth()和getWidth()输出的值不一样,请问这两个方法有什么区别? 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览