2012-07-05 47 views
0

我想在列表視圖中列出用戶安裝的應用程序。我試過許多方法,如@android:ID和@ + ID,但似乎沒有任何work..can有人指出什麼是這個代碼錯誤..listview給出運行時異常

applist.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> 

listrow.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); 
    } 
} 

回答

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'

+0

謝謝你,擴展活動解決了這個問題.. – user340

1

ListActivity有由一個唱默認佈局le,屏幕中央的全屏列表。但是,如果您願意,可以通過在onCreate()中使用setContentView()設置您自己的視圖佈局來自定義屏幕布局。要做到這一點,自己的觀點必須包含id爲一個ListView對象「@android:ID /列表」(或列表,如果它在代碼)