我想在单击按钮时在列表视图中添加行,但我的应用程序每次都会崩溃。 这是我的代码:
public class MTCRichGraphicsActivity extends Activity {
int ELEMENT_COUNT = 3;
int position=0;
Button bAddView;
String[] elements = new String[ELEMENT_COUNT];
int r =0 ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bAddView = (Button) findViewById(R.id.bNewEvent);
final ListView list = (ListView) findViewById(R.id.list3d);
bAddView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.bNewEvent :
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
final MyAdapter adapter = new MyAdapter(MTCRichGraphicsActivity.this,elements);
adapter.notifyDataSetChanged();
//list.setScrollY(currentPosition);
//list.setTranslationY(currentPosition);
list.setDivider( null );
list.setAdapter(adapter);
adapter.notifyDataSetChanged();
ELEMENT_COUNT = ELEMENT_COUNT + 3;
}
}
});
}
}
这里我想在每次点击一个按钮(即bNewEvent)时添加3行,所以我每次都将ELEMENT_COUNT递增3。它第一次工作正常,但是当我第二次按下按钮时它会崩溃。
这是我的适配器类:
public class MyAdapter extends BaseAdapter {
private final LayoutInflater mInflater;
private final String[] mItems;
TextView t;
ViewHolder holder;
public MyAdapter(Activity c,String[] objects) {
mInflater = c.getLayoutInflater();
mItems = objects;
}
public int getCount() {
return mItems.length;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView t;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listitem2, parent,false);
}
holder = new ViewHolder();
holder.t1 = (TextView) convertView.findViewById(R.id.tv1);
holder.t2 = (TextView) convertView.findViewById(R.id.tv2);
holder.t3 = (TextView) convertView.findViewById(R.id.tv3);
holder.t4 = (TextView) convertView.findViewById(R.id.tv4);
holder.t1.setText("Title"+position);
position = position + 3;
//((ImageView)convertView).setTextAlignment(1);
return convertView;
}
@Override
public Object getItem(int position) {
return mItems[position];
}
@Override
public long getItemId(int position) {
return position;
}
}
答案 0 :(得分:0)
你不能使用像这样的数组..
String[] elements = new String[ELEMENT_COUNT];
导致数组与ELEMENT_COUNT的初始值具有相同数量的元素,然后您不能将ELEMENT_COUNT增加3并尝试
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
因为数组只包含最初定义的元素。您需要将'elements'更改为ArrayList。
ArrayList<string> elements;
答案 1 :(得分:0)
U define
int ELEMENT_COUNT = 3;
String[] elements = new String[ELEMENT_COUNT];
但是你不能调整数组大小
for (int i = 0; i< ELEMENT_COUNT; i++) {
elements[i] = String.valueOf(i);
}
这样你就得到了例外
将阵列更改为列表
喜欢
List<String> element =new ArrayList<String>();
for (int i = 0; i< ELEMENT_COUNT; i++) {
element.add("String.valueOf(i)")
}
和更改适配器也喜欢这个