Next view id as a custom attribute in android

2019-06-23 14:20发布

问题:

For my custom view I have also defined a custom attribute for keep id of the view. Its format is "reference".

in layout xml it is defined like below, very similar with android:layout_below attr

<mycustomview id="@+id/cv_1" xyz:nextviewId="@id/cv_2"... />
<mycustomview id="@+id/cv_2" xyz:nextviewId="@id/cv_3"... />
...
<LinearLayout ...>
    <mycustomview id="@+id/cv_3" xyz:nextviewId="@id/cv_4"... />
</LinearLayout>
...

it gives me error I think it is because it is not declared yet.

Any suggestion for accessing the next object similar to this approach!!!

I am thinking to use tag attr for the next object find the next one with findByTag function. Is this a good way to do it.

Thanks a lot.

回答1:

Change your xml to:

...
<mycustomview id="@+id/cv_1" xyz:nextviewId="@+id/cv_2"... />
<mycustomview id="@+id/cv_2" xyz:nextviewId="@+id/cv_3"... />
...

(note the @+id in nextviewId)

This will work on Android 1.6+ (Api Level 4+). Exactly the same approach is used in RelativeLayouts.