Android Studio 在RecycleView适配器中获取空错误消息TextSwitcher

k5ifujac  于 2022-12-13  发布在  Android
关注(0)|答案(1)|浏览(98)

**我尝试在recyclerView中实现TextSwitcher,但每次调试时都返回错误消息:java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.ViewGroup$LayoutParams android.view.View.getLayoutParams()' on a null object reference这是我的代码XML

<TextSwitcher
        android:id="@+id/textSwitcher_card"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:textAlignment="textStart"
            android:lineSpacingExtra="5dp"
            android:textColor="@color/white"
            android:textSize="@dimen/appbar_padding"
            android:layout_gravity="start"
            android:text=""/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:textAlignment="textStart"
            android:lineSpacingExtra="5dp"
            android:textColor="@color/white"
            android:textSize="@dimen/appbar_padding"
            android:layout_gravity="start"
           />
    </TextSwitcher>

下面是我的Java代码:来自RecyclerView适配器的onBindViewHolder

@Override
        protected void onBindViewHolder(@NonNull ViewHolderCard holder, int position, @NonNull ModelBet model) {
   TextSwitcher textSwitcher=holder.getTextSwitcher();

    //textSwitcher.setText(TEXT[mPosition]);
    textSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
        @Override
        public View makeView() {
            TextView textView=new TextView(context);
            textView.setTextColor(context.getResources().getColor(R.color.white));
            textView.setTextSize(16);
            return null;
        }
    });
        }

这里是我的ViewHolder

public class ViewHolderCard  extends RecyclerView.ViewHolder {

...
public TextSwitcher textSwitcher;

public ViewHolderCard(@NonNull View itemView) {
    super(itemView);
    view=itemView;
  ...
    textSwitcher=(TextSwitcher)view.findViewById(R.id.textSwitcher_card);
}

@NonNull
public TextSwitcher getTextSwitcher() {
    return textSwitcher;
}

虽然我已经初始化了我的TextSwitcher,但我真的不知道问题出在哪里

ijxebb2r

ijxebb2r1#

我找到了一个解决方案。如果它能帮助别人,我已经动态地实现了文本切换器,它工作正常

相关问题