Why is recyclerview gone when I set android:layout_height="wrap_content"?

Issue

Why is RecyclerView gone when I set android:layout_height="wrap_content" in RecyclerView ?
But it’s normal when I set android:layout_height="300dp" in RecyclerView

android:layout_height="wrap_content" in RecyclerView

activity_currency.xml :

    <?xml version="1.0" encoding="utf-8"?>
    
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".currency.CurrencyActivity">
    
        <TextView
            android:id="@+id/textView_announcement"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginEnd="16dp"
            android:background="@color/textField_background_yellow01"
            android:gravity="left"
            android:padding="8dp"
            android:textAppearance="@style/TextAppearance.AppCompat.Small"
            android:textColor="@color/black"
            android:text="123"
            android:typeface="monospace"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recycler_view_currency"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="4dp"
            android:layout_marginRight="16dp"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView_announcement"
            tools:listitem="@layout/currency_recyclerview_row" />
    </androidx.constraintlayout.widget.ConstraintLayout>

CurrencyActivity.java

package com.weberhwang.longterminvestmentanalyst.currency;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

import com.weberhwang.longterminvestmentanalyst.R;
import com.weberhwang.longterminvestmentanalyst.common.UserDefinedMessage;
import com.weberhwang.longterminvestmentanalyst.common.FunctionResultLauncher;
import com.weberhwang.longterminvestmentanalyst.databinding.ActivityCurrencyBinding;
import com.weberhwang.longterminvestmentanalyst.db.InvestmentProjectViewModel;
import com.weberhwang.longterminvestmentanalyst.entity.InvestmentProject;
import com.weberhwang.longterminvestmentanalyst.exportandrestore.ExportAndRestoreActivity;
import com.weberhwang.longterminvestmentanalyst.entity.DetailCode;
import com.weberhwang.longterminvestmentanalyst.home.HomeActivity;
import com.weberhwang.longterminvestmentanalyst.investmentproject.InvestmentProjectActivity;
import com.weberhwang.longterminvestmentanalyst.summary.SummaryActivity;
import com.weberhwang.longterminvestmentanalyst.taxandfee.TaxAndFeeModelActivity;
import com.weberhwang.longterminvestmentanalyst.tools.DateTimeCreator;
import com.weberhwang.longterminvestmentanalyst.trans.TransChoiceProjectActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
import java.util.UUID;

public class CurrencyActivity extends AppCompatActivity {
    private DateTimeCreator dateTimeCreator = new DateTimeCreator();
    private UserDefinedMessage userDefinedMessage;

    private TreeMap<String, InvestmentProject> allRoomInvestmentProjects = new TreeMap<>();

    private ActivityCurrencyBinding binding;
    private ActionBar actionBar;
    private AlertDialog.Builder alertDialog;
    private RecyclerView recyclerView;
    // private ExtendedFloatingActionButton buttonInsertCurrency;

    private InvestmentProjectViewModel investmentProjectViewModel;


    private FunctionResultLauncher functionResultLauncher;

    private ActivityResultLauncher<Intent> homeActivityResultLauncher;
    private ActivityResultLauncher<Intent> summaryActivityResultLauncher;
    private ActivityResultLauncher<Intent> transActivityResultLauncher;

    private ActivityResultLauncher<Intent> investmentProjectActivityResultLauncher;
    private ActivityResultLauncher<Intent> taxAndFeeModelActivityResultLauncher;
    private ActivityResultLauncher<Intent> currencyActivityResultLauncher;
    private ActivityResultLauncher<Intent> exportAndRestoreActivityResultLauncher;

    private ActivityResultLauncher<Intent> currencyUpdateActivityResultLauncher;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityCurrencyBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        dateTimeCreator.setFormat("yyyy-MM-dd HH:mm:ss");

        userDefinedMessage =
                new UserDefinedMessage(getResources().getConfiguration().getLocales().get(0).getLanguage());

        bindingVarSetting();

        initActivityField();

        functionResultLauncher = new FunctionResultLauncher(this);
        homeActivityResultLauncher = functionResultLauncher.getHomeActivityResultLauncher();
        summaryActivityResultLauncher = functionResultLauncher.getSummaryActivityResultLauncher();
        // batchUpdateExchangeRateActivityResultLauncher = functionResultLauncher.getBatchUpdateExchangeRateActivityResultLauncher();
        transActivityResultLauncher = functionResultLauncher.getTransActivityResultLauncher();
        investmentProjectActivityResultLauncher = functionResultLauncher.getInvestmentProjectActivityResultLauncher();
        taxAndFeeModelActivityResultLauncher = functionResultLauncher.getTaxAndFeeModelActivityResultLauncher();
        currencyActivityResultLauncher = functionResultLauncher.getCurrencyActivityResultLauncher();
        exportAndRestoreActivityResultLauncher = functionResultLauncher.getExportAndRestoreActivityResultLauncher();

