如何在recyclerView中显示和隐藏imageview

时间:2019-04-01 10:33:10

标签: android android-recyclerview recycler-adapter

我正在使用for循环,并且在回收器视图中显示大约20个项目!现在,我如何在循环运行时隐藏/显示图像视图...在这里tts工作正常,但是当我尝试使用此按钮显示/隐藏时没有发生..

目前使用以下代码,一旦for循环结束,整个imageview都会受到影响,我希望它连续显示(显示current(image1)并隐藏先前的imageview(image))

我正在从Activity主类调用此方法,但是imageview不会显示或隐藏

活动

 ......
 ...... 
private void ConvertTextToSpeech() {
    // TODO Auto-generated method stub
   //items.forEach( Multiples obj ->  System.out.println());
    int z=0;
    View holder=null; ImageView imageView=null;ImageView imageView1=null;
    for (Multiples p : items) {

        if(z>0){

            holder = recyclerView.findViewHolderForAdapterPosition(z).itemView;
            holder.findViewById(R.id.image).setVisibility(View.VISIBLE);
            holder.findViewById(R.id.image1).setVisibility(View.INVISIBLE);
        }
        if(z < items.size()) {
              holder = recyclerView.findViewHolderForAdapterPosition(z).itemView;
              holder.findViewById(R.id.image).setVisibility(View.INVISIBLE);
            holder.findViewById(R.id.image1).setVisibility(View.VISIBLE);

        }
        text = p.first + "  " + p.getSecond() + " Za "+p.getResult()+".";
        tts.speak(text, TextToSpeech.QUEUE_ADD, null);
    z++;
    }

}

xml

  <?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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


    <com.balysv.materialripple.MaterialRippleLayout
        android:id="@+id/lyt_parent"
        style="@style/RippleStyleBlack"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:focusable="true">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <View
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:background="@color/grey_10" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_weight="1"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:textAlignment="gravity" >

                <View
                    android:layout_width="@dimen/spacing_large"
                    android:layout_height="wrap_content" />

                <ImageView
                    android:id="@+id/image"
                    android:layout_width="35dp"
                    android:layout_height="35dp"
                    android:background="@android:color/transparent"
                    android:src="@drawable/ic_arrow_right" />

                <ImageView
                    android:id="@+id/image1"
                    android:layout_width="51dp"
                    android:layout_height="35dp"
                    android:background="@android:color/transparent"
                    android:src="@drawable/ic_arrow_right"
                    android:visibility="invisible" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingBottom="@dimen/spacing_middle"
                    android:paddingTop="@dimen/spacing_middle">

                    <TextView
                        android:id="@+id/name"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginEnd="@dimen/spacing_middle"
                        android:layout_marginRight="@dimen/spacing_middle"
                        android:fontFamily="sans-serif-condensed"
                        android:gravity="center|left"
                        android:text="36"
                        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                        android:textColor="@color/grey_80"
                        android:textSize="30sp"

                        />



                </LinearLayout>





                <View
                    android:layout_width="@dimen/spacing_large"
                    android:layout_height="match_parent" />


            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1px"
                android:background="@color/grey_10" />

        </LinearLayout>

    </com.balysv.materialripple.MaterialRippleLayout>

</RelativeLayout>

适配器

public class AdapterListAnimation extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<Multiples> items = new ArrayList<>();

    private Context ctx;
    private OnItemClickListener mOnItemClickListener;
    private int animation_type = 0;
    .........
    ......... 

4 个答案:

答案 0 :(得分:0)

您不应使用以下命令直接更改适配器内部的项目视图状态:

holder = recyclerView.findViewHolderForAdapterPosition(z).itemView;
holder.findViewById(R.id.image).setVisibility(View.VISIBLE);
holder.findViewById(R.id.image1).setVisibility(View.INVISIBLE);

相反,您需要使用特定的方法来告知RecyclerView适配器您需要更改项目视图的状态。

请注意,RecylerView自然(以编程方式)将在需要绘制其他项目时重新对其前一个项目进行修改。因此,您需要保留每个项目的状态,无论是在模型内部使用特定变量还是使用变量来保存每个项目的状态。

如果您不想更改模型,可以使用SparseBooleanArray保持状态。您可以在适配器中执行以下操作:

public class YourAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private List<Multiples> mItems;

    // We use this to hold the image state.
    private SparseBooleanArray mImageStates;

    public YourAdapter(List<Multiples> items) {
      this.mItems = items;
      mImageStates = new SparseBooleanArray();

      ...
    }

    @Override
    public YourAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
       ...
       return viewHolder;
    }


    @Override
    public void onBindViewHolder(ContactsAdapter.ViewHolder viewHolder, int position) {

      int itemPosition = viewHolder.getAdapterPosition();
      Multiples item = mItems.get(itemPosition);

      // Load the state by the previous saved state
      // default value is false.
      if(mImageStates.get(itemPosition)) {
        // show the images or something.
      } else {
        // hide the images or something.
      }

    }

    public void setState(int position, boolean isVisible) {
      mImageStates.put(position, isVisible);

    }

}

