0

我想在列表视图中列出用户安装的应用程序。我尝试了很多方法,例如 @android:id 和 @+id 但似乎没有任何效果..有人可以指出这段代码中的错误是什么..

应用列表.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout> 

列表行.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"
    android:layout_height="match_parent" 
    android:padding="10dp"  
    android:textSize="16sp"
    android:id="@+id/rowTextView">
</TextView>

InstalledApp 类

public class InstalledApps extends ListActivity{

    private ListView listview;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.applist);

        listview = (ListView)findViewById(R.id.listView1);

        PackageManager pm = getPackageManager();
        List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

        List<ApplicationInfo> installedApps = new ArrayList<ApplicationInfo>();

        for(ApplicationInfo app : packages) {
            //checks for flags; if flagged, check if updated system app
            if((app.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 1) {
                //installedApps.add(app);
            //it's a system app, not interested
            } else if ((app.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
                //Discard this one
            //in this case, it should be a user-installed app
            } else {
                installedApps.add(app);
            }
        }

        ArrayAdapter<ApplicationInfo> adapter = new ArrayAdapter<ApplicationInfo>(this,
                R.layout.listrow, installedApps);
        listview.setAdapter(adapter);
    }
}
4

2 回答 2

1

ListActivity 有一个默认布局,它由屏幕中央的单个全屏列表组成。但是,如果您愿意,您可以通过在 onCreate() 中使用 setContentView() 设置您自己的视图布局来自定义屏幕布局。为此,您自己的视图必须包含一个 ID 为“@android:id/list”的 ListView 对象(如果它在代码中,则为列表)

于 2012-07-05T02:53:57.920 回答
1

您的代码似乎没问题,只是尝试了一个小错误public class InstalledApps extends Activity,而不是public class InstalledApps extends ListActivity如果您扩展ListActivity,那么您将收到错误Caused by: java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'

于 2012-07-05T02:57:13.527 回答