2012-07-28 78 views
0

我使用了自定义行至极一个ListView中有2个TextViews。我已经制作了自己的适配器,并且它与我的列表正常工作。现在,我希望用户输入2个文本,然后在我的ListView中插入一个新行(用户输入)。我试着用add方法,但我得到UnsupportedOperationException。我是否也必须重写add方法?如果是的话,我需要做些什么?谢谢。如何修改几个textviews同一行一个ListView

我要粘贴代码的片段。让我知道你是否需要进一步的信息。

public class ChatAdapter extends ArrayAdapter<ChatItems>{ 

Context context; 
int textViewResourceId; 
ChatItems[] objects; 


public ChatAdapter(Context context, int textViewResourceId, 
     ChatItems[] objects) { 
    super(context, textViewResourceId, objects); 

    this.context = context; 
    this.textViewResourceId = textViewResourceId; 
    this.objects = objects; 
} 


@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    View row = convertView; 
    ChatHolder holder = null; 


    if(row == null){ 
    LayoutInflater inflater = ((Activity)context).getLayoutInflater(); 
    row = inflater.inflate(textViewResourceId, null); 

    holder = new ChatHolder(); 
    holder.user = (TextView) row.findViewById(R.id.textUser); 
    holder.msg = (TextView) row.findViewById(R.id.textText); 

    row.setTag(holder); 

    }else 
     holder = (ChatHolder) row.getTag(); 


    ChatItems items = objects[position]; 
    holder.msg.setText(items.msg); 
    holder.user.setText(items.user); 


    return row; 

} 
static class ChatHolder{ 
    TextView user; 
    TextView msg; 
} 

}

public class ChatItems { 

String user; 
String msg; 

public ChatItems(String user, String msg){ 
    this.user = user; 
    this.msg = msg; 
} 

}

回答

1

如果你想添加另一项到你的ArrayAdapter使用ArrayList而不是Array作为你的后端数据的持有者。如果您使用的Array,比ArrayAdapter将使用内部List不能在以后修改。

从您的ChatAdapterobjects场。

重写你的构造类似

public ChatAdapter(Context context, int textViewResourceId, List<ChatItems> objects) { 
    super(context, textViewResourceId, objects); 
    this.context = context; 
    this.textViewResourceId = textViewResourceId; 
} 

以获得该项目在getView()使用ChatItems items = getItem(position)代替ChatItems items = objects[position];

最后创建适配器像adapter = new ChatAdapter(this, R.layout.chat_item, new ArrayList<ChatItems>());

+0

谢谢您的快速ansers!你们都是对的(Sa Dec)。我正在使用一个简单的数组而不是ArrayList。一旦改变它正常工作。 – Godraude 2012-07-28 14:52:54

3

我猜你使用的不可变列表,因此它提出UnsupportedOperationException当你试图元素(S)添加到列表中。考虑使用ArrayList或可变的东西。

如果您可以提供的logcat那么它将帮助(我们)更多。

0

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

“ 然而TextView的引用,将填充有toString()将阵列中的每个对象的。可以添加列表或自定义对象的阵列。覆盖的toString()方法你的对象,以确定哪些文本将显示在列表中的项目。

您需要用适配器比列表视图本身多玩,列表视图后,所有使用的适配器。

那个文件夹应该包含你所需要的所有信息。 祝你好运!请记住发布您的解决方案。