Android でアプリを開発しており、UI 要素をループで生成しています。ただし、これらの要素には、文字と数字の ID が必要です。たとえば"rl1"
、 または"rl2"
. メソッドを使用しようとしましたRelativeLayout.setId()
が、そのメソッドは のみを受け入れますint
。数字に限らずIDを自由に設定する方法はありますか?
ありがとう。
これが私が機能させようとしているコードです。
for (int i=1; i < 10; i++)
{
//gets the frameview where the elements will be created.
String LinearLayoutId = "frameview1";
int resID = getResources().getIdentifier(LinearLayoutId, "id", "com.myapp.ERS");
LinearLayout linearLayout = (LinearLayout)findViewById(resID);
//creates the RelativeLayout that will hold the ImageIcon and the TextView
RelativeLayout rl = new RelativeLayout(this);
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,40 );
rl.setLayoutParams(lp);
rl.setId("rl"); /// >>>> I would like here to set and ID of "rl1" for example.
rl.setBackgroundDrawable(getResources().getDrawable(R.drawable.bk36));
//creates the image icon within the layout at the left side
ImageView image = new ImageView(this);
lp = new RelativeLayout.LayoutParams(
40,RelativeLayout.LayoutParams.MATCH_PARENT );
image.setLayoutParams(lp);
String imageicon = "icon_"+i;
resID = getResources().getIdentifier(imageicon, "drawable", "com.myapp.ERS");
image.setImageDrawable(getResources().getDrawable(resID)); //sets the icon
rl.addView(image); //adds the ImageView to the relative layout
//creates the TextView within the layout with a 40 margin to the left
TextView tv = new TextView(this);
lp = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT );
lp.setMargins(40, 0, 0, 0);
tv.setLayoutParams(lp);
String textViewID = "tv"+i;
resID = getResources().getIdentifier(textViewID, "string", "com.myapp.ERS");
tv.setText(getResources().getString(resID));
tv.setTextColor(Color.BLACK);
tv.setTextSize(25);
rl.addView(tv);//adds the TextView to the relative layout
rl.setOnClickListener(mAddListener);
linearLayout.addView(rl);//adds the RelativeLayout to the LinearLayout
}
そして、私はこのようなOnClickListenerを持っています...
private OnClickListener mAddListener = new OnClickListener()
{
public void onClick(View v){
Intent intent;
Bundle bundle;
String id = getResources().getResourceEntryName(v.getId());
id = id.replaceAll("\\D+","");
int value = Integer.parseInt(id);
intent = new Intent(ERS.this, ShowInfo.class);
bundle = new Bundle();
bundle.putInt("key", value);
System.out.println(v.getId());
intent.putExtras(bundle);
startActivity(intent);
}
};
数値 ID を設定しようとしましたが、次のように検索すると、次のようになります。
String id = getResources().getResourceEntryName(v.getId());
それらを見つけることができません。
最初からこれらすべてをxml
ファイルに入れていましたが、リストには約40個のアイテムがあるため非常に長く、たとえばすべての文字を変更するのは複雑でした. 私はこのアイデアを思いつき、実行時にfor loop
. その間、10 でテストしていますが、動作しません。
私が何か間違ったことをしているなら、私を許してください、しかし私はこれに慣れていません。