【问题标题】:Get Width and Height of view with match_parent constant使用 match_parent 常量获取视图的宽度和高度
【发布时间】:2015-02-13 10:34:33
【问题描述】:

我在我的main_layout.xml 中声明了Linear Layout,它的layout_with 的值为match_parent,我试图以编程方式在像素中获取Linear Layout 的宽度,但我得到了0 的宽度. 这是我的main_layout.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.bairnlogixgame.MainActivity" > 

    <LinearLayout
        android:id="@+id/llTextvieConainter"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:background="@drawable/view_borders"
        android:orientation="vertical" 
        />

</RelativeLayout>

这是我的MainActivity 代码。

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mMainContainer = (LinearLayout) findViewById(R.id.llTextvieConainter);

        int mWidth = getBoxDimensions(mMainContainer)[0];
        Log.i(TypeRacingConstants.LOGCAT,
                "Width of box :" + mWidth); 

    }

    private int[] getBoxDimensions(LinearLayout linearLayout) {
        int boxDiamensions[] = { 0, 0 };
        linearLayout.measure(MeasureSpec.EXACTLY, MeasureSpec.EXACTLY);
        boxDiamensions[0] = linearLayout.getMeasuredWidth();
        boxDiamensions[1] = linearLayout.getMeasuredHeight();
        return boxDiamensions;
    }   
}

请帮帮我,我哪里出错了。

【问题讨论】:

    标签: android xml android-layout dimensions


    【解决方案1】:

    无需编写方法 getBoxDimensions() 来获取宽度。只需在 onCreate 中编写以下代码

            mMainContainer.post(new Runnable() {
            @Override
            public void run() {
    
                 int mWidth = mMainContainer.getWidth();
                 Log.d("tag", "Width of box :" + mWidth);
    
            }
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-12-08
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2010-11-18
      • 1970-01-01
      相关资源
      最近更新 更多