Android RecyclerView First and Last Item click works after Double click on First load

huangapple go评论57阅读模式
英文:

Android RecyclerView First and Last Item click works after Double click on First load

问题

我有一个RecyclerView。它在onCreateViewHolder方法中有一个项目点击事件,在onBindViewHolder方法中有一个ImageView点击事件。令人惊讶的是,当RecyclerView首次加载时,第一个和最后一个项目点击在第二次点击后才起作用,之后,如果不滚动,每次点击都起作用。再次滚动RecyclerView时,与首次加载时相同的情况发生在第一个和最后一个项目上。我无法找出问题所在。

以下是我的RecyclerView布局,@+id/recyclerViewForFilteredCourses 是RecyclerView:

    <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Activities.CoursesActivity">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <include layout="@layout/toolbar_with_search"
            android:id="@+id/toolbar" />

        <com.github.ybq.android.spinkit.SpinKitView
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/progressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            app:SpinKit_Color="@color/textColorGrey"
            android:visibility="gone"
            android:elevation="200dp"
            style="@style/SpinKitView.Circle"/>

        <!--这个TextView和RecyclerView负责过滤课程部分-->
        <TextView
            android:id="@+id/filterResultTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="显示 X 门课程"
            android:layout_below="@+id/toolbar"
            style="@style/headerTitleLabel"/>

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerViewForFilteredCourses"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/filterResultTitle"
            android:layout_above="@+id/bottomNavigationView"
            android:paddingHorizontal="14dp"
            android:clipToPadding="false"
            android:layout_marginTop="10dp"
            android:overScrollMode="never"/>

        <!--这是浮动的筛选按钮-->
        <com.google.android.material.floatingactionbutton.FloatingActionButton
            android:id="@+id/floatingFilterButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:clickable="true"
            android:layout_alignParentRight="true"
            android:layout_marginRight="25dp"
            android:layout_marginBottom="25dp"
            android:layout_alignParentBottom="true"
            android:backgroundTint="#273647"
            android:elevation="6dp"
            app:fabSize="normal"
            app:borderWidth="0dp"
            android:src="@drawable/filter"
            android:onClick="handleFilterButton" />
    </RelativeLayout>

    <androidx.core.widget.NestedScrollView
        android:id="@+id/bottomSheet"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#FEFFFF"
        app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior"
        app:behavior_hideable="true"
        app:behavior_peekHeight = "0dp">
        <include layout="@layout/course_filter_page" />
    </androidx.core.widget.NestedScrollView>

    </androidx.coordinatorlayout.widget.CoordinatorLayout>

以下是我的onCreateViewHolder中的项目点击事件:

    public CoursesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell2, parent, false);
        final ViewHolder holder = new ViewHolder(view);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final Course currentCourse = mCourses.get(holder.getAdapterPosition());
                switchToCourseDetailsActivity(currentCourse);
            }
        });
        return holder;
    }

以下是我的完整的onBindViewHolder

public class CoursesAdapter extends RecyclerView.Adapter<CoursesAdapter.ViewHolder> {
    // ... 其他成员和构造函数 ...

    @Override
    public void onBindViewHolder(@NonNull final CoursesAdapter.ViewHolder holder, final int position) {
        final Course currentCourse = mCourses.get(position);

        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchToCourseDetailsActivity(currentCourse);
            }
        });

        // ... 其他绑定操作 ...
    }

    // ... 其他方法 ...

    public class ViewHolder extends RecyclerView.ViewHolder {
        // ... ViewHolder 的成员变量 ...

        public ViewHolder(View itemView) {
            super(itemView);
            // ... 初始化 ViewHolder 的视图 ...
        }
    }
}
英文:

I have a recycerview. it has item click event in onCreateViewHolder method and an imageview click event on onBindViewHolder method. Surprisingly while recyclerview loads for the first time first and last item click works after second click then after it works on every click if it is not scrolled.Again when i scroll the recyclerview then same happen for the first and last item like first load. I can not figure out what is the problem

Below is my recyclerview layout @+id/recyclerViewForFilteredCourses is the recyclerview

    &lt;androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
