我在aListView
中有一个Fragment
,我想在从另一个ListView
返回时更新Activity
中的数据。我重写了onResume()
中的Fragment
方法,修改了Adapter
中的数据,并调用了notifyDataSetChanged()
中的Adpater
,但不知何故ListView
没有被更新。我怀疑我的Adapter
有问题,但似乎找不到错误。
这是我的代码:
class ManualExceptionsListAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private TextView mManualExceptions;
SwitchCompat mSwitch;
TextView name;
final Context context = getActivity();
final SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
int a;
int ifUse = 0;
ManualExceptionsListAdapter(LayoutInflater inflater) {
mInflater = inflater;
}
@Override
public int getCount() {
return (mPermanentManualException.size()+mContactsExceptionNumber.size());
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public int getItemViewType(int position) {
if (position < (mContactsExceptionNumber.size())) {
a = 0;
if(position == (mContactsExceptionNumber.size()-1)){
ifUse = 1;
}
return a;
} else {
a = 1;
return a;
}
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
final int pos;
if(mContactsExceptionNumber.size()>0) {
pos = i - (mContactsExceptionNumber.size());
}else{
pos = 0;
}
int pos2 = 0;
int type = getItemViewType(i);
if(ifUse == 1){
if(mContactsExceptionNumber.size()>0) {
pos2 = i - (mContactsExceptionNumber.size());
Exceptions.index = pos2;
}
}
View v = view;
if (view == null) {
switch (type) {
case 0:
v = mInflater.inflate(R.layout.contacts_exception_row, null);
name = (TextView) v.findViewById(R.id.contact_name);
name.setText(mContactsExceptionNames.get(i));
break;
case 1:
v = mInflater.inflate(R.layout.manual_exception_row, null);
mManualExceptions = (TextView) v.findViewById(R.id.manual_exception_number);
mSwitch = (SwitchCompat) v.findViewById(R.id.manual_exception_switch);
mManualExceptions.setText(mPermanentManualException.get(pos2));
mSwitch.setTag(i);
try {
if (mManualExceptionList.contains(mPermanentManualException.get(pos2))) {
mSwitch.setChecked(true);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}else{
switch (type) {
case 0:
v = mInflater.inflate(R.layout.contacts_exception_row, null);
name = (TextView) v.findViewById(R.id.contact_name);
name.setText(mContactsExceptionNames.get(i));
break;
case 1:
v = mInflater.inflate(R.layout.manual_exception_row, null);
mManualExceptions = (TextView) v.findViewById(R.id.manual_exception_number);
mSwitch = (SwitchCompat) v.findViewById(R.id.manual_exception_switch);
mManualExceptions.setText(mPermanentManualException.get(pos2));
mSwitch.setTag(i);
try {
if (mManualExceptionList.contains(mPermanentManualException.get(pos2))) {
mSwitch.setChecked(true);
}
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
try {
mSwitch.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
isTouched = true;
return false;
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
try {
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (isTouched) {
if (b) {
if (!mManualExceptionList.contains((mPermanentManualException.get(pos)))) {
mManualExceptionList.add((mPermanentManualException.get(pos)));
}
mSharedPreferences.edit().putString("ManualExceptions", TextUtils.
join(",", mManualExceptionList)).apply();
} else {
try {
mManualExceptionList.remove((mPermanentManualException.get(pos)));
mSharedPreferences.edit().putString("ManualExceptions", TextUtils.
join(",", mManualExceptionList)).apply();
} catch (Exception e) {
e.printStackTrace();
}
}
Log.d("RejectCall", "Permanent " + TextUtils.join(",", mPermanentManualException));
Log.d("RejectCall", TextUtils.join(",", mManualExceptionList));
}
}
});
} catch (NullPointerException e) {
e.printStackTrace();
}
return v;
}
}
最佳答案
您的Adapter
实现存在多个问题。太多了,我不能给你建议如何解决它。我只想解释一下如何有效地实现Adapter
,然后将其应用到Adapter
。
可以说,您应该以最佳方式切换到使用新的RecyclerView
,它比旧的ListView
有许多重大改进。您可以在RecyclerView
文档here和googles指南中找到如何使用它here。
如果要在ListView
中显示数据,应首先为ListView
中的每个项创建布局。在本例中,我将使用以下布局:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="12dp">
<CheckBox
android:id="@+id/checkbox"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
为了捆绑要在
ListView
的每个项中显示的数据,我们编写了一个新的类,它只包含私有字段中的数据,以及获取和设置该数据的getter和setter。此类类通常称为视图模型。上述布局的视图模型可能如下所示:public class ExampleViewModel {
// This is the text which will be set to the CheckBox
private String text;
// This boolean will be used to save the checked state of the CheckBox
private boolean checked;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
}
这样的视图模型的每个实例将表示
ListView
中的一个项。当其中一个项目进入ListView
的可见区域时,它必须绑定到View
中的ListView
(这是我们必须在getView()
的Adapter
中实现的)。只要项目是可见的,模型将保持绑定到这个View
,但是一旦View
退出ListView
的可见区域,它将被回收并绑定到另一个刚刚进入可见区域的视图模型。这被称为视图回收,其目的是最小化ListView
的内存占用,并提高整体滚动性能和流动性。Views
是非常昂贵的物品,尤其是充气Views
和findViewById()
会消耗很多性能,而回收利用的主要观点是,您只需充气少量的Views
即可重复使用,因此您可以避免昂贵的充气和以后的findViewById()
。我上面解释的大部分都是自动发生的。作为开发人员,您需要做的是在
Views
中对正确的getView()
进行充气,或者在已有可用的视图模型时重用它们,然后将正确的视图模型绑定到View
。我知道,如果你第一次听说这件事的话,大部分看起来都相当复杂和混乱,但是一旦我们开始看代码,事情就会变得简单和明显。现在我们有了
ListView
中视图项的布局和视图模型。我们现在需要做的是编写另一个类,通常称为视图持有者。这些视图持有者本质上是ListView
中视图周围的容器类。每个视图保持器都包含一个与View
中的项关联的ListView
,它们还负责将视图模型的数据绑定到View
。无需再多费周折,这里有一个视图固定器,可以从上面与视图模型一起使用:public class ExampleViewHolder {
// The reference to the CheckBox is saved so we only have to perform the findViewById() once.
private final CheckBox checkBox;
// A reference to the view model which is currently bound to this view holder
private ExampleViewModel currentModel;
// The View associated with this view holder is passed into the constructor from the Adapter.
public ExampleViewHolder(View view) {
// And here we look for all relevant views
// In our case we just need the CheckBox
this.checkBox = (CheckBox) view.findViewById(R.id.checkbox);
}
public void bind(ExampleViewModel viewModel) {
// Unset the listener in case there was one from a previous view model
this.checkBox.setOnCheckedChangeListener(null);
// Save a reference to the view model which is currently bound to this view holder
this.currentModel = viewModel;
// Bind the data to the CheckBox
this.checkBox.setText(viewModel.getText());
this.checkBox.setChecked(viewModel.isChecked());
// Reset the listener
this.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
currentModel.setChecked(isChecked);
}
});
}
}
现在我们差不多结束了。现在唯一缺少的是将所有这些都插入到
Adapter
中:public class ExampleAdapter extends BaseAdapter {
// Each type of view in the `ListView` gets its own id
// In this example we only have one type of View so we only need one id
private static final int EXAMPLE_VIEW_ID = 0;
// The default view id is just a fallback
private static final int DEFAULT_VIEW_ID = EXAMPLE_VIEW_ID;
private final LayoutInflater inflater;
private List<ExampleViewModel> viewModels;
public ExampleAdapter(Context context, List<ExampleViewModel> viewModels) {
// The view models are initially passed in through the constructor.
// You can pass an empty list into the Adapter if there is not data initially.
this.viewModels = viewModels;
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
if(viewModels == null) {
return 0;
}
return viewModels.size();
}
@Override
public Object getItem(int position) {
return viewModels.get(position);
}
@Override
public long getItemId(int position) {
final Object model = getItem(position);
// Here we check if the model is an instance of ExampleViewModel and if yes we return its id
if(model instanceof ExampleViewModel) {
return EXAMPLE_VIEW_ID;
}
return DEFAULT_VIEW_ID;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(getItemId(position) == EXAMPLE_VIEW_ID) {
final ExampleViewModel model = (ExampleViewModel) getItem(position);
final ExampleViewHolder viewHolder;
// If the convertView is null we need to inflate a new view
if(convertView == null) {
final View view = this.inflater.inflate(ExampleViewHolder.LAYOUT, parent, false);
viewHolder = new ExampleViewHolder(view);
// Here we set the viewHolder as tag to the View
// This is done so we can reuse the same view holder later on
// Essentially this is the integral part of the whole view recycling process
view.setTag(viewHolder);
} else {
// If the convertView is not null we can just get the view holder with getTag() from the View
viewHolder = (ExampleViewHolder) convertView.getTag();
}
// And we just need to bind the model to the view holder
viewHolder.bind(model);
}
return convertView;
}
}
这就是你所需要的。这几乎是
Adapter
的最佳实践实现。如果要处理两种或更多不同类型的视图,则需要为每种类型编写一个视图模型和视图保持器类。您可以编写一个名为ViewModel
的接口,其外观如下:public interface ViewModel {
}
您的每个视图模型都应该实现这个接口。然后可以在
List<ViewModel>
中使用Adapter
,它可以包含所有不同类型的视图模型。public class TypeOneViewModel implements ViewModel {
}
public class TypeTwoViewModel implements ViewModel {
}
只要所有视图模型都实现此接口,您就可以执行以下操作:
final List<ViewModel> models = new ArrayList<ViewModel>();
models.add(new TypeOneViewModel());
models.add(new TypeTwoViewModel());
...
这个
List
现在包含多种不同类型的视图模型,然后可以传递给Adapter
。然后Adapter
看起来像这样:public class ExampleAdapter extends BaseAdapter {
private static final int TYPE_ONE_VIEW_ID = 0;
private static final int TYPE_TWO_VIEW_ID = 1;
private static final int DEFAULT_VIEW_ID = TYPE_ONE_VIEW_ID;
private final LayoutInflater inflater;
private List<ViewModel> viewModels;
public ExampleAdapter(Context context, List<ViewModel> viewModels) {
this.viewModels = viewModels;
this.inflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
if(viewModels == null) {
return 0;
}
return viewModels.size();
}
@Override
public ViewModel getItem(int position) {
return viewModels.get(position);
}
@Override
public long getItemId(int position) {
final ViewModel model = getItem(position);
if(model instanceof TypeOneViewModel) {
return TYPE_ONE_VIEW_ID;
}
if(model instanceof TypeTwoViewModel) {
return TYPE_TWO_VIEW_ID;
}
return DEFAULT_VIEW_ID;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(getItemId(position) == TYPE_ONE_VIEW_ID) {
final TypeOneViewModel model = (TypeOneViewModel) getItem(position);
final TypeOneViewHolder viewHolder;
if(convertView == null) {
final View view = this.inflater.inflate(TypeOneViewHolder.LAYOUT, parent, false);
viewHolder = new TypeOneViewHolder(view);
view.setTag(viewHolder);
} else {
viewHolder = (TypeOneViewHolder) convertView.getTag();
}
viewHolder.bind(model);
}
if(getItemId(position) == TYPE_TWO_VIEW_ID) {
final TypeTwoViewModel model = (TypeTwoViewModel) getItem(position);
final TypeTwoViewHolder viewHolder;
if(convertView == null) {
final View view = this.inflater.inflate(TypeTwoViewHolder.LAYOUT, parent, false);
viewHolder = new TypeTwoViewHolder(view);
view.setTag(viewHolder);
} else {
viewHolder = (TypeTwoViewHolder) convertView.getTag();
}
viewHolder.bind(model);
}
return convertView;
}
}
您还可以通过编写抽象类来统一视图持有者。这样一个抽象类看起来像这样:
public abstract class ViewHolder<T extends ViewModel> {
protected final View itemView;
public ViewHolder(View view) {
this.itemView = view;
}
public abstract void bind(T model);
}
如果您使用这个抽象类作为视图保持器的基类,您将按如下方式编写它们:
public class TypeOneViewHolder extends ViewHolder<TypeOneViewModel> {
public TypeOneViewHolder(View view) {
super(view);
...
}
public void bind(TypeOneViewModel model) {
...
}
}
虽然这部分不是必需的。在
ListView
中处理多个不同类型的项时,最重要的部分是所有模型都实现一个公共接口,这样您就可以安全地将它们放在同一个List
中。总之,这整件事看起来比你的
Adapter
简单得多,不是吗?这样您就可以在ListView
中的数据和显示数据的Views
之间实现完美的分离,而且它的可维护性要高得多。您可以轻松地在视图保持器中实现动画,而不必关心视图回收,而且许多需求的实现变得简单得多。当然,RecyclerView
会把这一切带到下一个层次。它的工作原理几乎相同,但比ListView
有几个主要改进,我真的建议您看看它。我完全忘记了一件事:可以用getter公开视图模型的内部
List
,这样就可以从外部修改视图模型。在Adapter
中添加这样的方法:public List<ExampleViewModel> viewmodels() {
return viewModels;
}
public void setViewModels(List<ExampleViewModel> models) {
viewModels = models;
}
然后您可以修改
Adapter
中的视图模型,如下所示:adapter.setViewModels(newData);
...
adapter.viewmodels().add(viewModel);
修改完数据后,可以通过调用
ListView
上的notifyDataSetChanged()
来更新Adapter
。
关于android - 如何正确实现ListView的适配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27219144/