-1

Я пытаюсь нажать на кнопку, которая была объявлена ​​в adapterview я загрузки recyclerview внутри деятельности когда я выполнить щелчок и пытается получить значение из метода mRecyclerView.getChildLayoutPosition его дает мне ClassCastException

вот мой код активности

import android.content.Intent; 
import android.database.Cursor; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.NavigationView; 
import android.support.v4.view.GravityCompat; 
import android.support.v4.widget.DrawerLayout; 
import android.support.v7.app.ActionBarDrawerToggle; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.LinearLayoutManager; 
import android.support.v7.widget.RecyclerView; 
import android.support.v7.widget.Toolbar; 
import android.util.Log; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.TextView; 

import java.util.ArrayList; 
protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_location_reminder_list); 
     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 
     dbAdapter=new LocationReminderDBAdapter(getApplicationContext()); 
     dbAdapter.open(); 
     ///////////////////////////////////////////////////////////////////////////////////// 
     mRecyclerView = (RecyclerView)findViewById(R.id.reminders_recycler); 

     int[] locationImage = new int[5]; 
     for (int i = 0; i < locationImage.length; i++) { 
      locationImage[i] = i; 
     } 
     reminderNames = new ArrayList<String>(); 
     reminderLocations = new ArrayList<String>(); 
     imagePaths=new ArrayList<String>(); 
     mLayoutManager = new LinearLayoutManager(getApplicationContext()); 
     mRecyclerView.setLayoutManager(mLayoutManager); 
     adapter = new SavedReminderAdapter(reminderNames, reminderLocations, imagePaths); 
     mRecyclerView.setAdapter(adapter); 
     populateReminderList(); 

     adapter.setListener(new SavedReminderAdapter.Listener() { 
      @Override 
      public void onClick(int position) { 
       Intent intent=new Intent(getApplicationContext(),ViewAddedReminder.class); 
       startActivity(intent); 
      } 


     }); 
     ////////////////////////////////////////////////////////////////////////////////////// 
     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View view) { 
       Intent intent=new Intent(LocationReminderList.this,AddLocationReminder.class); 
       startActivity(intent); 
       /* Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
         .setAction("Action", null).show();*/ 
      } 
     }); 


    } 

здесь он дает ошибку ClassCastException

public void editReminder(View view){ 
     int itemPosition = mRecyclerView.getChildLayoutPosition(view); 

    } 

и вот мой макет код деятельности

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout 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:id="@+id/content_location_reminder_list" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingBottom="2dp" 
    android:paddingLeft="0.5dp" 
    android:paddingRight="0.5dp" 
    android:paddingTop="2dp" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:context="reminder.locrem.com.locationreminder.LocationReminderList" 
    tools:showIn="@layout/app_bar_location_reminder_list"> 


    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentTop="true" 
     android:layout_alignParentStart="true" 
     android:layout_marginStart="118dp" 
     android:layout_marginTop="87dp" 
     android:id="@+id/tempshow" /> 

    <include 
     layout="@layout/recycler_view_list" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     /> 


</RelativeLayout> 

и вот мой макет код зрения ресайклера (recycler_view_list)

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" android:layout_height="match_parent" 
    android:id="@+id/reminders_recycler" 
    android:scrollbars="vertical"> 

</android.support.v7.widget.RecyclerView> 

и, наконец, вот мой макет код зрения адаптера

