2013-03-02 3 views
6

これを長らく検索して作業しています。 (これは、単純でなければならない支援のおかげで?。)findViewById(R.id。>> StringVarHere <<)の操作方法は?

通常、より多くのハードコード化された方法でEditTexts'テキストの全画面表示を設定しますが、いない/取得しよう:

代わり
... findViewById (R.id.SomeTextWidgetId) ; 

、私は(String)name_of_widgetを保持する変数を介して再利用可能な方法を理解しようとしています。擬似コードで

findViewById(R.id >> StringVarHere < <)。 // どうやってするか ?

私はまた、このfindViewById方法を試してみましたが、それはうまくいきませんでした(!?)

//// 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") ; 
} 

予想したように、私は、... GENを

//// 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 ...   
     /> 

を.setIdを試してみました

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

「編Rファイルは、このような何かを持っています

はい、ありがとう - それは活動の中でそれを行うことが理にかなっています。私はコードが大きすぎるのを防ぐよう努めていました。ここで私はあなたとA-Cの有益な提案に基づいて今何をしているのですか? 1つのString []にフォームのすべてのテキストを戻すことを意図しています。 (私はすべてのフィールドにも力を入れることができると知っています)

皆さんはこれについて以下のすべてを考えていますか?あなたの提案、マッドマッドと非常によく似ていますか?これが貧弱な設計アプローチであるかどうか疑問に思っていますか?

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 

はその後Activityクラスから、それだけだ。これは作業を行い

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

- 私はそれがテストにスタンドアロンしようとしたとき:

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()); 
} 
+0

あなたが試したと言うSOの答えを見ると、うまくいくはずです。 'setContentView()'を呼び出した後、すべてこれを行うようにしてください –

+0

"SO"?あれは何でしょう ? ...うん、setContentViewを忘れると、参照するためのXMLがないことを意味します:) ... –

+0

SO = "StackOverflow"。私はあなたが鉱山かその答えの実装を使っていた試練を投稿すべきだと思います。私は私の実装を試して、それは動作したので、私はそれがあなたのために働いていないのか分かりません。 –

答えて

3

(私はあなたがしようとしている方法を理解するよう)あなたがそれを行うことの方法は次のとおりです。

これは、非活動(YourClassnameにすることができます。Javaの):アクティビティクラスで

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

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") ; 
     } 
    } 
} 

しかし、私はそれはのようなアクティビティクラスのコードへのより良いと思う:

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") ; 
     } 
    } 
} 
+0

あなた、Code-Guru、そしてA-Cが私を助けてくれました。 –

2

ACは、の線に沿って何かを示唆しましたリグ。ありがとう!まだ何が爆発しているのかは分かりませんが、コンテキストやリソースの項目がアクセス不能であると思われます。

+0

アクティビティクラスにない場合は、 'context.getResources()。getIdentifier(field、" id "、getPackageName());' – madlymad

+0

を使用してくださいありがとうmadlymad - (AFAICT?)がコンテキストを非アクティビティクラスのコンストラクタに渡しました - context.getResources()。getIdentifier ...有効なIDを返していましたが、使用しようとするとnull pntr例外が発生しました。 ... –

+0

上記の返信を参照してください - (Kevを除いて、間違ったポストを修正してくれてありがとう!) –

1

なお、変数名( R.id.some_idなど)は、コンパイル時にのみ使用でき、実行時にString値からアクセスすることはできません。これらのIDはintと宣言されているため、IDを格納するにはint[]またはList<Integer>を使用することを検討することがあります。あなたのレイアウトがどのように動的であるか、その中のビューを使って何をやっているかによって、実行時にビューを作成し、idsをまったく使用せずに配列またはリストを保存するだけでもいいかもしれません。

+1

リストのおかげでありがとう - 良いアイデア...問題は、コンテキストが適切でないためにIDを取得/保存するほどではありませんでした。 - Kevが私の返事をあまりにも上の正しい場所に移動しました。 –

+0

@HowardPautzあなたはそれを理解してうれしいです。あなたのAndroidプログラミングで幸運を祈る! SOにようこそ。 –

+0

Code-Guru、運と歓迎にとても感謝します! SOが何となくすばらしいと評価されています。バグのほとんどすべてのGoogle検索は、どれほど曖昧であっても、ヒットのトップでSOを見つけます! –

関連する問題

 関連する問題