我正在開發一個應用程序在Android上,我正在循環中生成UI元素。但我需要這些元素以字母和數字來標識,例如"rl1"
或"rl2"
。我試圖使用方法RelativeLayout.setId()
,但該方法只接受int
。有沒有一種方法可以根據需要設置ID而不受數字限制?如何爲UI元素分配字符串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
中生成它們。與此同時,我正在測試10個,但我無法完成它的工作。
如果我做的不正確,請原諒我,但我對此很陌生。
我是這個新手,我不知道你的意思是由SharedPreferences – jorgerodriguezhn
檢查這個鏈接如何使用它:http://developer.android.com/guide/topics/data/data-storage。 html #pref –
@jerisalan如果您仔細查看代碼,生成的元素是佈局,ImageView和其他UI元素。我不認爲SharedPreferences是真正的存儲這些ID的方式。 – Chilledrat