        final CurrencyAdapter adapter = new CurrencyAdapter();
        recyclerView.setAdapter(adapter);

        investmentProjectViewModel = new ViewModelProvider(this).get(InvestmentProjectViewModel.class);

        DetailCode detailCodeTemp = new DetailCode(null, null,
                null, null, null, null, null, null, null,
                null, null, null, null);
        detailCodeTemp.setMCode("001");
        try {
            investmentProjectViewModel.getDetailCodesByMCode(detailCodeTemp).observe(this, new Observer<List<DetailCode>>() {
                @Override
                public void onChanged(List<DetailCode> detailCodes) {
                    String mainCurrency = "";
                    ExchangeRateCalculator exchangeRateCalculator = new ExchangeRateCalculator();
                    detailCodes = exchangeRateCalculator.sortCurrencies(detailCodes); 

                    for (DetailCode detailCode : detailCodes) {
                        mainCurrency = detailCode.getDCode();
                        break;
                    }

                    if (mainCurrency.equalsIgnoreCase("TWD")) {
                        detailCodes = exchangeRateCalculator.getExchangeRateIsTWD(detailCodes);
                    } else {

                        detailCodes = exchangeRateCalculator.getExchangeRateNotTWD(detailCodes);
                    }
                    adapter.submitList(detailCodes);
                }
            });
        } catch (Exception e) {
            Log.d("MyLog", "Exception", e);
        }

        try {
            investmentProjectViewModel.getAllInvestmentProjects().observe(this, new Observer<List<InvestmentProject>>() {
                @Override
                public void onChanged(@Nullable List<InvestmentProject> investmentProjects) {
                    allRoomInvestmentProjects.clear();
                    for (InvestmentProject item : investmentProjects) {
                        allRoomInvestmentProjects.put(item.getProjectCode(), item);
                    }
                }
            });
        } catch (Exception e) {
            Log.d("MyLog", "Exception", e);
        }

        currencyUpdateActivityResultLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == Activity.RESULT_OK) {
                            // There are no request codes
                            Intent data = result.getData();
                            DetailCode currency = (DetailCode) data.getSerializableExtra("Currency");
                            currency.setUpdateTime(dateTimeCreator.getSystemTime());
                            currency.setChangeMode("U");

                        }
                    }
                });

   

        adapter.setOnItemClickListener(new CurrencyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(DetailCode detailCode) {

                Intent intent = new Intent(CurrencyActivity.this, CurrencyEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("Currency", detailCode);
                intent.putExtras(bundle);
                currencyUpdateActivityResultLauncher.launch(intent);
            }
        });
    }


    private void bindingVarSetting() {
        actionBar = getSupportActionBar();

        // RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView = binding.recyclerViewCurrency;
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setHasFixedSize(true);

        alertDialog = new AlertDialog.Builder(CurrencyActivity.this)
                .setTitle("Error message")
                .setMessage("")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                });
    }


    private void initActivityField() {

        actionBar.setTitle("Long-Term Investment Analyst");
        actionBar.setSubtitle("Currency");
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.function_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.menu_home:
                intent = new Intent(CurrencyActivity.this, HomeActivity.class);
                homeActivityResultLauncher.launch(intent);
                return true;
            case R.id.menu_summary:
                intent = new Intent(CurrencyActivity.this, SummaryActivity.class);
                summaryActivityResultLauncher.launch(intent);
                return true;
            case R.id.menu_trans:
                intent = new Intent(CurrencyActivity.this, TransChoiceProjectActivity.class);
                transActivityResultLauncher.launch(intent);
                return true;
            case R.id.menu_investment_project:
                intent = new Intent(CurrencyActivity.this, InvestmentProjectActivity.class);
                investmentProjectActivityResultLauncher.launch(intent);
                return true;
            case R.id.menu_tax_and_fee_model:
                intent = new Intent(CurrencyActivity.this, TaxAndFeeModelActivity.class);
                taxAndFeeModelActivityResultLauncher.launch(intent);
                return true;
            case R.id.menu_currency:
                intent = new Intent(CurrencyActivity.this, CurrencyActivity.class);
                currencyActivityResultLauncher.launch(intent);
                return true;
            case R.id.menu_export_and_restore:
                intent = new Intent(CurrencyActivity.this, ExportAndRestoreActivity.class);
                exportAndRestoreActivityResultLauncher.launch(intent);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

CurrencyAdapter.java

package com.weberhwang.longterminvestmentanalyst.currency;

import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.RecyclerView;

import com.weberhwang.longterminvestmentanalyst.entity.DetailCode;
import com.weberhwang.longterminvestmentanalyst.R;

import java.math.BigDecimal;

public class CurrencyAdapter extends ListAdapter<DetailCode, CurrencyAdapter.CurrencyHolder> {

    private OnItemClickListener listener;


    private static final DiffUtil.ItemCallback<DetailCode> DIFF_CALLBACK = new DiffUtil.ItemCallback<DetailCode>() {

        @Override
        public boolean areItemsTheSame(@NonNull DetailCode oldItem, @NonNull DetailCode newItem) {
            return oldItem.getUuid() == newItem.getUuid();
        }

        @Override
        public boolean areContentsTheSame(@NonNull DetailCode oldItem, @NonNull DetailCode newItem) {
            return oldItem.getMCode().equals(newItem.getMCode()) &&
                    oldItem.getDCode().equals(newItem.getDCode()) &&
                    oldItem.getDCodeName().equals(newItem.getDCodeName()) &&
                    oldItem.getAttr1().equals(newItem.getAttr1()) &&
                    oldItem.getAttr2().equals(newItem.getAttr2()) &&
                    oldItem.getAttr3().equals(newItem.getAttr3()) &&
                    oldItem.getAttr4().equals(newItem.getAttr4()) &&
                    oldItem.getAttr5().equals(newItem.getAttr5()) &&
                    oldItem.getAttr6().equals(newItem.getAttr6()) &&
                    oldItem.getMainCurrencyChange().equals(newItem.getMainCurrencyChange()) &&
                    (oldItem.getExchangeRate().compareTo(newItem.getExchangeRate())) == 0 &&
                    oldItem.getStatus().equals(newItem.getStatus()) &&
                    oldItem.getCreateTime().equals(newItem.getCreateTime()) &&
                    oldItem.getUpdateTime().equals(newItem.getUpdateTime()) &&
                    oldItem.getChangeMode().equals(newItem.getChangeMode());
        }
    };


    public CurrencyAdapter() {
        super(DIFF_CALLBACK);
    }


    @NonNull
    @Override
    public CurrencyHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.currency_recyclerview_row, parent, false);
        return new CurrencyHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull CurrencyHolder holder, int position) {

        DetailCode currentDetailCode = getItem(position);
        holder.textViewCurrencyCode.setText(currentDetailCode.getDCode());
        holder.textViewCurrencyName.setText(currentDetailCode.getDCodeName());


        if (currentDetailCode.getExchangeRate().compareTo(new BigDecimal("0")) <= 0) {
            holder.textViewExchangeRate.setText("");
        } else if (currentDetailCode.getAttr2().equalsIgnoreCase("y")) {
            holder.textViewExchangeRate.setText("Main currency");
        } else {
            holder.textViewExchangeRate.setText(currentDetailCode
                            .getExchangeRate()
                            .setScale(6, BigDecimal.ROUND_HALF_UP)
                            .stripTrailingZeros()
                            .toPlainString());
        }


        if (currentDetailCode.getAttr2().equalsIgnoreCase("y")) {
            holder.textViewCurrencyCode.setTextColor(Color.parseColor("#0138FA"));
            holder.textViewCurrencyName.setTextColor(Color.parseColor("#0138FA"));
        } else {
            holder.textViewCurrencyCode.setTextColor(Color.parseColor("#000000"));
            holder.textViewCurrencyName.setTextColor(Color.parseColor("#000000"));
        }
    }


    public DetailCode getDetailCodeAt(int position) {

        return getItem(position);
    }

    class CurrencyHolder extends RecyclerView.ViewHolder {
        private TextView textViewCurrencyName;
        private TextView textViewCurrencyCode;
        private TextView textViewExchangeRate;

        public CurrencyHolder(View itemView) {
            super(itemView);

            textViewCurrencyName = itemView.findViewById(R.id.textView_currency_name);
            textViewCurrencyCode = itemView.findViewById(R.id.textView_currency_code);
            textViewExchangeRate = itemView.findViewById(R.id.textView_exchange_rate);
            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int position = getAdapterPosition();
                    if (listener != null && position != RecyclerView.NO_POSITION) {
 
                        listener.onItemClick(getItem(position));
                    }
                }
            });
        }
    }


    public interface OnItemClickListener {
        void onItemClick(DetailCode detailCode);
    }


    public void setOnItemClickListener(OnItemClickListener listener) {
        this.listener = listener;
    }
}

Solution

I think it’s because your RecyclerView doesn’t have a bottom constraint. Try to add bottom constraint, but in case it still not working, set the layout_height to 0dp.

Answered By – Bernhard Josephus

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published