Aquí tienes un ejemplo con un RecyclerView
con un GridLayoutManager
.
La Activity
principal.
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_grid_view_sof);
GridAdapter ga = new GridAdapter();
RecyclerView rvGrid = findViewById(R.id.rv_grid);
rvGrid.setAdapter(ga);
Button btAzul = findViewById(R.id.bt_azul);
Button btRojo = findViewById(R.id.bt_rojo);
btAzul.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ga.putImageResource(R.drawable.image1);
}
});
btRojo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ga.putImageResource(R.drawable.image2);
}
});
}
Xml
de la Acitivty
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_grid"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layoutManager="android.support.v7.widget.GridLayoutManager"
app:spanCount="8"
tools:listitem="@layout/item_grid_sof"
android:layout_weight="1" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="@+id/bt_azul"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Azul" />
<Button
android:id="@+id/bt_rojo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rojo" />
</LinearLayout>
</LinearLayout>
Adapter
del RecyclerView
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.Holder> {
private final List<Integer> listImages = new ArrayList<>(0);
public void putImageResource(Integer res) {
listImages.add(res);
notifyItemInserted(listImages.size() - 1);
}
@NonNull
@Override
public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new Holder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_grid_sof, parent, false));
}
@Override
public int getItemCount() {
return listImages.size();
}
@Override
public void onBindViewHolder(@NonNull Holder holder, int position) {
holder.image.setBackgroundResource(listImages.get(position));
}
class Holder extends RecyclerView.ViewHolder {
ImageView image;
public Holder(View itemView) {
super(itemView);
image = itemView.findViewById(R.id.image);
}
}
}
Xml
item del adapter
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/image"
android:layout_width="70dp"
android:layout_height="15dp"/>