Search code examples
javaandroidfindviewbyid

I want to use findViewById with strings as an Id


I am new to Android Studio and just trying to learn new ways to code and I'm stuck right now. I would like to use a String in a findViewById for example.

public void BDate0(String BId, String BHistoryClass) {
        bdatum0 = (Button) findViewById(R.id.BId);
        bdatum0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent BDatum0 = new Intent(bethistory.this, BHistoryClass.class);
                startActivity(BDatum0);
            }
        });
    }

and I would like to call the BDate0 with the strings for example,

BDate0(BId1, BHistory1);

I have 10 buttons and the activity they start would be different every day.

Sorry for bad englihs it's not my native language and thank you for help in advance.


Solution

  • You can use this code to replace the findViewById(..). This should make it possible to use a string as identifier:

    String BId = "button1"; // for example 
    int id = getResources().getIdentifier(BId, "id", getPackageName());
    // finds R.id.button1
    bdatum0 = (Button) findViewById(id);