现在您可以使用以下方式更改状态项的可见性:

yourAdapter.setState(yourItemPosition, true);

然后通过以下方式通知适配器有关更改:

yourAdapter.notifyItemChanged(yourItemPosition);

或如果您通过以下方式更改了许多项目,则重设所有内容:

yourAdapter.notifyDataSetChanged();

答案 1 :(得分:-1)

然后您必须在onbindholder上编写逻辑。

onBindHolder(ViewHolder holder, int position){
 if(position %2==0)
  imageview.setVisibility(View.Visible);
 else 
  imageview.setVisibility(View.InVisible);
}

答案 2 :(得分:-2)

最终获得了解决方案

我在您的倍数中添加了两个参数。在条件为true的循环中,我将根据您对Image视图所做的设置来设置变量。在通知RecyclerView之后。因此,将在onBindViewHolder上进行回调。在那里,我添加了显示/隐藏图像视图的条件。

假定左箭头为image和右箭头为image1

注意::Android默认TextToSpeech不提供任何事件监听器来完成操作。因此,我尝试了一个维护良好并提供Speech recognitionText to speech功能的新库。

成绩:

implementation 'net.gotev:speech:1.4.0'

初始化:

要开始使用该库,必须在“活动”中对其进行初始化。

public class YourActivity extends Activity {

private count = 0;
private maxCount = 0;

    Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        Speech.init(this, getPackageName());
        maxCount = items.size();

    }

    @Override
    protected void onDestroy() {
        // prevent memory leaks when activity is destroyed
        Speech.getInstance().shutdown();
    }
}

public class Multiples implements Serializable {

        private Boolean isShowimage = false;
        private Boolean isShowimage1 = false;

        public Boolean getShowimage() {
            return isShowimage;
        }

        public void setShowimage(Boolean showimage) {
            isShowimage = showimage;
        }

        public Boolean getShowimage1() {
            return isShowimage1;
        }

        public void setShowimage1(Boolean showimage1) {
            isShowimage1 = showimage1;
        }
    }

private void ConvertTextToSpeech() {

    if (count < maxCount) {

        reset();
        String text = items.get(count).first + "  " + items.get(count).getSecond() + " Za " + items.get(count).getResult() + ".";

        Speech.getInstance().say(text, new TextToSpeechCallback() {
            @Override
            public void onStart() {
                Log.i("speech", "speech started");
                items.get(count).setShowimage(false);
                items.get(count).setShowimage1(true);

                adapter.notifyDataSetChanged();
            }

            @Override
            public void onCompleted() {
                Log.i("speech", "speech completed");
                ConvertTextToSpeech();
                count++;
            }

            @Override
            public void onError() {
                Log.i("speech", "speech error");
            }
        });
    }
}

private void reset() {
    for (Multiples p : items) {
        p.setShowimage(true);
        p.setShowimage1(false);
    }
}
@Override
    public void onBindViewHolder(ViewHolder holder, int position) {

        final Multiples item = items.get(position);

        if (item.getShowimage()) {
            holder.image.setVisibility(View.VISIBLE);
        } else {
            holder.image.setVisibility(View.INVISIBLE);
        }

        if (item.getShowimage1()) {
            holder.image1.setVisibility(View.VISIBLE);
        } else {
            holder.image1.setVisibility(View.INVISIBLE);
        }

    }

public static class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView imageView,imageView1;

        public ViewHolder(View view) {
            super(view);
            this.imageView = (ImageView) view.findViewById(R.id.imageView);
            this.imageView1 = (ImageView) view.findViewById(R.id.imageView1);

        }
    }

答案 3 :(得分:-2)

您只需要在适配器中添加字段即可保存当前活动的项目。然后致电notifyDataSetChanged。 另外,您应该像这样更新onBindViewHolder

private int currentPosition = -1;

@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
    holder.textView.setText(items.get(position));
    if (currentPosition == position) {
        holder.img1.setVisibility(View.INVISIBLE);
        holder.img2.setVisibility(View.VISIBLE);
    } else {
        holder.img1.setVisibility(View.VISIBLE);
        holder.img2.setVisibility(View.INVISIBLE);
    }
}

public void setCurrentPosition(int currentPosition) {
    this.currentPosition = currentPosition;
}

我已经创建了一个测试项目来展示如何实现它。 Here,您会看到它是如何工作的。 Here是我的github存储库。