Converting "R.id.myID" from a String to the int value R.id.myID?
The text on my views represent an id. So when clicked I would like to get a reference to that resource. The following incorrect code represents what I'm trying to do
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.categories);
Bundle bundle = getIntent().getExtras();
i开发者_如何学Cnt myArrayID = bundle.getInt("category_id", 0);
String [] myArray = getResources().getStringArray(myArrayID);
setListAdapter(new CategoryAdapter(this, android.R.layout.simple_list_item_1, R.id.categoryText, myArray));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String myIdString = (String) ((TextView) view.findViewById(R.id.categoryText)).getText();
int myIdInt = // convert to the correct id that is represented by this string myIdString
Intent intent = new Intent(Categories.this, Categories.class);
intent.putExtra("category_id", myIdInt);
startActivity(intent);
}
});
}
I understand why this method doesn't work. For example the view would have the text "example1" and then there would be an R.id.example1 value that I need to get a reference to. Obviously I am approaching this the wrong way, and would like some guidance.
Edit - more code as requested.
Edit2 - Poor description. So my activity is a custom list. When one of the views is clicked, the title of that item will correspond to a string-array I have in my strings.xml. So if "example1" is pressed, there will be a string-array with the id R.array.example1. I want my code to extract the text of the view, and use it to find the correct string-array. This string-array would then be used to populate a new activity, with the custom list items the items in the array
I didn't get exactly what your code is supposed to do. But to get a resource id out of the resource name, use the following
getResources().getIdentifier(<resource name>, "id", getPackageName())
Read more here.
The best solution to store the resource Id would probably be using the Tag
property of the TextView (If I understand correctly, the TextView from your code is part of a custom list item, correct ?)
精彩评论