0
我有這個代碼正在從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;
}
}
謝謝,但我已經做到了。我已經使用了普通的字符串變量,並且已經成功地獲得了複選框並將其發送給另一個活動,但是我無法爲上述代碼執行此操作。我不知道在哪裏需要包含代碼複選框。那就是我卡住的地方 – user2551275
好吧,我添加了一個複選框,現在第一個項目有一個複選框,但是如何將它添加到其他項目? – user2551275
它應該添加listview的每個項目列表,你不按照教程?有arraylist包含7個項目,並看到7複選框添加到相應的列表項。 – ridoy