RecyclerView внутри фрагмента не кликабелен - PullRequest
0 голосов
/ 31 октября 2019

Глупый вопрос, вероятно, но я не могу найти, почему мой RecyclerView не отвечает на щелчки. RV находится во фрагменте, я добавил интерфейс к адаптеру и внедряю его во фрагмент. Но при попытке щелчка эмулятор даже не издает звук "щелчка"

Это мой адаптер

public class ArtistsRvAdapter extends RecyclerView.Adapter<ArtistsRvAdapter.ArtistViewHolder> {
private List<Artist> mArtists;
private Context mContext;

final private ItemClickListener mItemClickListener;

public ArtistsRvAdapter(Context c, ItemClickListener listener){
    mContext=c;
    mItemClickListener =listener;
}

@NonNull
@Override
public ArtistsRvAdapter.ArtistViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
    int layoutIdForListItem = R.layout.artist_list_item;
    LayoutInflater inflater = LayoutInflater.from(mContext);
    boolean shouldAttachToParentImmediately = false;
    View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
    ArtistViewHolder viewHolder = new ArtistViewHolder(view);
    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull ArtistViewHolder artistViewHolder, int position) {
    Artist artist = this.mArtists.get(position);
    Log.d("rv adapter ", "artist img " + artist.getArtistImageUrl());
    String image = artist.getArtistImageUrl();

    Picasso.get()
            .load(image)
            .placeholder(R.drawable.ic_launcher_background)
            .error(R.drawable.ic_launcher_foreground)
            .into(artistViewHolder.artistImage);
        artistViewHolder.artistName.setText(artist.getArtistName());
    Log.d("rv adapter ", "artist name " + artist.getArtistName());
        artistViewHolder.artistGenre.setText(artist.getArtistGenre());
        artistViewHolder.concertDate.setText(artist.getConcertDate());
        artistViewHolder.concertLocation.setText(artist.getConcertLocation());
}

@Override
public int getItemCount() {
    return (null != mArtists ? mArtists.size() : 0);
}

public class ArtistViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    ImageView artistImage;
    TextView artistName;
    TextView artistGenre;
    TextView concertLocation;
    TextView concertDate;

    public ArtistViewHolder(View itemView){
        super(itemView);
            artistImage = itemView.findViewById(R.id.artist_image);
            artistName = itemView.findViewById(R.id.artist_name);
            artistGenre = itemView.findViewById(R.id.artist_genre);
            concertLocation = itemView.findViewById(R.id.concert_location);
            concertDate = itemView.findViewById(R.id.concert_date);
    }

    @Override
    public void onClick(View v) {
        String elementID = mArtists.get(getAdapterPosition()).getKey();
        Log.d(" adapter " , "position clicked " + getAdapterPosition());
        mItemClickListener.onItemClickListener(elementID);
    }
}

public interface ItemClickListener {
     void onItemClickListener(String itemId);
  }

public void setArtists(List<Artist> artists){
    mArtists = artists;
    Log.d("rv " , "list artists " + mArtists);
    notifyDataSetChanged();
}

}

А это фрагмент

public class BaseFragment extends Fragment implements ArtistsRvAdapter.ItemClickListener {

private ArtistsRvAdapter mAdapter;
private String LOG_TAG = BaseFragment.class.getSimpleName();
private View mRootView;
@BindView(R.id.rv)
RecyclerView recyclerView;
private Context mContext;
private AppDatabase mDb;

public BaseFragment(){}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    mRootView= inflater.inflate(R.layout.base_fragment, container, false);
    ButterKnife.bind(this, mRootView);
    mContext = getActivity().getApplicationContext();
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(mContext);

    mDb = AppDatabase.getInstance(getActivity());

    mAdapter = new ArtistsRvAdapter(mContext, this);
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(mAdapter);

    DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
            ((LinearLayoutManager) layoutManager).getOrientation());
    recyclerView.addItemDecoration(dividerItemDecoration);

    setupViewModel();

    return mRootView;
}

private void setupViewModel(){
    Log.d(LOG_TAG, "getting artists from DB");
    DetailsViewModel viewModel = ViewModelProviders.of(getActivity()).get(DetailsViewModel.class);
    viewModel.getArtists().observe(this, new Observer<List<Artist>>() {
        @Override
        public void onChanged(List<Artist> artists) {
            mAdapter.setArtists(artists);
        }
    });
}

@Override
public void onItemClickListener(String itemId) {
    Intent i = new Intent(getActivity(), DetailsActivity.class);
    i.putExtra("artistId", itemId);
    startActivity(i);

}

}

Это xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto">


<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="6dp"
    android:theme="@style/Theme.Bacon.AppBarOverlay"
    app:layout_constraintTop_toTopOf="parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:layout_gravity="bottom">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:contentDescription="@string/app_name"
            android:src="@mipmap/logo"
            app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"/>

    </androidx.appcompat.widget.Toolbar>

</com.google.android.material.appbar.AppBarLayout>


<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="@dimen/min_margin_dp"
    android:layout_marginLeft="@dimen/min_margin_dp"
    android:layout_marginTop="@dimen/rv_margin"
    android:layout_marginEnd="@dimen/min_margin_dp"
    android:layout_marginRight="@dimen/min_margin_dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/appBarLayout">
</androidx.recyclerview.widget.RecyclerView>

Ответы [ 2 ]

1 голос
/ 31 октября 2019

добавьте эту строку "itemView.setOnClickListener (this);"в конструкторе ArtistViewHolder

 public ArtistViewHolder(View itemView){
        super(itemView);
            artistImage = itemView.findViewById(R.id.artist_image);
            artistName = itemView.findViewById(R.id.artist_name);
            artistGenre = itemView.findViewById(R.id.artist_genre);
            concertLocation = itemView.findViewById(R.id.concert_location);
            concertDate = itemView.findViewById(R.id.concert_date);

            itemView.setOnClickListener(this);
    };
1 голос
/ 31 октября 2019

В вашем ArtistViewHolder после super(itemView); добавьте

itemView.setOnClickListener(this);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...