使用notifyDataSetChanged()
适配器方法时,我无法显示ListView中显示的先前数据。使用的String数组(甚至尝试过ArrayList<String>
)来存储数据。
我已经尝试了几乎所有与此问题相关的答案,但无法获得正确的结果。任何帮助将不胜感激。 在我的代码中,我试图修改String数组。
MainActivity
public class MainActivity extends ActionBarActivity implements View.OnClickListener{
String countryArray[];
Button add;
CustomAdapter adapter;
ListView list,newList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countryArray = new String[3];
countryArray[0] = "India";
countryArray[1] = "USA";
countryArray[2] = "England";
adapter = new CustomAdapter(this,android.R.layout.simple_list_item_1,countryArray);
list = (ListView) findViewById(R.id.lvCheckList);
newList = list;
list.setAdapter(adapter);
add = (Button) findViewById(R.id.bAdd);
add.setOnClickListener(this);
}
@Override
public void onClick(View v) {
countryArray[2] = "belgium";
adapter.notifyDataSetChanged();
}
}
CustomAdapter
public class CustomAdapter extends ArrayAdapter<String> {
Context context;
String[] values;
View rowView;
public CustomAdapter(Context context, int val, String[] objects) {
super(context,val,objects);
this.context = context;
this.values = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.test, parent, false);
}
TextView tx = (TextView) rowView.findViewById(R.id.tv1);
ImageView iv = (ImageView) rowView.findViewById(R.id.iv1);
tx.setText(values[position]);
iv.setImageResource(R.drawable.Image1);
return rowView;
}
}
答案 0 :(得分:1)
请在代码中查看此行。
rowView = convertView;
当您放置notifydatasetchanged()
方法时,行将更新并刷新。因此,在获取数据后将此方法放在getView()
中。
请检查this link。
答案 1 :(得分:0)
您可以覆盖属于Activity的onResume方法。您需要将此方法添加到您的活动中。
@Override
public void onResume()
{
super.onResume();
adapter = new CustomAdapter(this,android.R.layout.simple_list_item_1,countryArray);
list.setAdapter(adapter);
}
答案 2 :(得分:0)
更改自定义适配器的getView()方法,如下所示..
@Override
public View getView(int position, View convertView, ViewGroup parent) {
rowView = convertView; //you are missing this line
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.test, parent, false);
}
TextView tx = (TextView) rowView.findViewById(R.id.tv1);
ImageView iv = (ImageView) rowView.findViewById(R.id.iv1);
tx.setText(values[position]);
iv.setImageResource(R.drawable.Image1);
return rowView;
}