【解決方法】r.id.i の配列[I] アンドロイド

プログラミングQA


TextView[] t = new TextView[8];
t[0] = (EditText)findViewById(R.id.seller1);
t[1] = (EditText)findViewById(R.id.seller2);
t[2] = (EditText)findViewById(R.id.seller3);
t[3] = (EditText)findViewById(R.id.seller4);
t[4] = (EditText)findViewById(R.id.seller5);
t[5] = (EditText)findViewById(R.id.seller6);
t[6] = (EditText)findViewById(R.id.seller7);
t[7] = (EditText)findViewById(R.id.seller8);

アンド・ゴー・オン

私が試したこと:

t[i] = (EditText)findViewById(R.id.selleri);

私のコードで何度も繰り返すので、seller1、seller2 ….をある種のselleriの配列に置き換えようとしています。 だから私は試してみました

Java
String[] Seller = {"seller1","seller2","seller3","seller4"};

そしてそれを交換してください

Java
t[i] = (EditText)findViewById(R.id.seller[i]);

しかし、エラーが発生します seller[i].

解決策 1

あなたの呼び出しからわかるように findViewById、文字列を使用してリソースを参照することはできません。実際のリソース識別子を使用する必要があります。 したがって、次のようなものを試すことができます:

Java
int[] Sellers = {r.id.seller1, r.id.seller2, r.id.seller3, r.id.seller4, ...};
// and replace it in 
t[i] = (EditText) findViewById(Sellers[i]);

しかし、これらすべてが疑問を投げかけます: 本当に必要ですか? EditText このためのタイプ、または可能性があります List<T> よく働く?

解決策 2

命名規則が固定されている場合は、すべての ID で配列を定義するよりも、以下のようなコードの方が簡単です。

試す:

Java
ArrayList<EditText> myList = new ArrayList<EditText>();

// Removed array
String sellerID;
int resourceViewID; 

for (int i = 0; i < 4; i++)
{
   sellerID = "seller" + i;
   resourceViewID = getResources().getIdentifier(sellerID, "id", getPackageName());
   myList.add((EditText)findViewById(resourceViewID);
}

参照: Java 配列リスト[^]

引用:

組み込み配列と Java の ArrayList の違いは、配列のサイズを変更できないことです (配列に要素を追加したり、配列から要素を削除したりするには、新しいものを作成する必要があります)。

解決策 3

TextView[] t = new TextView[8];
t[0] = (EditText)findViewById(R.id.seller1);
t[1] = (EditText)findViewById(R.id.seller2);
t[2] = (EditText)findViewById(R.id.seller3);
t[3] = (EditText)findViewById(R.id.seller4);
t[4] = (EditText)findViewById(R.id.seller5);
t[5] = (EditText)findViewById(R.id.seller6);
t[6] = (EditText)findViewById(R.id.seller7);
t[7] = (EditText)findViewById(R.id.seller8);
t[i] = (EditText)findViewById(R.id.selleri);

コメント

タイトルとURLをコピーしました