xmlns:tools=&quot;http://schemas.android.com/tools&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
tools:context=&quot;.Activities.CoursesActivity&quot;&gt;
&lt;RelativeLayout
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;&gt;
&lt;include layout=&quot;@layout/toolbar_with_search&quot;
android:id=&quot;@+id/toolbar&quot; /&gt;
&lt;com.github.ybq.android.spinkit.SpinKitView
xmlns:app=&quot;http://schemas.android.com/apk/res-auto&quot;
android:id=&quot;@+id/progressBar&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_centerVertical=&quot;true&quot;
android:layout_centerHorizontal=&quot;true&quot;
app:SpinKit_Color=&quot;@color/textColorGrey&quot;
android:visibility=&quot;gone&quot;
android:elevation=&quot;200dp&quot;
style=&quot;@style/SpinKitView.Circle&quot;/&gt;
&lt;!--This textview and the recycler view is responsible for filtered course section--&gt;
&lt;TextView
android:id=&quot;@+id/filterResultTitle&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;Showing X Courses&quot;
android:layout_below=&quot;@+id/toolbar&quot;
style=&quot;@style/headerTitleLabel&quot;/&gt;
&lt;androidx.recyclerview.widget.RecyclerView
android:id=&quot;@+id/recyclerViewForFilteredCourses&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:layout_below=&quot;@+id/filterResultTitle&quot;
android:layout_above=&quot;@+id/bottomNavigationView&quot;
android:paddingHorizontal=&quot;14dp&quot;
android:clipToPadding=&quot;false&quot;
android:layout_marginTop=&quot;10dp&quot;
android:overScrollMode=&quot;never&quot;/&gt;
&lt;!--This is the floating filter button--&gt;
&lt;com.google.android.material.floatingactionbutton.FloatingActionButton
android:id=&quot;@+id/floatingFilterButton&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:clickable=&quot;true&quot;
android:layout_alignParentRight=&quot;true&quot;
android:layout_marginRight=&quot;25dp&quot;
android:layout_marginBottom=&quot;25dp&quot;
android:layout_alignParentBottom=&quot;true&quot;
android:backgroundTint=&quot;#273647&quot;
android:elevation=&quot;6dp&quot;
app:fabSize=&quot;normal&quot;
app:borderWidth=&quot;0dp&quot;
android:src=&quot;@drawable/filter&quot;
android:onClick=&quot;handleFilterButton&quot; /&gt;
&lt;/RelativeLayout&gt;
&lt;androidx.core.widget.NestedScrollView
android:id=&quot;@+id/bottomSheet&quot;
android:layout_width=&quot;match_parent&quot;
android:layout_height=&quot;match_parent&quot;
android:background=&quot;#FEFFFF&quot;
app:layout_behavior=&quot;com.google.android.material.bottomsheet.BottomSheetBehavior&quot;
app:behavior_hideable=&quot;true&quot;
app:behavior_peekHeight = &quot;0dp&quot;&gt;
&lt;include layout=&quot;@layout/course_filter_page&quot; /&gt;
&lt;/androidx.core.widget.NestedScrollView&gt;
&lt;/androidx.coordinatorlayout.widget.CoordinatorLayout&gt;

And below is my onCreateVieHolder Item click

    public CoursesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell2, parent, false);
final ViewHolder holder = new ViewHolder(view);
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Course currentCourse = mCourses.get(holder.getAdapterPosition());
switchToCourseDetailsActivity(currentCourse);
}
});
return holder;
}
private void switchToCourseDetailsActivity(Course currentCourse) {
Intent intent = new Intent(mContext, CourseDetailsActivity .class);
intent.putExtra(&quot;Course&quot;, currentCourse);
mContext.startActivity(intent);
}

And Below is my complete onBindViewHolder

