我是 Android 的新手,我正在学习上下文菜单,但是在浏览了上下文菜单之后,我对 Adapter 和 Inflater 有点困惑。我看到 1 个使用适配器的程序和 1 个使用 Inflater 的程序。所以,请帮助我如何/何时使用 Adapter 和 Inflater。
这是一个使用充气机的例子......
public class MainActivity extends ListActivity {
private String selectedName = "";
private String[] nameList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
nameList = getResources().getStringArray(R.array.name_list);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, nameList));
registerForContextMenu(getListView());
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.context_menu, menu);
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo adapInfo = (AdapterContextMenuInfo) item
.getMenuInfo();
selectedName = nameList[(int) adapInfo.id];
switch (item.getItemId()) {
case R.id.view:
Toast.makeText(MainActivity.this,
"You have pressed View Context Menu for " + selectedName,
Toast.LENGTH_LONG).show();
return true;
case R.id.save:
Toast.makeText(MainActivity.this,
"You have pressed Save Context Menu for " + selectedName,
Toast.LENGTH_LONG).show();
return true;
case R.id.edit:
Toast.makeText(MainActivity.this,
"You have pressed Edit Context Menu for " + selectedName,
Toast.LENGTH_LONG).show();
return true;
case R.id.delete:
Toast.makeText(MainActivity.this,
"You have pressed Delete Context Menu for " + selectedName,
Toast.LENGTH_LONG).show();
return true;
}
return false;
}
}
另一个使用适配器的例子:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Countries = getResources().getStringArray(R.array.Game);
ListView list = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.listitem, Countries);
list.setAdapter(adapter);
registerForContextMenu(list);
}
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId() == R.id.list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle(Countries[info.position]);
String[] menuItems = getResources().getStringArray(
R.array.contextmenu);
for (int i = 0; i < menuItems.length; i++) {
menu.add(Menu.NONE, i, i, menuItems[i]);
}
}
}
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
.getMenuInfo();
int menuItemIndex = item.getItemId();
String[] menuItems = getResources().getStringArray(R.array.contextmenu);
String[] menuItems1 = getResources().getStringArray(R.array.game);
String menuItemName = menuItems[menuItemIndex];
String listItemName = menuItems1[info.position];
// selectedName = nameList[(int) info.id];
TextView text = (TextView) findViewById(R.id.textView1);
text.setText(String.format("Selected %s for item %s", menuItemName,
listItemName));
return true;
}