如何解决如何在RecyclerView中更新项目的特定TextView?
当用户单击其他项目时,我想更新RecyclerView中的上一个TextView项目:
例如,如果用户单击“ lemanju” TextView,它将字体颜色更改为橙色,而当用户单击“ Lightning” TextView时,lemanju的字体颜色应恢复为黑色,而Lighning的字体颜色必须变为橙色,如下所示。
Lightning being selected (How I expect it to work)
Lightning being selected (What is happening now -> not updating lemanju's font color back to black)
我在适配器类中尝试了以下代码以实现此结果:
// set previous item TextColor to black.
holder.itemView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
holder.adapter.notifyItemChanged(previousSamplePosition);
// set actual item TextColor to orange.
holder.itemView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
不幸的是,当我单击Lightning时,我无法将lemanju的字体颜色改回黑色。
有人知道如何使用notifyItemChanged更改特定的TextView吗?还是有另一种方法可以实现?
我的适配器类中的onCreateViewHolder方法可以在下面看到:
/**
* Sets the contents of an item at a given position in the RecyclerView.
* Called by RecyclerView to display the data at a specificed position.
*
* @param holder The view holder for that position in the RecyclerView.
* @param samplePosition The position of the item in the RecyclerView.
* <p>
*/
@Override
public void onBindViewHolder(@NonNull SampleViewHolder holder,int samplePosition) {
if (sampleList != null) {
Sample currentSample = sampleListFiltered.getCurrentList().get(samplePosition);
// Add the data to the view holder.
holder.sampleView.setText(currentSample.getName());
holder.bind(currentSample);
if (sampleNameSearched != null) {
String sampleName = Normalizer.normalize(sampleListFiltered.getCurrentList().get(samplePosition).getName(),Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]","").toLowerCase();
Pattern sampleQuery = Pattern.compile(sampleNameSearched);
Matcher sampleMatcher = sampleQuery.matcher(sampleName);
SpannableStringBuilder spanString = new SpannableStringBuilder(sampleListFiltered.getCurrentList().get(samplePosition).getName());
while (sampleMatcher.find()) {
spanString.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD),sampleMatcher.start(),sampleMatcher.end(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
holder.sampleView.setText(spanString);
} else {
// This solved the problem
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
}
}
Bundle sampleBundle = new Bundle();
holder.sampleView.setOnClickListener(view -> {
sampleBundle.putLong("Sample",sampleListFiltered.getCurrentList().get(samplePosition).getId());
SampleCollectorListNavigatorFragment.addScreenToStack(0);
SampleCollectorListNavigatorFragment.setLastSurveyIdAccessed(sampleListFiltered.getCurrentList().get(samplePosition).getSurveyId());
Navigation.findNavController(view).navigate(R.id.action_sampleCollectorListNavigator_to_sampleCollectorInspectSampleFragment,sampleBundle);
});
holder.sampleView.setOnLongClickListener(view -> {
sampleBundle.putLong("Sample",sampleListFiltered.getCurrentList().get(samplePosition).getId());
if (sampleID == 0) {
// Access the view of the previous screen
((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
} else if (sampleID == sampleListFiltered.getCurrentList().get(samplePosition).getId()) {
if (((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).getVisibility() == View.VISIBLE) {
((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.GONE);
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
} else {
((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
}
} else if (sampleID != sampleListFiltered.getCurrentList().get(samplePosition).getId()) {
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
notifyItemChanged(previousSamplePosition);
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
}
sampleID = sampleListFiltered.getCurrentList().get(samplePosition).getId();
previousSamplePosition = samplePosition;
return true;
});
}
}
更新->如何解决此问题?
要解决代码中的问题,我必须在搜索过滤器中将字符串更新回黑色:
// This solved the problem
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
但是,如果您的结构与我的不同,或者您只想更新回收站中的上一个TextView项目,则可以使用以下部分代码:
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
notifyItemChanged(previousSamplePosition);
notifyItemChanged(previousSamplePosition)
可以解决问题。
解决方法
这是一个基本示例,下面我也添加了您的代码
您的适配器
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private String[] mDataset;
List<TextView> textViews = new ArrayList<>();
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item,and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView textView;
public MyViewHolder(TextView v) {
super(v);
textView = v.findViewById(R.id.textView);
}
}
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.my_text_view,parent,false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder,int position) {
holder.textView.setText(mDataset[position]);
views.add(holder.textView);
}
@Override
public int getItemCount() {
return mDataset.length;
}
public List<TextView> getTextViews(){
return textViews;
}
}
您的活动
public class MainActivity extends AppCompatActivity {
private Button changeColorButton;
private RecyclerView recyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
changeColorButton = findViewById(R.id.button);
recyclerView = findViewById(R.id.recyclerView);
MyAdapter adapter = new MyAdapter(new String[]{"Hello","world"});
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
changeColorButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
int length = adapter.getTextViews().size();
List<TextView> textViews = adapter.textViews;
for(int i=0; i<length; i++){
textViews.get(i).setTextColor(Color.parseColor("#bdbdbd"));
}
}
});
}
}
现在输入您的代码
public static class SampleViewHolder extends RecyclerView.ViewHolder {
private final TextView sampleView;
/**
* Creates a new custom view holder to hold the view to display in the RecyclerView.
*
* @param sampleListView The view in which to display the data.
* @param adapter The adapter that manages the the data and views for the RecyclerView.
*/
public SampleViewHolder(View sampleListView) {
super(sampleListView);
sampleView = sampleListView.findViewById(R.id.data_name);
}
}
/**
* Inflates an item view and returns a new view holder that contains it.
* Called when the RecyclerView needs a new view holder to represent an item.
*
* @param parent The view group that holds the item views.
* @param viewType Used to distinguish views,if more than one type of item view is used.
* @return a view holder.
*/
@NonNull
@Override
public SampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent,int viewType) {
// Inflate an item view.
View sampleListView = inflater.inflate(R.layout.fragment_sample_collector_list_sample,false);
return new SampleViewHolder(sampleListView);
}
/**
* Sets the contents of an item at a given position in the RecyclerView.
* Called by RecyclerView to display the data at a specificed position.
*
* @param holder The view holder for that position in the RecyclerView.
* @param samplePosition The position of the item in the RecyclerView.
* <p>
* TODO: Most important method used
*/
@Override
public void onBindViewHolder(@NonNull SampleViewHolder holder,int samplePosition) {
if (sampleList != null) {
// Retrieve the data for that position.
//Sample currentSample = sampleListFiltered.get(samplePosition);
Sample currentSample = sampleListFiltered.getCurrentList().get(samplePosition);
// Add the data to the view holder.
holder.sampleView.setText(currentSample.getName());
holder.bind(currentSample);
list.add(holder.sampleView);
if (sampleNameSearched != null) {
String sampleName = Normalizer.normalize(sampleListFiltered.getCurrentList().get(samplePosition).getName(),Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]","").toLowerCase();
Pattern sampleQuery = Pattern.compile(sampleNameSearched);
Matcher sampleMatcher = sampleQuery.matcher(sampleName);
SpannableStringBuilder spanString = new SpannableStringBuilder(sampleListFiltered.getCurrentList().get(samplePosition).getName());
while (sampleMatcher.find()) {
spanString.setSpan(new android.text.style.StyleSpan(android.graphics.Typeface.BOLD),sampleMatcher.start(),sampleMatcher.end(),Spannable.SPAN_INCLUSIVE_INCLUSIVE);
}
holder.sampleView.setText(spanString);
}
}
Bundle sampleBundle = new Bundle();
holder.sampleView.setOnClickListener(view -> {
sampleBundle.putLong("Sample",sampleListFiltered.getCurrentList().get(samplePosition).getId());
SampleCollectorListNavigatorFragment.addPreviousScreen(0);
SampleCollectorListNavigatorFragment.setLastSurveyIdAccessed(sampleListFiltered.getCurrentList().get(samplePosition).getSurveyId());
Navigation.findNavController(view).navigate(R.id.action_sampleCollectorListNavigator_to_sampleCollectorInspectSampleFragment,sampleBundle);
});
holder.sampleView.setOnLongClickListener(view -> {
sampleBundle.putLong("Sample",sampleListFiltered.getCurrentList().get(samplePosition).getId());
// TODO: if the same button is clicked close the buttonPanel,else keep it open.
if (sampleID == 0) {
// Access the view of the previous screen
((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
} else if (sampleID == sampleListFiltered.getCurrentList().get(samplePosition).getId()) {
if (((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).getVisibility() == View.VISIBLE) {
((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.GONE);
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
} else {
((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
}
} else if (sampleID != sampleListFiltered.getCurrentList().get(samplePosition).getId()) {
Toast.makeText(inflater.getContext(),"list size() " + list.size(),Toast.LENGTH_SHORT).show();
// I CANNOT CHANGE THE COLOR OF THE PREVIOUS SAMPLE RIGHT HERE.
List<RecyclerView.ViewHolder> vh = getItem();
changeColor(vh,previousSamplePosition);
holder.adapter.notifyItemChanged(previousSamplePosition);
holder.sampleView.setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.PrimaryColor_1));
((Activity) inflater.getContext()).findViewById(R.id.ButtonPanel).setVisibility(View.VISIBLE);
}
sampleID = sampleListFiltered.getCurrentList().get(samplePosition).getId();
previousSamplePosition = samplePosition;
return true;
});
}
public List<RecyclerView.ViewHolder> getItem(){
return list;
}
public void changeColor(List<RecyclerView.ViewHolder> vh,int previousSamplePosition) {
for (int i = 0; i < list.size(); i++) {
if(i == previousSamplePosition) {
// Does not change the previous TextView.
Toast.makeText(inflater.getContext(),"i -> " + i + " previousSamplePos -> " + previousSamplePosition,Toast.LENGTH_SHORT).show();
// How can I use the vh here?
//vh.get(i).setTextColor(ContextCompat.getColor(inflater.getContext(),R.color.BaseColor_1));
//holder.adapter.notifyItemChanged(i);
}
}
}
}
让我知道它是否有效
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。