<?xml version="1.0" encoding="utf-8"?> 
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="200dp" 
    android:id="@+id/reminder_card_view" 
    android:layout_margin="5dp" 
    xmlns:card_view="http://schemas.android.com/apk/res-auto" 
    card_view:cardCornerRadius="4dp" 
    card_view:cardElevation="4dp"> 
    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical" 
     > 
     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:paddingLeft="5dp" 
      android:textSize="18sp" 
      android:textAlignment="viewStart" 
      android:id="@+id/list_of_items_label" 
      android:textStyle="normal|bold" 
      android:text="Items List" /> 
     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:paddingLeft="5dp" 
      android:textSize="14sp" 
      android:textAlignment="viewStart" 
      android:id="@+id/list_of_items"/> 

     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:paddingLeft="5dp" 
      android:textSize="18sp" 
      android:textAlignment="viewStart" 
      android:id="@+id/location_label" 
      android:textStyle="normal|bold" 
      android:text="Location" /> 
     <TextView 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:paddingLeft="5dp" 
      android:textSize="14sp" 
      android:maxLines="1" 
      android:ellipsize="end" 
      android:textAlignment="viewStart" 
      android:id="@+id/location_value"/> 
     <ImageView 
      android:layout_width="match_parent" 
      android:layout_height="0dp" 
      android:id="@+id/info_image" 
      android:layout_weight="0.47" 
      android:scaleType="centerCrop" 
      /> 
     <RelativeLayout 
      android:layout_width="match_parent" 
      android:layout_height="32dp"> 
     <ImageButton 
      android:id="@+id/reminder_alarm" 
      android:background="@android:drawable/ic_lock_idle_alarm" 
      android:layout_width="31dp" 
      android:layout_height="31dp" 
      android:onClick="setAlarm"/> 
     <ImageButton 
      android:layout_width="31dp" 
      android:layout_height="31dp" 
      android:id="@+id/markCompleted" 
      android:layout_centerHorizontal="true" 
      android:background="@drawable/done" 
      android:backgroundTint="@color/common_google_signin_btn_text_light_default" 
      android:onClick="settaskCompleted"/> 
     <ImageButton 
      android:id="@+id/edit_reminder" 
      android:layout_alignParentRight="true" 
      android:background="@android:drawable/ic_menu_edit" 
      android:layout_width="31dp" 
      android:layout_height="31dp" 
      android:onClick="editReminder"/> 
     </RelativeLayout> 

    </LinearLayout> 
</android.support.v7.widget.CardView> 

build.gradle файл

compile fileTree(include: ['*.jar'], dir: 'libs') 
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 
     exclude group: 'com.android.support', module: 'support-annotations' 
    }) 
    compile 'com.android.support:appcompat-v7:24.2.1' 
    compile 'com.android.support:design:24.2.1' 
    testCompile 'junit:junit:4.12' 
    compile 'com.google.android.gms:play-services-maps:9.2.0' 
    compile 'com.google.android.gms:play-services:9.2.0' 
    compile 'com.google.android.gms:play-services-ads:9.2.0' 
    compile 'com.google.android.gms:play-services-auth:9.2.0' 
    compile 'com.google.android.gms:play-services-gcm:9.2.0' 
    compile 'com.android.support:cardview-v7:24.2.1' 

Пожалуйста, помогите мне в этом заранее спасибо

+0

может у добавить оператор импорта слишком –

+0

я обновил с импортным заявлением и файлом build.gradle а – sasikanth

ответ

-1

Проблема на самом деле в том же методе вы указываете

public void editReminder(View view){ 
     int itemPosition = mRecyclerView.getChildLayoutPosition(view); 
} 

getChildLayoutPosition внутренний вызов ниже метода

static ViewHolder getChildViewHolderInt(View child) { 
     if (child == null) { 
      return null; 
     } 
     return ((LayoutParams) child.getLayoutParams()).mViewHolder; 
} 

Как вы можете видеть выше, он пытается бросить LayoutParams к RecyclerView.LayoutParams и ваш взгляд class - RelativeLayout, тем самым бросая исключение класса.

Теперь давайте поговорим о решении

Я предпочел бы предложить вам простой способ получить идентификатор точки зрения, установив его в теге.

В onBindViewHolder наборе ID

@Override 
public void onBindViewHolder(ViewHolder customViewHolder, int i) { 
    // do your stuff 
    viewHolder.itemView.setTag(<SET_YOUR_ID>); 
} 

И чтобы получить его обратно

public void editReminder(View view){ 
    int itemPosition = (int)view.getTag(); 
} 
+0

любая конкретная причина для downvotes, будет любить улучшать мой ответ, если получить обратную связь :) –

+0

после применения вашего решения я получаю нулевой указатель другого типа, кроме ion – sasikanth

+0

Вот мой код – sasikanth

-1

Какой версии библиотеки поддержки вы используете? В библиотеке поддержки v24.2.0 или старше обнаружена ошибка, которая вызывает эту проблему. Попробуйте обновиться до более новой версии и посмотрите, помогает ли это. Версия 24.2.1 работала для меня.

+0

я обновленное build.gradle файл все еще не работает – sasikanth

Смежные вопросы