在Recycler View行之间添加布局?

时间:2018-01-18 07:12:04

标签: android android-layout android-recyclerview

我想要实现的是,如果我能在回收者视图项目中检测到一个字符串,我会在它之后以及在显示下一个回收者视图项目之前对其进行充气。

3 个答案:

答案 0 :(得分:1)

您可以使用int getItemViewType(int);类的RecyclerView.Adapter<>覆盖方法。

@Override
public int getItemViewType(int position){
    if (data.get(position).contains("Your string"))
        return 007; // any random integer you can use
    return super.getItemViewType(position);
}

在onCreateViewHolder方法中

@Override
public void onCreateViewHolder(ViewGroup parent, int viewType){
    if (viewType == 007){ // the view type you returned
        return #special_view // inflate your other layout here which you want to inflate if it contains your special string.
    else 
        return #normal_view;// inflate the normal view here and return
    }
}

答案 1 :(得分:1)

例如,就像你有CustomObject类一样。使用布尔值(isCustomView)添加自定义布局。

public class YourObject {
String customString ="";
boolean isCustomView=false;

public String getCustomString() {
    return customString;
}

public void setCustomString(String customString) {
    this.customString = customString;
}

public boolean isCustomView() {
    return isCustomView;
}

public void setCustomView(boolean customView) {
    isCustomView = customView;
}

}

在向Adapter发送数据之前,请对数据进行更改

 ArrayList<YourObject> yourObjectArrayList = new ArrayList<>();

    // Assume You have yourObjectArrayList with data filled

    // Take temp object 
    YourObject object = new YourObject();
    object.setCustomView(true);

    for (int i = 0; i < yourObjectArrayList.size(); i++) {
        if(yourObjectArrayList.get(i).getCustomString().equals("YOUR CUSTOM STRING")){

            // Adding a custom object before That Position
            if (i==0)
                yourObjectArrayList.add(0,object);
            else
                yourObjectArrayList.add(i-1,object);

            // Adding a custom object After That Position. Note here i+2 is a must
            yourObjectArrayList.add(i+2,object);
        }
    }
    // Add data to RecyclerView adapter & notify

在回收器适配器中覆盖getItemViewType()

@Override
public int getItemViewType(int position) {
    return (yourObjectArrayList.get(position).isCustomView()) ? R.layout.your_custom_layout : R.layout.your_raw_layout;
}

进行以下更改以覆盖方法onCreateViewHolder

 @Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView;


    if(viewType == R.layout.your_custom_layout){
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_custom_layout, parent, false);
    }
    else {
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.your_raw_layout, parent, false);
    }

    return new ViewHolder(itemView);

}

答案 2 :(得分:0)

holder.dynamicLinearLayout.removeAllViews()
View view = LayoutInflater.from(context).inflate(R.layout.new_layout,null);
holder.dynamicLinearLayout.addView(view);

在onBind上试试