我有两个列表我将list1
中的项目添加到另一个列表中,但是当我点击某个项目时。程序结束时没有任何错误
debug显示异常错误
以下是代码: -
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String lst1[] = {"abdul","yousuf","khalid","john","egor"};
String lst2[]= {};
Double lp1[]={10.0,5.0,2.0,0.5,1.5};
Double lp12[]={};
ListView lis1= (ListView)findViewById(R.id.lv1);
ListView lis2= (ListView)findViewById(R.id.lv2);
ArrayAdapter<String> adapter1 =new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,lst1);
final ArrayAdapter<String> adapter2 =new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,lst2);
lis1.setAdapter(adapter1);
lis2.setAdapter(adapter2);
lis1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = ((TextView)view).getText().toString();
adapter2.add(item);
}
});
}
答案 0 :(得分:1)
因为当你使用
ArrayAdapter<String> adapter1 =new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,lst2);`
// Internally a fixed size list will be generated ^^^^
然后lst2
数组将转换为固定长度列表,该列表无法接受新条目
public More ...ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects) {
init(context, resource, textViewResourceId, Arrays.asList(objects));
// fixed length array
}
了解asList
解决方案:
ArrayAdapter<String> adapter1 =new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
new ArrayList<String>(Arrays.asList(lst1));
// Pass array as new mutable list
final ArrayAdapter<String> adapter2 =new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1,
new ArrayList<String>(Arrays.asList(lst2));
答案 1 :(得分:0)
试试这个
lis1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item =lst1[position];
adapter2.add(item);
}
});
答案 2 :(得分:0)
这是解决方案
lis1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = ((TextView)view).getText().toString();
lst2.add(item);
adapter2.notifyDataSetChanged();
}
});