【问题标题】:Listview shows junk valueListview 显示垃圾值
【发布时间】:2013-07-10 16:01:12
【问题描述】:

您好,我正在做示例项目,因为我遇到了一个问题,例如 listitem 显示一些垃圾值。不知道怎么解决。谁能帮帮我。

这是我的活动:

public class MainActivity extends Activity {
ListView app_List;
private ArrayList<AppInfo> infoList;
private ArrayAdapter<AppInfo> adpt;
@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    app_List = (ListView)findViewById(R.id.listView1);
    infoList = getListOfUserInstalledApps();
    }

   private ArrayList<AppInfo> getListOfUserInstalledApps() {
    // TODO Auto-generated method stub
    List<PackageInfo> apps = getPackageManager().getInstalledPackages(0);
    System.out.println("No. of applications installed on the device: "+apps.size());
    ArrayList<AppInfo> infoList1 = new ArrayList<AppInfo>();
    for(int i=0;i<apps.size();i++) {        
        PackageInfo p = apps.get(i);        
        /*if ((!getSysPackages) && (p.versionName == null)) {      
            continue ;        }*/

        AppInfo info = new AppInfo();
        //info.appname = p.applicationInfo.loadLabel(getPackageManager()).toString();
        info.pname = p.packageName;
        System.out.println("application name: "+info.pname);
        //info.pname = p.packageName;
        infoList1.add(info);

    }
    return infoList1;
}
static class AppInfo {
    //private String appname = "";    
    private String pname = "";    
    //private String versionName = "";    
    //private int versionCode = 0;    
    //private Drawable icon;

}


@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    adpt =  new ArrayAdapter<AppInfo>(this,android.R.layout.simple_list_item_1, infoList);
    app_List.setAdapter(adpt);

}
}

参考屏幕截图

http://i.stack.imgur.com/w4Axi.png

【问题讨论】:

    标签: java android listview android-listview android-widget


    【解决方案1】:

    ListView 显示的不是垃圾,而是对象AppInfo 引用的人类表示。您有两种方法可以解决您的问题。您可以将ArrayList&lt;String&gt; 而不是ArrayList&lt;AppInfo&gt; 传递给ArrayAdapter,或者从ArrayAdapter 覆盖getView

    编辑

    正如@Luksprog 建议的那样(请参阅下面的评论),您还可以覆盖AppInfo.toString() 以返回pname

    【讨论】:

    • 您有两种方法可以解决您的问题 - 或者第三种更简单的方法,即覆盖 toString() 类的 toString() 方法以返回目标值( pname 我假设)。
    • 当心! @toString() 并不意味着为用户界面提供文本。它应该提供关于对象的人类可读信息。 toString 用于记录和调试
    • @verbose-mode 告诉ArrayAdapter类。
    【解决方案2】:

    您的屏幕截图显示了每个 AppInfo 对象的 toString 值。 AppInfo 应覆盖 toString 以将结构显示为您想要的字符串。

    http://developer.android.com/reference/android/widget/ArrayAdapter.html

    【讨论】:

      猜你喜欢
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多