我有这段代码,它正在努力从 android 获取所有已安装的应用程序,但现在我想在每个列表项旁边显示一个复选框,并将这些项目单击到其他活动中。我使用过普通字符串,当我使用代码时它似乎可以正常工作
setListAdapter(new ArrayAdapter<String>(this, android.R.simple_list_item_checked, stringname));
但这在这里行不通,因为它没有可以带的字符串。第二行的适配器变量是一个对象,所以我不能使用它,所以请告诉我如何在每个项目旁边添加一个复选框。谢谢。
这是我的代码
public class MainActivity extends ListActivity {
AppAdapter adapter=null;
String[] apps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lstView = getListView();
lstView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
PackageManager pm=getPackageManager();
Intent main=new Intent(Intent.ACTION_MAIN, null);
main.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> launchables=pm.queryIntentActivities(main, 0);
Collections.sort(launchables,
new ResolveInfo.DisplayNameComparator(pm));
adapter=new AppAdapter(pm, launchables);
setListAdapter(adapter);
}
@Override
protected void onListItemClick(ListView l, View v,
int position, long id) {
ResolveInfo launchable=adapter.getItem(position);
ActivityInfo activity=launchable.activityInfo;
ComponentName name=new ComponentName(activity.applicationInfo.packageName,
activity.name);
Intent i=new Intent(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_LAUNCHER);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |
Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
i.setComponent(name);
startActivity(i);
}
class AppAdapter extends ArrayAdapter<ResolveInfo> {
private PackageManager pm=null;
AppAdapter(PackageManager pm, List<ResolveInfo> apps) {
super(MainActivity.this, R.layout.row, apps);
this.pm=pm;
}
@Override
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView==null) {
convertView=newView(parent);
}
bindView(position, convertView);
return(convertView);
}
private View newView(ViewGroup parent) {
return(getLayoutInflater().inflate(R.layout.row, parent, false));
}
private void bindView(int position, View row) {
TextView label=(TextView)row.findViewById(R.id.label);
label.setText(getItem(position).loadLabel(pm));
ImageView icon=(ImageView)row.findViewById(R.id.icon);
icon.setImageDrawable(getItem(position).loadIcon(pm));
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_settings :
/*Intent myIntent = new Intent(this,MainActivity.class);
myIntent.putExtra("key", adapter);
startActivity(myIntent);
break;*/
}
return false;
}
}