public class CoursesAdapter extends RecyclerView.Adapter&lt;CoursesAdapter.ViewHolder&gt; {
private static final String TAG = &quot;Courses List Adapter&quot;;
private static final String TAG2 = &quot;Checker&quot;;
//vars
private Context mContext;
private ArrayList&lt;Course&gt; mCourses = new ArrayList&lt;&gt;();
Matcher matcher;
public CoursesAdapter(Context context, ArrayList&lt;Course&gt; courses) {
mCourses = courses;
mContext = context;
}
@NonNull
@Override
public CoursesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell2, parent, false);
final ViewHolder holder = new ViewHolder(view);
return holder;
}
private void switchToCourseDetailsActivity(Course currentCourse) {
Intent intent = new Intent(mContext, CourseDetailsActivity .class);
intent.putExtra(&quot;Course&quot;, currentCourse);
mContext.startActivity(intent);
}
@Override
public void onBindViewHolder(@NonNull final CoursesAdapter.ViewHolder holder, final int position) {
final Course currentCourse = mCourses.get(position);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchToCourseDetailsActivity(currentCourse);
}
});
holder.name.setText(currentCourse.getTitle());
// holder.coursePrice.setText(currentCourse.getPrice());
holder.totalNumberOfRating.setText(&quot;( &quot;+currentCourse.getTotalNumberRating()+&quot; )&quot;);
//holder.instructorName.setText(&quot;by &quot;+currentCourse.getInstructor()+&quot; &quot;+currentCourse.getBiography());
holder.starRating.setRating(currentCourse.getRating());
holder.rating.setText((&quot; &quot;+currentCourse.getRating()+&quot; &quot;));
if(currentCourse.getIs_bestseller().equals(&quot;yes&quot;)){
holder.tvBestseller.setVisibility(View.VISIBLE);
}else{
holder.tvBestseller.setVisibility(View.GONE);
}
if(currentCourse.getCourseOverviewUrl()!=null &amp;&amp; currentCourse.getCourseOverviewProvider()!=null &amp;&amp; currentCourse.getCourseOverviewProvider().equals(&quot;youtube&quot;)){
//Extract video id from url
String pattern = &quot;(?&lt;=watch\\?v=|/videos/|embed\\/|youtu.be\\/|\\/v\\/|\\/e\\/|watch\\?v%3D|watch\\?feature=player_embedded&amp;v=|%2Fvideos%2F|embed%\u200C\u200B2F|youtu.be%2F|%2Fv%2F)[^#\\&amp;\\?\\n]*&quot;;
Pattern compiledPattern = Pattern.compile(pattern);
matcher = compiledPattern.matcher(currentCourse.getCourseOverviewUrl()); //url is youtube url for which you want to extract the id.
if (matcher.find()) {
holder.play_video.setVisibility(View.VISIBLE);
holder.play_video1.setVisibility(View.VISIBLE);
} else{
holder.play_video.setVisibility(View.GONE);
holder.play_video1.setVisibility(View.GONE);
}
} else{
holder.play_video.setVisibility(View.GONE);
holder.play_video1.setVisibility(View.GONE);
}
holder.play_video.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final BottomSheetDialog dialog3 = new BottomSheetDialog(mContext);
dialog3.setContentView(R.layout.bottom_videoplay);
if(!dialog3.isShowing()) {
dialog3.show();
}
dialog3.setCancelable(true);
final WebView web_view = (WebView) dialog3.findViewById(R.id.youtube_web_view);
final ProgressBar progressBar2 = (ProgressBar) dialog3.findViewById(R.id.progressBar2);
final TextView tvTitle2 = (TextView) dialog3.findViewById(R.id.tvTitle2);
final TextView tvEnroll = (TextView) dialog3.findViewById(R.id.tvEnroll);
tvTitle2.setText(currentCourse.getTitle());
tvEnroll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switchToCourseDetailsActivity(currentCourse);
}
});
//String myVideoYoutubeId = &quot;Wwy9aibAd54&quot;;
String myVideoYoutubeId;
WebSettings webSettings = web_view.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
myVideoYoutubeId=matcher.group();
web_view.loadUrl(&quot;https://www.youtube.com/embed/&quot; + myVideoYoutubeId);
web_view.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
web_view.setWebViewClient(new WebViewClient() {
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar2.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar2.setVisibility(View.GONE);
//to enable autoplay ref:https://stackoverflow.com/questions/28039209/android-webview-youtube-embed-video-autoplay-not-working/45655979#45655979
long delta = 100;
long downTime = SystemClock.uptimeMillis();
float x = view.getLeft() + (view.getWidth()/2);
float y = view.getTop() + (view.getHeight()/2);
MotionEvent tapDownEvent = MotionEvent.obtain(downTime, downTime + delta, MotionEvent.ACTION_DOWN, x, y, 0);
tapDownEvent.setSource(InputDevice.SOURCE_CLASS_POINTER);
MotionEvent tapUpEvent = MotionEvent.obtain(downTime, downTime + delta + 2, MotionEvent.ACTION_UP, x, y, 0);
tapUpEvent.setSource(InputDevice.SOURCE_CLASS_POINTER);
view.dispatchTouchEvent(tapDownEvent);
view.dispatchTouchEvent(tapUpEvent);
}
});
}
});
holder.play_video1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
holder.play_video.performClick();
}
});
if(currentCourse.getIs_mentor()!=null &amp;&amp; currentCourse.getIs_mentor().equals(&quot;1&quot;)){
holder.instructorName.setVisibility(View.VISIBLE);
holder.tvMentor.setVisibility(View.GONE);
if(currentCourse.getBiography()!=null) {
holder.instructorName.setText(&quot;by &quot; + currentCourse.getInstructor() + &quot; &quot; + currentCourse.getBiography());
}else{
holder.instructorName.setText(&quot;by &quot; + currentCourse.getInstructor());
}
} else{
//holder.tvMentor.setVisibility(View.GONE);
holder.instructorName.setVisibility(View.GONE);
holder.tvMentor.setVisibility(View.VISIBLE);
if(currentCourse.getBiography()!=null) {
holder.tvMentor.setText(&quot;by &quot; + currentCourse.getInstructor() + &quot; &quot; + currentCourse.getBiography());
} else{
holder.tvMentor.setText(&quot;by &quot; + currentCourse.getInstructor());
}
}
if(currentCourse.getMain_price()!=null &amp;&amp; !currentCourse.getPrice().equals(&quot;Free&quot;)){
String  c_price = currentCourse.getPrice().substring(0, currentCourse.getPrice().length() - 1);
Double main_price=Double.parseDouble(currentCourse.getMain_price());
Double current_price=Double.parseDouble(c_price);
if(current_price&lt;main_price){
holder.tvcompare.setVisibility(View.VISIBLE);
holder.tvDiscountprice.setVisibility(View.VISIBLE);
holder.tvDiscountprice.setText(Double.toString(main_price)+&quot;Tk&quot;);
Double diff=main_price-current_price;
Double percent=diff*100/main_price;
holder.tvcompare.setText(percent+&quot;% OFF&quot;);
}else{
holder.tvDiscountprice.setVisibility(View.GONE);
holder.tvcompare.setVisibility(View.GONE);
}
} else{
holder.tvcompare.setVisibility(View.GONE);
holder.tvDiscountprice.setVisibility(View.GONE);
}
if(!currentCourse.getPrice().equals(&quot;Free&quot;)) {
String c_price = currentCourse.getPrice().substring(0, currentCourse.getPrice().length() - 1);
holder.coursePrice.setText(c_price + &quot;Tk&quot;);
} else{
holder.coursePrice.setText(currentCourse.getPrice());
}
if(currentCourse.getCourse_type()!=null){
if(currentCourse.getCourse_type().equals(&quot;Course&quot;)){
holder.tvCategory.setText(&quot;Lifetime Access&quot;);
holder.image.setVisibility(View.VISIBLE);
holder.play_video.setVisibility(View.VISIBLE);
holder.monthly_couching.setVisibility(View.GONE);
Glide.with(mContext)
.asBitmap()
.load(currentCourse.getThumbnail())
.into(holder.image);
}
if (currentCourse.getCourse_type().equals(&quot;MonthlyCouching&quot;)){
holder.tvCategory.setText(&quot;Monthly Couching&quot;);
holder.coursePrice.setText(holder.coursePrice.getText()+&quot;/month&quot;);
holder.image.setVisibility(View.GONE);
holder.play_video.setVisibility(View.GONE);
holder.monthly_couching.setVisibility(View.VISIBLE);
Picasso.get().load(currentCourse.getThumbnail()).into(holder.image);
Picasso.get().load(currentCourse.getThumbnail()).into(holder.image1);
if(currentCourse.getOnline_classschedule()!=null){
holder.layout_classschedule.setVisibility(View.VISIBLE);
holder.tvClass_schedule.setText(currentCourse.getOnline_classschedule());
} else{
holder.layout_classschedule.setVisibility(View.GONE);
}
}
if(currentCourse.getCourse_type().equals(&quot;FixedTermCouching&quot;)){
holder.image.setVisibility(View.GONE);
holder.play_video.setVisibility(View.GONE);
holder.monthly_couching.setVisibility(View.VISIBLE);
if(currentCourse.getDuration()!=null &amp;&amp; currentCourse.getStart_date()!=null){
long l = Long.parseLong(currentCourse.getStart_date());
Date date = new Date(l);
holder.tvCategory.setText(currentCourse.getDuration()+&quot; Couching starting on &quot;+date);
}
if(currentCourse.getOnline_classschedule()!=null){
holder.layout_classschedule.setVisibility(View.VISIBLE);
holder.tvClass_schedule.setText(currentCourse.getOnline_classschedule());
} else{
holder.layout_classschedule.setVisibility(View.GONE);
}
}
if(currentCourse.getCourse_type().equals(&quot;Workshop&quot;)){
holder.image.setVisibility(View.VISIBLE);
holder.play_video.setVisibility(View.VISIBLE);
holder.monthly_couching.setVisibility(View.GONE);
if(currentCourse.getDuration()!=null &amp;&amp; currentCourse.getStart_date()!=null){
long l = Long.parseLong(currentCourse.getStart_date());
Date date = new Date(l);
holder.tvCategory.setText(currentCourse.getDuration()+&quot; workshop starting on &quot;+date);
}
}
}
if(currentCourse.getWeekly_class()!=null &amp;&amp; currentCourse.getWeekly_class().equals(&quot;1&quot;)){
holder.tvweekly_class.setVisibility(View.VISIBLE);
if(currentCourse.getWeeklyonline_class()!=null &amp;&amp; Integer.parseInt(currentCourse.getWeeklyonline_class())&gt;0){
holder.tvweekly_class.setText(holder.tvweekly_class.getText()+&quot; &quot;+currentCourse.getWeeklyonline_class());
}
} else{holder.tvweekly_class.setVisibility(View.GONE);}
if(currentCourse.getWeekly_exam()!=null &amp;&amp; currentCourse.getWeekly_exam().equals(&quot;1&quot;)){
holder.tvweekly_exam.setVisibility(View.VISIBLE);
if(currentCourse.getWeeklyonline_test()!=null &amp;&amp; Integer.parseInt(currentCourse.getWeeklyonline_test())&gt;0){
holder.tvweekly_exam.setText(holder.tvweekly_exam.getText()+&quot; &quot;+currentCourse.getWeeklyonline_test());
}
} else{holder.tvweekly_exam.setVisibility(View.GONE);}
if(currentCourse.getReview_class()!=null &amp;&amp; currentCourse.getReview_class().equals(&quot;1&quot;)){
holder.tvreview_class.setVisibility(View.VISIBLE);
} else{holder.tvreview_class.setVisibility(View.GONE);}
if(currentCourse.getCourse_upload()!=null &amp;&amp; currentCourse.getCourse_upload().equals(&quot;1&quot;)){
holder.tvcourse_upload.setVisibility(View.VISIBLE);
} else{holder.tvcourse_upload.setVisibility(View.GONE);}
if(currentCourse.getRecord_upload()!=null &amp;&amp; currentCourse.getRecord_upload().equals(&quot;1&quot;)){
holder.tvrecord_upload.setVisibility(View.VISIBLE);
} else{holder.tvrecord_upload.setVisibility(View.GONE);}
if(currentCourse.getCourse_type()!=null &amp;&amp; currentCourse.getCourse_type().equals(&quot;FixedTermCouching&quot;) &amp;&amp; currentCourse.getLifetime_access()!=null &amp;&amp; currentCourse.getLifetime_access().equals(&quot;1&quot;)){
holder.tvlifetime_access.setVisibility(View.VISIBLE);
} else{holder.tvlifetime_access.setVisibility(View.GONE);}
}
@Override
public int getItemCount() {
return mCourses.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView image,image1,play_video,play_video1;
TextView name;
TextView coursePrice;
TextView instructorName;
TextView rating;
TextView totalNumberOfRating;
RatingBar starRating;
TextView tvweekly_class,tvweekly_exam,tvreview_class,tvcourse_upload,tvrecord_upload,tvlifetime_access,tvCategory,tvDiscountprice,tvMentor,tvcompare,tvBestseller,tvClass_schedule;
RelativeLayout monthly_couching;
LinearLayout layout_classschedule;
public ViewHolder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.courseThumbnail);
image1 = itemView.findViewById(R.id.courseThumbnail1);
name = itemView.findViewById(R.id.courseTitle);
coursePrice = itemView.findViewById(R.id.tvcoursePrice);
instructorName = itemView.findViewById(R.id.instructorName);
rating = itemView.findViewById(R.id.numericRating);
totalNumberOfRating = itemView.findViewById(R.id.totalNumberOfRatingByUsers);
starRating = itemView.findViewById(R.id.starRating);
tvweekly_class=itemView.findViewById(R.id.tvweekly_class);
tvweekly_exam=itemView.findViewById(R.id.tvweekly_exam);
tvreview_class=itemView.findViewById(R.id.tvreview_class);
tvcourse_upload=itemView.findViewById(R.id.tvcourse_upload);
tvrecord_upload=itemView.findViewById(R.id.tvrecord_upload);
tvlifetime_access=itemView.findViewById(R.id.tvlifetime_access);
tvCategory=itemView.findViewById(R.id.tvCategory);
tvDiscountprice=itemView.findViewById(R.id.tvDiscountprice);
tvMentor=itemView.findViewById(R.id.tvMentor);
play_video=itemView.findViewById(R.id.play_video);
play_video1=itemView.findViewById(R.id.play_video1);
tvcompare=itemView.findViewById(R.id.tvcompare);
tvBestseller=itemView.findViewById(R.id.tvBestseller);
monthly_couching=itemView.findViewById(R.id.monthly_couching);
tvClass_schedule=itemView.findViewById(R.id.tvClass_schedule);
layout_classschedule=itemView.findViewById(R.id.layout_classschedule);
}
}
}

