Android and getting a view with id cast as a string

后端 未结 2 1516
时光说笑
时光说笑 2020-11-28 07:08

In the Java code of an Android project if you want the reference for a view resource you can do something like:

View addButton = findViewById(R.id.button_0);         


        
2条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 07:45

    int resID = getResources().getIdentifier("button_%i",
        "id", getPackageName());
    View addButton = findViewById(resID);
    

    where %i is replaced by some valid index.

    The getResources() method belongs to the Context class, so you can use that directly from an Activity. If you are not inside an activity, then use a context to access: (myCtxt.getResources()).

提交回复
热议问题