2015-09-20 56 views
0

我有一個名爲SmsArrayAdapter具有代碼如下的arrayadapter獲得項目:如何從arrayadapter

public class SmsArrayAdapter extends ArrayAdapter<String> { 

    List<String> smsBody; 
    List<Boolean> Status; 
    Context context; 
    private static LayoutInflater inflater = null; 
    String fromNumber; 

    public SmsArrayAdapter(Context context, int resource, List<String> smsBody,List<Boolean> Status, 
      String fromNumber) { 
     super(context, resource, smsBody); 
     this.smsBody = smsBody; 
     this.Status = Status; 
     this.context = context; 
     inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     this.fromNumber = fromNumber; 
    } 

    public String getStr(int position) 
    { 
     return smsBody.get(position); 
    } 

    @Override 
    public String getItem(int position) { 
     // TODO Auto-generated method stub 
     return smsBody.get(position); 
    } 

    public static class ViewHolder { 

     public TextView textfrom; 
     public TextView text_sms; 

    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     ViewHolder holder; 
     if (convertView == null) { 

      /****** Inflate tabitem.xml file for each row (Defined below) *******/ 
      convertView = inflater.inflate(R.layout.row_item, null); 

      /****** View Holder Object to contain tabitem.xml file elements ******/ 

      holder = new ViewHolder(); 
      holder.textfrom = (TextView) convertView 
        .findViewById(R.id.textView_from); 
      holder.textfrom.setText(" SMS FROM " + fromNumber); 
      holder.text_sms = (TextView) convertView 
        .findViewById(R.id.textView_sms); 
      String smsTextToDisplay = smsBody.get(position); 
      if (smsTextToDisplay.length() > 100) 
       smsTextToDisplay = smsTextToDisplay.substring(0, 99) + " ..."; 

      holder.text_sms.setText(smsTextToDisplay); 

      if (Status.get(position) == false) { 
       convertView.setBackgroundColor(context.getResources() 
         .getColor(R.color.light_blue_overlay)); 

      } 

      /************ Set holder with LayoutInflater ************/ 
      convertView.setTag(holder); 
     } else 
      holder = (ViewHolder) convertView.getTag(); 




     return convertView; 
    } 

} 

我想這arrayadapter的項目。爲此,我有以下代碼:

public void onItemClick(AdapterView<?> parent, View view, int pos, long id) { 

     String smsMessageStr = (String) arrayAdapter.getItem(pos); 

     Toast.makeText(this, smsMessageStr, Toast.LENGTH_SHORT).show(); 

} 

但我無法獲得正確的項目。我能做什麼 ?我怎樣才能避免這個錯誤?

+1

使用'getItem(int position)'並移除'getStr' – pskink

回答

1

在適配器中,您可以使用getItem()來訪問列表中的項目。你的數組適配器保存字符串元素,getItem()返回一個字符串對象。

+0

爲什麼不能得到正確的項目? –

+0

嘗試「String str =(String)getListAdapter()。getItem(position);」 –