web-dev-qa-db-ja.com

CardViewを使用したRecyclerView 2列

レイアウトに問題があります。私はこのようなことをしようとしています:

Image

今のところ、CardViewを中に含むRecyclerViewがあります。 CardViewにImageViewとTextViewを配置しましたが、その理由はわかりませんが、CardViewはImageViewよりも高さが内部にあります。

コードとサンプル画像を次に示します。

Image

そして、ここにコードがあります:アクティビティ

public class AddRoomActivity extends AppCompatActivity implements View.OnClickListener {

private View snackView;
private FloatingActionButton fabDoneAddRoom;
private EditText etRoomName;
private String roomName = null;
public final static String KEY_PI_IP = "MyPi_IP";
private final static String KEY_ROOM = "myRoom";
private final static String KEY_ROOM_TYPE = "myRoom_Type";

private RecyclerView typeRecyclerView;
private GridLayoutManager layoutManager;
private AddRoomActivity.TypeAdapter adapter;


private String myPi;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_room);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    fabDoneAddRoom = (FloatingActionButton) findViewById(R.id.doneAddRoom);
    fabDoneAddRoom.setOnClickListener(this);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    etRoomName = (EditText) findViewById(R.id.addRoomName);
    myPi = getIntent().getStringExtra(KEY_PI_IP);

    layoutManager = new GridLayoutManager(this, 2);


    typeRecyclerView = (RecyclerView) findViewById(R.id.recyclerTypeRoom);
    typeRecyclerView.setHasFixedSize(true);

    typeRecyclerView.setLayoutManager(layoutManager);

    // specify an adapter (see also next example)
    adapter = new TypeAdapter(getResources().getStringArray(R.array.roomTypeName));
    typeRecyclerView.setAdapter(adapter);


}


void showToastMessage(String message) {
    Snackbar.make(snackView, message, Snackbar.LENGTH_LONG).show();
}

@Override
public void onClick(View v) {
    if (v.getId() == R.id.doneAddRoom) {
        snackView = v;
        String myString = etRoomName.getText().toString();

        if (myString.length() > 0) {
            roomName = myString.substring(0, 1).toUpperCase() + myString.substring(1);
            addRoomToPi();
        } else {
            showToastMessage(getString(R.string.noNameRoom));

        }
    }
}

private void addRoomToPi() {
    Integer ret = -1;
    try {
        ret = (Integer) new RaspberryTCPClient(myPi, getResources(), RaspberryTCPClient.TYPE_ADD_ROOM, roomName, XMLRoom.TYPE_KITCHEN_ROOM).execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }

    if (ret == RaspberryTCPClient.OPERATION_DONE) {

        showToastMessage(getString(R.string.roomAdded));

        Intent data = new Intent();
        data.putExtra(KEY_ROOM, roomName);
        setResult(Activity.RESULT_OK, data);

        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        }, 1500);
    } else {
        showToastMessage(getString(R.string.addRoomError));
    }

}


private class TypeAdapter extends RecyclerView.Adapter<AddRoomActivity.TypeAdapter.ViewHolder> {

    private String[] myData;


    public TypeAdapter(String[] roomList) {
        myData = roomList;
    }


    public void onItemClick(int position) {
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        // each data item is just a string in this case
        public TextView tvType;
        public CardView cvRoomCard;
        public ImageView imgRoomType;

        public ViewHolder(View vCard) {
            super(vCard);
            cvRoomCard = (CardView) vCard;
            tvType = (TextView) vCard.findViewById(R.id.tvTypeName);
            imgRoomType = (ImageView) vCard.findViewById(R.id.img_roomType);
        }
    }


    @Override
    public AddRoomActivity.TypeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.type_room_recycler_view, parent, false);
        // set the view's size, margins, paddings and layout parameters
        //...
        AddRoomActivity.TypeAdapter.ViewHolder vh = new AddRoomActivity.TypeAdapter.ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(AddRoomActivity.TypeAdapter.ViewHolder holder, int position) {
        // - get element from your dataset at this position
        // - replace the contents of the view with that element
        holder.tvType.setText(myData[position]);

        switch (position) {
            case XMLRoom.TYPE_ROOM:
                holder.imgRoomType.setImageResource(R.drawable.img_room_sqr);
                break;
            case XMLRoom.TYPE_BED_ROOM:
                holder.imgRoomType.setImageResource(R.drawable.img_bedroom_sqr);
                break;
            case XMLRoom.TYPE_GARDEN_ROOM:
                holder.imgRoomType.setImageResource(R.drawable.img_garden_sqr);
                break;
            case XMLRoom.TYPE_KITCHEN_ROOM:
                holder.imgRoomType.setImageResource(R.drawable.img_kitchen_sqr);
                break;
            case XMLRoom.TYPE_LIVING_ROOM:
                holder.imgRoomType.setImageResource(R.drawable.img_living_room_sqr);
                break;
            case XMLRoom.TYPE_SWIMMING_POOL_ROOM:
                holder.imgRoomType.setImageResource(R.drawable.img_swimming_pool_sqr);
                break;
        }

        holder.cvRoomCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onItemClick(position);
            }
        });


    }

    @Override
    public int getItemCount() {
        return myData.length;
    }


}

