我有一个带有列表视图的活动。单击列表视图中的项目时,会将意图发送到包含单击项目的值的下一个列表。该列表是使用 xml 文件生成的。
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Selected item
String cat = ((TextView) view).getText().toString();
// Launching new Activity on selecting single Item List
Intent intent = new Intent(getApplicationContext(), ContentListing.class);
// Sending data to new activity
intent.putExtra("cat", cat);
startActivity(intent);
}
在下一个活动中,我再次必须读取一个 xml 文件,但该文件将根据在上一个列表中单击的项目而有所不同。
// Creating a handle to capture data sent from previous activity
Intent intent = getIntent();
// Storing the category into a variable
String cat = intent.getStringExtra("cat");
// Storing string resources into Array
String[] itemList = getResources().getStringArray(R.array.itemList);
我想做一些像String[] itemList = getResources().getStringArray(R.array.cat);
ie R.array.variable这样对我不起作用的事情。我是 java 和 android 的新手,所以欢迎任何形式的帮助(易于理解和实施)。
另外,我希望第二个活动的名称每次都与单击的项目不同。我应该为此做些什么?
编辑:
这是我更新的代码,它给出了关于 getContext() 的错误
public class ContentListing extends ListActivity {
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content_listing);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
// Creating a handle to capture data sent from previous activity
Intent intent = getIntent();
// Storing the category into a variable
String cat = intent.getStringExtra("cat");
setTitle(cat);
// Line that shows error
int resourceId = Resources.getSystem().getIdentifier(cat, "array", getContext().getPackageName());
Log.d("Print message1: ", String.valueOf(resourceId)+"\n");
if(resourceId != 0) {
Log.d("Print message: ", String.valueOf(resourceId)+"\n");
// Storing string resources into Array
//String[] itemList = getResources().getStringArray(R.array.itemList);
String[] itemList = getResources().getStringArray(resourceId);
// Binding resources Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item2, R.id.label, itemList));
ListView lv = getListView();
// Listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single Item List
Intent intent = new Intent(getApplicationContext(), ContentListing.class);
// Sending data to new activity
intent.putExtra("product", product);
startActivity(intent);
}
});
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_content_listing, menu);
return true;
}
}