Question

I'm working with a layout, that hosts many custom views. Each custom view has "myname:num" attribute, that holds unique number value.

Question: how can I find a view by "num" attribute? Normally I would use findViewById() method, but since the "android:id" can't be a number, I have to find another solution.

Layout definition:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:myname="http://schemas.android.com/apk/res/com.example"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <com.example.custom.MyView
            myname:num="17"
            myname:type="2" />
        <com.example.custom.MyView
            myname:num="18"
            myname:type="2" />
        <com.example.custom.MyView
            myname:num="19"
            myname:type="2" />
    </LinearLayout>
</LinearLayout>
Was it helpful?

Solution

Give each view an id, and then in your activity you can dynamically call each view by using

int dynamicId = getResources().getIdentifier("*unique_id*", "id", "*package_name*");
findViewById(dynamicId);

So if you id'ed each incrementally as view_1, view_2, ... view_numViews you can then get them dynamically using something like a loop

for(int i = 1; i <= numViews; i ++){
    int dynamicId = getResources().getIdentifier("view_" + i, "id", "*package_name*");
    MyView view = (MyView) findViewById(dynamicId);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top