MainLayout

<Android.support.design.widget.AppBarLayout
    Android:id="@+id/appBar"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:theme="@style/AppTheme.AppBarOverlay">

    <Android.support.v7.widget.Toolbar
        Android:id="@+id/toolbar"
        Android:layout_width="match_parent"
        Android:layout_height="@dimen/toolbar"
        Android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</Android.support.design.widget.AppBarLayout>


<RelativeLayout
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    Android:layout_marginBottom="90dp"
    Android:layout_marginTop="@dimen/toolbar"
    Android:descendantFocusability="beforeDescendants"
    Android:focusableInTouchMode="true">


    <TextView
        Android:id="@+id/tvAddRoom"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:layout_alignParentTop="true"
        Android:layout_margin="5dp"
        Android:gravity="center"
        Android:text="@string/textAddRoom"
        Android:textColor="@color/primary_text"
        Android:textSize="20dp"
        Android:textStyle="bold" />

    <Android.support.design.widget.TextInputLayout
        Android:id="@+id/inputaddRoomName"
        Android:layout_width="match_parent"
        Android:layout_height="wrap_content"
        Android:layout_below="@id/tvAddRoom"
        Android:layout_gravity="center"
        Android:layout_margin="5dp">

        <EditText
            Android:id="@+id/addRoomName"
            Android:layout_width="match_parent"
            Android:layout_height="wrap_content"
            Android:hint="@string/Prompt_RoomName"
            Android:inputType="textEmailAddress"
            Android:maxLines="1"
            Android:singleLine="true" />

    </Android.support.design.widget.TextInputLayout>

    <Android.support.v7.widget.RecyclerView
        Android:id="@+id/recyclerTypeRoom"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        Android:layout_below="@id/inputaddRoomName"
        Android:scrollbars="vertical" />

</RelativeLayout>


<Android.support.design.widget.FloatingActionButton
    Android:id="@+id/doneAddRoom"
    Android:layout_width="@dimen/fab_Dimension"
    Android:layout_height="@dimen/fab_Dimension"
    Android:layout_gravity="bottom|center"
    Android:layout_margin="@dimen/fab_margin"
    app:srcCompat="@drawable/ic_done" />

</Android.support.design.widget.CoordinatorLayout>

およびビューレイアウト:

<Android.support.v7.widget.CardView xmlns:Android="http://schemas.Android.com/apk/res/Android"
xmlns:app="http://schemas.Android.com/apk/res-auto"
xmlns:card_view="http://schemas.Android.com/apk/res-auto"
Android:id="@+id/card_view"

Android:layout_width="match_parent"
Android:layout_height="wrap_content"

card_view:cardCornerRadius="4dp">


<ImageView
    Android:id="@+id/img_roomType"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:layout_alignParentTop="true"
    Android:src="@drawable/img_room" />

<TextView
    Android:id="@+id/tvTypeName"
    Android:layout_width="match_parent"
    Android:layout_height="wrap_content"
    Android:layout_gravity="bottom"
    Android:gravity="center"
    Android:textColor="@Android:color/white"
    Android:textSize="20sp" />


</Android.support.v7.widget.CardView>
22

URLが将来無効になり、時間を節約するために、受け入れられた回答から必要な情報を抽出しました。

GridLayoutManagerは、リストの代わりにグリッド形式でRecyclerViewを表示するために使用されます。

RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
recyclerView.setLayoutManager(mLayoutManager);

Kotlinバージョン:

recyclerView.apply {
   layoutManager = GridLayoutManager(this, 2)
}
59
raevilman

このコードは簡単に使用できます

<Android.support.v7.widget.RecyclerView
    app:layoutManager="Android.support.v7.widget.GridLayoutManager"
    app:spanCount="2"/>
7
Ahmad Aghazadeh

AndroidXライブラリを使用すると、次のことが簡単に行えます。

<androidx.recyclerview.widget.RecyclerView
    app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
    app:spanCount="2"/>
3
Nicola Gallazzi