我正在尝试获取我的 RelativeLayout
的尺寸。
许多人告诉我使用以下代码:
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.myRelativeLayout);
int layoutWidth = relativeLayout.getWidth();
int layoutHeight = relativeLayout.getHeight();
我的问题是我在 R.id
中找到的所有 id 都是按钮、 TextView 等等。根本没有像布局 ID 这样的东西!
然后我试着写:
relativeLayout = (RelativeLayout) findViewById(R.layout.main_activity);
relativeLayout
运行时为空。所以也是不正确的。
我是否需要手动将布局 ID 添加到 R.id
中?我不这么认为。
但是为什么R.id
中的布局没有id呢?
最佳答案
这取决于你指的是什么布局。默认情况下,当您创建 Activity 或 XML 布局时,它将存储为 R.layout.xxx 。但是假设,在一个布局中,您有另一个布局(在本例中为嵌套布局),您必须手动“标识”您要引用的布局。
例如:
<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" >
<RelativeLayout
android:id="@+id/CallMe"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="139dp"
android:layout_marginTop="130dp" >
</RelativeLayout>
<RelativeLayout
android:layout_width="@+layout/test"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/CallMe"
android:layout_below="@+id/CallMe"
android:layout_marginTop="64dp" >
</RelativeLayout>
</RelativeLayout>
然后您可以通过 R.id.CallMe 引用第一个相关布局,通过 R.layout.test 引用第二个相关布局
您可以任意命名,不必是布局或 ID。 希望有帮助
关于android - 获取 RelativeLayout 的尺寸时 R.id 中没有 RelativeLayout id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17646188/