android - 获取 RelativeLayout 的尺寸时 R.id 中没有 RelativeLayout id

标签 android android-layout android-resources

我正在尝试获取我的 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/

相关文章:

java - 使用同一资源文件更改所有布局的 TextView 值

java - 是否可以打包通用类?

android - 是否有适用于 Android 的 Erlang 实现?

android - 如何处理 ListView 中的快速连续点击

android - ListFragment onListItemClick - 如何知道点击了哪个组件

java - 如何使卡片 View 的移动更加流畅?

android - 字符串格式转换为 ?通过数据绑定(bind)

java - Android OkHttp 库 : GET Request - Exception EOFException:\n not found: size=0 content=

java - DatePickerDialog 将选项限制为最长一周

Android 在 styles.xml 中为 TextView 设置背景色