我无法将活动扩展到listactivity。需要帮助

时间:2013-05-15 10:48:05

标签: java android android-intent android-listview

我无法将活动扩展到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));
    }
}

3 个答案:

答案 0 :(得分:1)

如果您要使用ListActivity,那么您不需要这一行:

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

但是现在引用的特定ListView(如果它位于相应的xml布局中)必须将其ID更改为

<ListView
  android:id="@android:id/list"
.....

答案 1 :(得分: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的默认布局由屏幕中央的单个全屏列表组成。因此您可以直接设置适配器。

查看docs以供参考

我希望它会有所帮助!!

答案 2 :(得分: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
}
}