我在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有几个主要改进,我真的建议您看看它。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/
我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru
我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t
我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚
Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack
我在MiniTest::Spec和Capybara中使用以下规范:find_field('Email').must_have_css('[autofocus]')检查名为“电子邮件”的字段是否具有autofocus属性。doc说如下:has_css?(path,options={})ChecksifagivenCSSselectorisonthepageorcurrentnode.据我了解,字段“Email”是一个节点,因此调用must_have_css绝对有效!我做错了什么? 最佳答案 通过JonasNicklas得到了答案:No
在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/
我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为