[英]Android - How to change the visibility of a widget of and show it in all items in recyclerView?
[英]Change the View visibility of all items of RecyclerView
我有一個RecyclerView,當單擊某些項目時,他會播放錄音。 我希望當用戶單擊item1時正在播放特定的錄音,並且更改了“視圖”按鈕,這可以正常工作。
但是同時播放item1錄音時,用戶單擊item2,然后item1的行Button將返回到其原始位置。
在圖像下方顯示了單擊item1(Row 1)時的視圖。 (這很好)
我也測試了此方法以控制inBindViewHolder方法中的View。但是它不起作用,因為每當我單擊Holder對象時,都僅控制當前選定行的View。
mPlayAudio.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Log.d(TAG, "onClick: Present in onClick mPlayAudio");
if (listener != null)
{
final int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION)
{
// This section contain the code to play and stop
the audio
// Using below line I only able to change selected
// row button View not other row Button View
mPlayAudio.setImageResource(R.drawable.play);
}
}
}
});
我也在onBindViewHolder方法中嘗試過此方法,但仍無法正常工作。
holder.mPlayAudio.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View view) { // This section contain code to play and stop audio //Using below statement I only able to change the //visibility of current selected row View not others holder.mPlayAudio.setImageResource(R.drawable.play); } }
因此,我終於能夠在自己的項目中進行嘗試。
答案 BindViewHolder,你做一個項目點擊后,保存項目的位置的值。 然后在click事件中調用notifyDataSetChanged,這將刷新適配器。 現在,它獲得您的結果,在BindViewHolder內部有一個if語句,檢查該值是否應相應設置(或不可見),否則顯示為可見。
范例程式碼
public class SelectorAdapter extends RecyclerView.Adapter<SelectorAdapter.ItemHolder> implements View.OnClickListener {
private List itemList;
private int selectedKey;
public SelectorAdapter(List list) {
itemList = list;
}
@Override
public void onClick(View v) {
}
/* ViewHolder for each item */
class ItemHolder extends RecyclerView.ViewHolder {
//title
@BindView(R.id.selector_title)
TextView title;
@BindView(R.id.selector_layout)
LinearLayout selector;
ItemHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
@Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout_selector, parent, false);
return new ItemHolder(itemView);
}
@Override
public void onBindViewHolder(ItemHolder holder, int position) {
String title = (String) itemList.get(position);
holder.title.setText(title);
if (position != selectedKey) {
holder.title.setBackgroundResource(R.drawable.selector);
} else {
holder.title.setBackgroundResource(R.drawable.selector_selected);
}
holder.itemView.setOnClickListener(v -> {
Timber.e("selected item: %s", position);
selectedKey = position;
notifyDataSetChanged();
});
}
@Override
public int getItemCount() {
Timber.e("itemCount: %s", itemList.size());
return itemList.size();
}
}
這是我自己的項目,當我選擇一個項目時,它將背景資源更改為“選定”,然后將其余資源返回到默認狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.