0

我已经为自己构建了一个应用程序,其中包含一个列表。到目前为止,我已经使用SimpleAdapter来填充列表,但我决定移动到ArrayAdapter。问题是,我不知道如何以相同的方式填充ArrayAdapter!下面是我使用的方法我SimpleAdapter从simpleAdapter转换为ArrayAdapter

adapter=new SimpleAdapter(this, listItems, R.layout.custom_row_view, new String[]{"name", "current", "reset"}, new int[] {R.id.text1, R.id.text2, R.id.text3}); 

我listItems中的变量实际上是设置这样的:

static final ArrayList<HashMap<String,String>> listItems = new ArrayList<HashMap<String,String>>(); 

现在,尝试使用ArrayAdapter构造函数使用相同的参数时,它给我一个错误。这怎么能做到?

回答

1

现在,试图用一个ArrayAdapter构造具有相同 参数时,它给我一个错误。

这是因为一个ArrayAdapter被设计用于非常简单的场景,其中数据是在一个列表/阵列仅具有单个微件(通常是TextView)以结合的形式。当你在你的布局三种构件你需要扩展ArrayAdapter类绑定您的数据,因为它不能做到这一点对自己用的默认实现,这样的事:

listView.setAdapter(
      new ArrayAdapter<HashMap<String, String>>(this, R.layout.custom_row_view, 
        R.id.text1, listItems) { 

         @Override 
         public View getView(int position, View convertView, 
           ViewGroup parent) { 
          View rowView = super.getView(position, convertView, parent); 
          final HashMap<String, String> item = getItem(position); 
          TextView firstText = (TextView) rowView.findViewById(R.id.text1); 
          firstText.setText(item.get("corresponding_key")); 
          TextView secondText = (TextView) rowView.findViewById(R.id.text2); 
          secondText.setText(item.get("corresponding_key")); 
          TextView thirdText = (TextView) rowView.findViewById(R.id.text3); 
          thirdText.setText(item.get("corresponding_key")); 
          return rowView; 
         } 

      }); 

但在最后有一个问题,为什么你要使用ArrayAdapter,当SimpleAdapter更适合你的情况。

+0

在stackoverflow上可能至少有50个问题,询问如何对列表视图中的某些数据进行更改,但答案很少。你对这个问题的回答也回答了这50个问题。 – SmulianJulian 2015-05-20 09:14:08

0

你应该定义一个ArrayAdapter这样的:

ListView listView = (ListView) findViewById(R.id.mylist); 
String[] values = new String[] { "Android", "iPhone", "WindowsMobile", 
    "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X", 
    "Linux", "OS/2" }; 

// Define a new Adapter 
// First parameter - Context 
// Second parameter - Layout for the row 
// Third parameter - ID of the TextView to which the data is written 
// Fourth - the Array of data 

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
    android.R.layout.simple_list_item_1, android.R.id.text1, values); 


// Assign adapter to ListView 
listView.setAdapter(adapter); 
+0

我知道这一点,但我有我自己的布局,你可以看到上面,以及不止一个'R.id.text $'。请看我的更新,因为我的值也存储在'ArrayList >'中。 – arielschon12 2013-03-09 10:16:14

+0

啊,我明白了。我不认为你可以像这样使用ArrayAdapter;您将必须实现从BaseAdapter派生的自定义适配器。如果你需要列,为什么不使用GridView呢? – crazylpfan 2013-03-09 10:30:20