LoginSignup
28
25

More than 5 years have passed since last update.

Androidのlayoutのxmlで@id と @+id の違い

Last updated at Posted at 2015-05-20

結論

android:id では、@+id/
RelativeLayoutのポジション(ex: layout_below)指定では、 @id/

まえがき

基本id/で書いてるけど、レガシーコードで@+idで書かれてるのがあった。
android:id で@id/と書くとeclipseとかandroid stdioとかに怒られるけど
RelativeLayoutで@+id/で指定しても怒られない。
同じようなもんかと思って、ずっとスルーしていた・・・。
しかし、レイアウト変えてて@+idで指定してるxmlを編集してるときに思わぬエラーになって
困り果てて、ちゃんと調べようと思った。

「+」とはいったい何にプラスするのか

@+id/ と @id/ の違いは、+があるかないか。

本家参照じゃなくて、申し訳ないが。スタる(?)とあった
http://stackoverflow.com/questions/5025910/difference-between-id-and-id-in-android

+はR.javaにidを追加すると意味。
android:idは新しくidを作りたいわけだから、@+id/で指定する
たとえば、@+id/hoge : R.java にhogeというidを追加するという意味。

@id/はすでにR.javaにあるidを参照するという意味。
たとえば、@id/hoge : R.javaのhogeを参照。

RelativeLayoutにポジションを指定する際は、
すでに描写してあるviewに対して、上か下かなどを指定したいので、@id/で指定する。

lintの段階でエラーにならないコード

以下の様なコードは、
実行時にエラーになるがeclipseでlintの段階でエラーならない。
@id/で書き直すと未定義idでlintのエラーで、間違ってることに気づく。

<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" >

    <LinearLayout
        android:id="@+id/header"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/context"
        android:layout_alignParentTop="true"
        android:orientation="horizontal" >
    </LinearLayout>

    <LinearLayout
        android:id="@+id/context"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/footer"
        android:layout_below="@+id/header"
        android:orientation="horizontal" />

    <LinearLayout
        android:id="@+id/footer"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true" />

</RelativeLayout>
28
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
25