答案1

得分: 1

RecyclerView 会重用视图持有者以提高性能。你也可以说它回收(recycles) 视图持有者 - 这就是它名字的由来。

RecyclerView 适配器不会创建比所需更多的视图持有者。视图持有者的数量大致可以等于:

// 将其视为伪代码
viewHoldersCount = recyclerView.height / viewHolder.height + 1

因此,它将生成填充屏幕的视图持有者数量 + 1,多出的一个项目会绘制在屏幕外(例如在回收视图底部),以平滑滚动动画并消除任何故障。

在此之后:onCreateViewHolder 仅用于创建视图持有者!绝不要在 onCreateViewHolder 中将任何数据绑定到视图持有者。

如果您的适配器中有 100 个要显示的项,但设备屏幕只能显示 10 个,那么在滚动列表时将重用 11 个视图持有者。

每当要显示项时,将调用 onBindViewHolder - 这是将数据附加到视图持有者的地方。

public CoursesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell2, parent, false);
    return new ViewHolder(view);
}

public void onBindViewHolder(@NonNull final CoursesAdapter.ViewHolder holder, final int position) {
    final Course currentCourse = mCourses.get(position);

    holder.play_video.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
           // ...
        }
    }

    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switchToCourseDetailsActivity(currentCourse);
        }
    });
}
英文:

