2

我无法将我的活动扩展到 listactivity。我想将它扩展到 listactivity 并将 onclicklistener 添加到列表项中。

public class MainActivity extends Activity {

    private ListView lView;
    private ArrayList results = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        lView = (ListView) findViewById(R.id.lvApps);
        PackageManager pm = this.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List < ResolveInfo > list = pm.queryIntentActivities(intent, PackageManager.PERMISSION_GRANTED);
        for (ResolveInfo rInfo: list) {
            results.add(rInfo.activityInfo.applicationInfo
                .loadLabel(pm).toString());
            Log.w("Installed Applications", rInfo.activityInfo.applicationInfo
                .loadLabel(pm).toString());
        }
        lView.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, results));
    }
}
4

3 回答 3

1

如果你要使用 aListActivity那么你不需要这一行:

ListView lView = (ListView) findViewById(R.id.lvApps);

但是现在引用的那个特定ListView的(假设它在相应的xml布局中)必须将它的id更改为

<ListView
  android:id="@android:id/list"
.....
于 2013-05-15T10:59:31.870 回答
1

使用以下代码:

    public class MainActivity extends ListActivity implements OnItemClickListener{

    private ArrayList results = new ArrayList();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//            setContentView(R.layout.activity_main);

        PackageManager pm = this.getPackageManager();

        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);

        List < ResolveInfo > list = pm.queryIntentActivities(intent, PackageManager.PERMISSION_GRANTED);
        for (ResolveInfo rInfo: list) {
            results.add(rInfo.activityInfo.applicationInfo
                .loadLabel(pm).toString());
            Log.w("Installed Applications", rInfo.activityInfo.applicationInfo
                .loadLabel(pm).toString());
        }
                getListView().setOnItemClickListener(this);

        setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, results));
    }

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    // TODO Auto-generated method stub

}

}

解释:

ListActivity 有一个默认布局,它由屏幕中央的单个全屏列表组成。因此您可以直接设置适配器。

查看文档以供参考

我希望它会有所帮助!

于 2013-05-15T10:59:49.150 回答
0

实现 OnItemClickListener

public class MainActivity extends ListActivity implements OnItemClickListener
{
   //your code;

    @Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
    // TODO Auto-generated method stub
    results.get(pos);  //this will give you the value in the clicked list item as per your code
}
}
于 2013-05-15T11:13:11.693 回答