我在 android 上开发一个应用程序,我正在循环生成 UI 元素。但是我需要这些元素有一个带有字母和数字的 id,例如"rl1"
or "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
文件中,但它真的很长,因为列表中有大约四十个项目,而且我去更改所有这些项目中的一个字母是很复杂的。我想出了这个想法,在运行时以for loop
. 与此同时,我正在测试十个,但我无法让它工作。
如果我做错了什么,请原谅我,但我对此并不陌生。