RecyclerView reuses view holders to improve performance. You can also say it recycles view holders - this is where it gets its name from.

RecyclerView adapter will not create more view holders than it requires. The number of view holders can be roughly equal to:

// consider it pseudocode
viewHoldersCount = recyclerView.height / viewHolder.height + 1

So it will generate the number of view holders that fill the screen + 1 more item that is drawn off-screen (e.g. at the bottom of the recycler view) to smooth out scrolling animation and remove any glitches.

Following that: onCreateViewHolder is used only to create a view holder!
Do not ever bind any data to a view holder from onCreateViewHolder.

If you have 100 of items in your adapter that you want to display but the screen of a device can display only 10 you will have 11 view holders that are reused when you scroll the list.

onBindViewHolder is called every time an item is going to be displayed - this is the place to attach data to your view holders.

public CoursesAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell2, parent, false);
return new ViewHolder(view);
}
public void onBindViewHolder(@NonNull final CoursesAdapter.ViewHolder holder, final int position) {
final Course currentCourse = mCourses.get(position);
holder.play_video.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ...
}
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
switchToCourseDetailsActivity(currentCourse);
}
});
}

答案2

得分: 0

最后我找到了一个解决方案。我的RecyclerView布局中有一个嵌套的滚动视图(NestedScrollView),
在我的RecyclerView中添加android:nestedScrollingEnabled="false"解决了我的问题。我不知道为什么,但它解决了我的问题。

英文:

At last I found a solution. My recyclerview layout has a nestedscrollview
adding android:nestedScrollingEnabled=&quot;false&quot; to my recyclerview solved my problem. I don't know why but it solved my problem

huangapple
  • 本文由 发表于 2020年9月4日 19:45:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63740549.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定