How to do a findViewById (R.id.>> StringVarHere << )?

限于喜欢 提交于 2019-12-12 10:43:21

问题


Searched and working on this a long while - no luck. ( It must be simple ? Thanks for the assist. )

Trying to get / set a screen full of EditTexts' text, but not with the usual, more hard-coded way:

... findViewById (R.id.SomeTextWidgetId) ;

Instead, I'm trying to figure out a reusable way via a variable holding the (String) name_of_widget.

In psuedo code:

findViewById (R.id.>> StringVarHere << ); // how to do that ?

I tried also this findViewById method, but it didn't work (!?)

//// given:

static final String FIELD_TV_FEE   = "TextViewFee" ;
static final String FIELD_TV_FOO   = "TextViewFoo" ;
static final String FIELD_TV_FUM   = "TextViewFum" ;
//// and some arbitrary number more of similar fields  

static final String [] ALL_FIELDS = {

    FIELD_TV_FEE ,
    FIELD_TV_FOO ,  
    FIELD_TV_FUM   // ...
 } ; 

//// ...

    //// this part works
    int ResourceID;
    String stringVarHere = FIELD_TV_FEE; 

    //// outputs a correct id, say '0x7f05000f' as in R.id.xxx below
    ResourceID = context
                       .getResources()
                       .getIdentifier ( stringVarHere,
                                        "id", 
                                        context 
                                          .getApplicationInfo()
                                          .packageName
                                      ) ;
    Log.d ("MyClass" , "RESID = " + Integer.toHexString(ResourceID) ) ;  
/*
 * that's where I'm stuck ^^^ ... how do I do:
 */

String field_name ;

for ( field_name : ALL_FIELDS ) {
    (EditText) SomethingLike_a_findViewById(field_name).setText ("Hello Wurld") ;
}

I've tried .setId ...

//// details

    <!-- excerpt from working xml layout -->
    <EditText
        android:id="@+id/TextViewFee"
        android:inputType="text"
        android:layout ... etc ...         
        />
    <EditText
        android:id="@+id/TextViewFoo"
        android:inputType="text"
        android:layout ... etc ...         
        />
    <EditText
        android:id="@+id/TextViewFum"
        android:inputType="text"
        android:layout ... etc ...         
        />

As expected, the gen'ed R file has something like this:

// ...
public static final class id {
    public static final int TextViewFee=0x7f05000f;
    public static final int TextViewFum=0x7f05001c;
    public static final int TextViewFoo=0x7f05001d;
    // ... etc

Yes, thanks - it makes sense to do it in the activity. I was trying to keep it from getting too code bulky. Here's what I'm doing now, based on your and A-C's helpful suggestions. The intention is to get all the text of fields of a form back in one String[]. (I know I could brute force all the fields too.)

What do you all think about this below - seems very similar to your suggestion, madlymad ? I am wondering if this is a poor design approach ?

public class FoodBar {

private Activity activity; 
private Context ctx;

public  FoodBar ( Activity _activity ) {        
    this.activity = _activity;
    this.ctx = this.activity.getApplicationContext() ;
}

public String[] getTextFromAllEditTexts () { // the UI views

    int res_id = 0;
    int i = 0;   

    String [] retValues = new String [MyClassName.ALL_FIELDS_LENGTH] ;

    for (String field : MyClassName.ALL_FIELDS_ALL_VEHICLES) {

       res_id = this.ctx.getResources()
                        .getIdentifier ( field, "id", this.ctx.getPackageName() );

           ((EditText) this.activity
                           .findViewById (res_id))
                           .setText( "Meat and Potatoes" ) ;

               // redundant - get it right back to make sure it really went in !  
        retVal[i++] = ((EditText) this.activity
                                        .findViewById (res_id))
                                        .getText().toString() ;
    }

     return retVal;

} // end func
} // end class

Then from the Activity class, it's just:

String [] theFields = null;
FoodBar = new FoodBar (this);

try {

     theFields = FoodBar.getTextFromAllEditTexts ();

} catch (Exception e) {
     Log.d ("OOPS", "There's a big mess in the Foodbar: " + e.toString() );
}

回答1:


The way you could do it is (as I understand the way you are trying):

This can be in non-Activity (YourClassname.java):

public static int getMyId(Context context, String field) {
     return context.getResources().getIdentifier (field, "id", context.getPackageName());
}

in Activity-class:

for ( String field_name : YourClassname.ALL_FIELDS ) {
    int resid = YourClassname.getMyId(context, field_name);
    if(resid != 0) { // 0 = not found 
       EditText et = (EditText) findViewById(resid);
       if (et != null) {
          et .setText ("Hello Wurld") ;
       }
    }
}

But I think it's better to code in the activity class like:

String packageName = getPackageName();
Resources res = getResources();
for ( String field_name : YourClassname.ALL_FIELDS ) {
    int resid = res.getIdentifier (field_name, "id", packageName);
    if(resid != 0) {// 0 = not found 
       EditText et = (EditText) findViewById(resid);
       if (et != null) {
          et .setText ("Hello Wurld") ;
       }
    }
}



回答2:


A-C suggested something along the lines of:

res_id = getResources().getIdentifier (field, "id", getPackageName());
((EditText)findViewById (res_id)).setText("NoLongerFubar");

this DOES work - when I tried it standalone in a test rig. Thanks ! Still not sure what was blowing up, but I suspect it was Context or Resource items not being accessible.




回答3:


Note that variable names (such as R.id.some_id) are only available at compile time and cannot be accessed from a String value at run time. Since these ids are declared as ints, you might consider using an int[] or List<Integer> to store the ids. Depending on how dynamic your layout is and what you are doing with the Views in it, you might even want to simply create the Views at run time and store an array or List of them without using any ids at all.



来源:https://stackoverflow.com/questions/15179797/how-to-do-a-findviewbyid-r-id-stringvarhere

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!