Programmatically Add Id to R.Id

programmatically add id to R.id

You can set ID's you'll use later in R.id class using an xml resource file, and let Android SDK give them unique values during compile time.

res/values/ids.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

<item name="my_edit_text_1" type="id"/>
<item name="my_button_1" type="id"/>
<item name="my_time_picker_1" type="id"/>

</resources>

To use it in code:

myEditTextView.setId(R.id.my_edit_text_1);

How can I assign an ID to a view programmatically?

Android id overview

An Android id is an integer commonly used to identify views; this id can be assigned via XML (when possible) and via code (programmatically.) The id is most useful for getting references for XML-defined Views generated by an Inflater (such as by using setContentView.)

Assign id via XML

  • Add an attribute of android:id="@+id/somename" to your view.
  • When your application is built, the android:id will be assigned a unique int for use in code.
  • Reference your android:id's int value in code using "R.id.somename" (effectively a constant.)
  • this int can change from build to build so never copy an id from gen/package.name/R.java, just use "R.id.somename".
  • (Also, an id assigned to a Preference in XML is not used when the Preference generates its View.)

Assign id via code (programmatically)

  • Manually set ids using someView.setId(int);
  • The int must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)
  • For example, if creating and numbering several views representing items, you could use their item number.

Uniqueness of ids

  • XML-assigned ids will be unique.
  • Code-assigned ids do not have to be unique
  • Code-assigned ids can (theoretically) conflict with XML-assigned ids.
  • These conflicting ids won't matter if queried correctly (keep reading).

When (and why) conflicting ids don't matter

  • findViewById(int) will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View it finds with a matching id.
  • As long as there are no code-assigned ids assigned before an XML-defined id in the hierarchy, findViewById(R.id.somename) will always return the XML-defined View so id'd.

Dynamically Creating Views and Assigning IDs

  • In layout XML, define an empty ViewGroup with id.
  • Such as a LinearLayout with android:id="@+id/placeholder".
  • Use code to populate the placeholder ViewGroup with Views.
  • If you need or want, assign any ids that are convenient to each view.
  • Query these child views using placeholder.findViewById(convenientInt);

  • API 17 introduced View.generateViewId() which allows you to generate a unique ID.

If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext() and be sure to set each reference to null in onDestroy. Apparently leaking the Activity (hanging onto it after is is destroyed) is wasteful.. :)

Reserve an XML android:id for use in code

API 17 introduced View.generateViewId() which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

Conflicting id example

For clarity by way of obfuscating example, lets examine what happens when there is an id conflict behind the scenes.

layout/mylayout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>

To simulate a conflict, lets say our latest build assigned R.id.placeholder(@+id/placeholder) an int value of 12..

Next, MyActivity.java defines some adds views programmatically (via code):

int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
TextView tv = new TextView(this.getApplicationContext());
// One new TextView will also be assigned an id==12:
tv.setId(i);
placeholder.addView(tv);
}

So placeholder and one of our new TextViews both have an id of 12! But this isn't really a problem if we query placeholder's child views:

// Will return a generated TextView:
placeholder.findViewById(12);

// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12:
Activity.this.findViewById(12);

*Not so bad

how to set android:id in programmatically in android?

You can use #layerList.setId and set the id by index . Check the code below . I have made few changes in it to match it to xml-drawable .

val layer1 = GradientDrawable()
layer1.cornerRadius = 10f
layer1.setStroke(1, Color.WHITE)
layer1.setColor(Color.YELLOW)

val scaleDrawable = GradientDrawable()
scaleDrawable.cornerRadius = 10f
scaleDrawable.setStroke(1, Color.WHITE)
scaleDrawable.setColor(Color.BLUE)

val layer2 = ScaleDrawable(scaleDrawable, Gravity.START,1f,0.1f)
val drawableList = arrayOf(layer1, layer2)
val layerList = LayerDrawable(drawableList)
layerList.setId(0,android.R.id.background)
layerList.setId(1,android.R.id.progress)
seekBar.progressDrawable = layerList

How to programmatically get resource Id for android.R.id.content?

I have solved it by using a named view, setting the id in the xml layout of the activity and using the following code to replace the root view...

int containerViewId = getResources().getIdentifier("rootView", "id", getPackageName());
getFragmentManager().beginTransaction().replace(containerViewId, new SettingsFragment()).commit();

android - set ID to the view programmatically

According to the API it's not forbidden or deprecated. Here is the best way of using it.

  1. Create res/values/ids.xml and define

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
    <item type="id" name="button1" />
    <item type="id" name="button2" />
    </resources>
  2. once you have that, you can than use setId

    button1.setId(R.id.button1);
    button2.setId(R.id.button2);

Assign R.id to dynamically created Edit Text

In android id should be unique. Setting any arbitrary integer value can lead to duplicate ids. The correct way is to define id like below.

Create a new xml file named ids.xml inside res/values folder.

Add new item like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="button_group_cancel" />
</resources>

Now you can set the id to edittext as:

edittext.setId(R.id.button_group_cancel);

Android create ID programmatically

Refer to this fantastic answer: https://stackoverflow.com/a/13241629/586859

R.* references are used explicitly to access resources. What you are trying to do is not really possible, but maybe you could us something like the following section from the above answer:

Reserve an XML android:id for use in code

If your ViewGroup cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:

Here, values/ids.xml defines a custom id:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
</resources>

Then once the ViewGroup or View has been created, you can attach the custom id

myViewGroup.setId(R.id.reservedNamedId);

How to set id for each item in a view dynamically?

As @Rasoul Miri said, you can use View.generateViewId() to set id for newly inserted views, and you should use a list to record them. And also you should set the id for those three items.

like these:

for the inserted view

<EditText
android:id="@+id/one_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="number"/>
<EditText
android:id="@+id/two_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="number"/>
<EditText
android:id="@+id/three_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:inputType="number"/>

for the MainActivity

public ArrayList<InsertedView> list;

public void addView() {
View new_view = layoutInflater.inflate(R.layout.new_layout,insertPoint, false);
insertPoint.addView(new_view);
index_num++;
InsertedView insertedView = new InsertedView(View.generateViewId(), View.generateViewId(), View.generateViewId());
new_view.findViewById(R.id.one_view).setId(insertedView.firstId);
new_view.findViewById(R.id.two_view).setId(insertedView.secondId);
new_view.findViewById(R.id.three_view).setId(insertedView.thirdId);
list.add(insertedView);
}

class InsertedView {
public int firstId;
public int secondId;
public int thirdId;
public InsertedView(int one, int two, int three) {
firstId = one;
secondId = two;
thirdId = three;
}
}


Related Topics



Leave a reply



Submit