GridLayoutManager每行的背景相同

时间:2016-11-10 09:51:34

标签: android android-recyclerview grid-layout gridlayoutmanager

我一直在link尝试这个项目。一切都很好。我也得到了输出。我想加强它,但我不知道该怎么做。我有一个背景,我需要在recyclerview中将它作为gridlayoutmanager的每一行的背景。 请帮帮我。并提前致谢

MainActivity.java
public class MainActivity extends AppCompatActivity {

RecyclerView recyclerView;

Context context;

RecyclerView.Adapter recyclerView_Adapter;

RecyclerView.LayoutManager recyclerViewLayoutManager;

String[] numbers = {
        "one",
        "two",
        "three",
        "four",
        "five",
        "six",
        "seven",
        "eight",
        "nine",
        "ten",
        "eleven",

};


@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    context = getApplicationContext();

    recyclerView = (RecyclerView) findViewById(R.id.recycler_view1);


    recyclerViewLayoutManager = new GridLayoutManager(context, 2);

    recyclerView.setLayoutManager(recyclerViewLayoutManager);

    recyclerView_Adapter = new RecyclerViewAdapter(context,numbers);

    recyclerView.setAdapter(recyclerView_Adapter);

}
}

RecyclerViewAdapter.java
public class RecyclerViewAdapter extends RecyclerView.
Adapter<RecyclerViewAdapter.ViewHolder>{

String[] values;
Context context1;

public RecyclerViewAdapter(Context context2,String[] values2){

    values = values2;

    context1 = context2;
}

public static class ViewHolder extends RecyclerView.ViewHolder{

    public TextView textView;

    public ViewHolder(View v){

        super(v);

        textView = (TextView) v.findViewById(R.id.textview1);

    }
}

@Override
public RecyclerViewAdapter.ViewHolder 
onCreateViewHolder(ViewGroup parent, int viewType){

    View view1 = LayoutInflater.from(context1).inflate
 (R.layout.recycler_view_items,parent,false);

    ViewHolder viewHolder1 = new ViewHolder(view1);

    return viewHolder1;
}

@Override
public void onBindViewHolder(ViewHolder Vholder, int position){

    Vholder.textView.setText(values[position]);

    Vholder.textView.setBackgroundColor(Color.CYAN);

    Vholder.textView.setTextColor(Color.BLUE);

}

@Override
public int getItemCount(){

    return values.length;
}
}

1 个答案:

答案 0 :(得分:0)

简易黑客: 你可以使用LinearLayout管理器而不是gridLayoutManager。 然后你可以改变项目布局(adpater中每个项目的布局,即:recycler_view_items)到

类似这样的事情

<LinearLayout
 background: set it as ur image>
   <LinearLayout>
    // first item 
   </LinearLayout>

   <LinearLayout>
     //2nd item
   </LinearLayout>

<LinearLayout>

并更改适配器以相应地设置值。 它需要更改布局和适配器代码。 这适用于你,因为你可以为每一行设置背景

(PS:每行现在被视为单个项目)