CardView无法在RecyclerView中显示

时间:2017-05-05 16:33:36

标签: android android-recyclerview android-cardview

在你问之前,是的,我知道有很多问题与此非常相似,我尝试了大部分问题都无济于事。我的问题是CardView没有在RecyclerView中显示。其中的项目正在显示,但不是卡片本身。

没有进一步或做,这是我的代码:

适配器:

Integer count = 0;
Boolean isStart = true;
String datag = "";
String typeg = "";
Integer LastItemType=0; //0=None 1=Text 2=Image
ViewHolder a;
@Override
public EntryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    a= createholder(parent, viewType);
    return(a);
}
public ViewHolder createholder(ViewGroup parent, int viewtype) {

        if (typeg.equals("image")) {
            View root = LayoutInflater.from(parent.getContext()) 
                    .inflate(R.layout.listitems, parent, false);
            CardView card = (CardView) root.findViewById(R.id.card_view);
            ImageView image = (ImageView) root.findViewById(R.id.Img);
            ((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.card_view));
            if (LastItemType == 2) {
                ((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.Img));
            }
            if (LastItemType == 1) {
                ((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.Txt));
            }
            ViewHolder vh = new ViewHolder(image, card);
            LastItemType = 2;
            return vh;
        } else {
            if (typeg.equals("text")) {
                View root = LayoutInflater.from(parent.getContext()) 
                        .inflate(R.layout.listitems, parent, false);
                CardView card = (CardView) root.findViewById(R.id.card_view);
                TextView image = (TextView) root.findViewById(R.id.Txt);
                ((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.card_view));
                if (LastItemType == 1) {
                    ((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.Txt));
                }
                if (LastItemType == 2) {
                    ((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.Img));
                }
                ViewHolder vh = new ViewHolder(image, card);
                LastItemType = 1;
                return vh;
            }
            return null; //TODO: REMOVE!
        }
}
@Override
public void onBindViewHolder(EntryAdapter.ViewHolder holder, int position) {
    // Deal with data

}
public class ViewHolder extends RecyclerView.ViewHolder {
    public ImageView imgg;
    public TextView txtg;
    public CardView cardg;
    public ViewHolder(ImageView image, CardView card) {
        super(image);
        imgg = image;
        cardg = card;
}
    public ViewHolder(TextView text, CardView card) {
        super(text);
        txtg = text;
        cardg = card;
    }
}
@Override
public int getItemCount() {
    return count;
}
public void refresh(String data, String type, ViewGroup parent) {
    isStart = false;
    datag = data;
    typeg = type;
    count++;
    createholder(parent, -100);
}

listitems.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_gravity="center"
    android:layout_width="200dp"
    android:layout_height="200dp"
    card_view:cardCornerRadius="4dp">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp"
        >
<ImageView
    android:layout_height="wrap_content"
    android:layout_weight="0.25"
    android:layout_width="wrap_content"
    android:layout_margin="10dp"
    android:id="@+id/Img"
    android:scaleType="center"
    android:maxHeight="100dp"
    android:maxWidth="150dp"/>
<TextView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:layout_weight="0.25"
    android:id="@+id/Txt"
    android:layout_gravity="center_horizontal|center_vertical"/>
    </RelativeLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

提前致谢!

4 个答案:

答案 0 :(得分:2)

查看我的代码,我稍微修改后将其用于我的每个应用程序。如果您有多个RecyclerViews,也可以通过相应地更改它的类型字段和布局和视图来使用适配器。它包含一个CoordinatorLayout,其中包含带有ImageView的CollapsingLayout。它包含许多Material Design的布局,我希望它有所帮助。

Activity包含RecyclerView和CardView,我删除了你可能不需要的数据库,浮动操作按钮之类的东西,可能会让它更难理解。如果您需要全班同学,请与我联系。

public class MeasureListActivity extends AppCompatActivity
    implements MeasureListAdapter.OnRecyclerViewMeasureClickListener {
// Views
private RecyclerView mRecyclerView;
private MeasureListAdapter mAdapter;
private Toolbar toolbar;

// List that keeps values displayed on the screen
private List<Measure> listMeasure;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_prev_measures);
    setViews();
}



private void setViews() {
    /*
     * Set toolbar and arrow icon to return back
     */
    toolbar = (Toolbar) findViewById(R.id.toolbarPrevMeasure);
    setSupportActionBar(toolbar);
    // Enable home button for API < 14
    getSupportActionBar().setHomeButtonEnabled(true);
    // Enable home button for API >= 14
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    /*
     * RecylerView to display items as a list
     */
    mRecyclerView = (RecyclerView) findViewById(R.id.recyclerViewPrevMeasure);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));

    mAdapter = new MeasureListAdapter(this, listMeasure, 0);

    // Attach an instance of OnRecyclerViewMeasureClickListener that
    // implements itemClicked()
    mAdapter.setClickListener(this);
    mRecyclerView.setAdapter(mAdapter);

}



@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == android.R.id.home) {
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void itemMeasureClicked(View view, int position) {

}

}

public class MeasureListAdapter extends RecyclerView.Adapter<MeasureListAdapter.MyViewHolder> {

private LayoutInflater inflater;
private List<Measure> data = Collections.emptyList();
// This is for delegating event from adapter's onClick() method to
// NavigationDrawerFragment
private OnRecyclerViewMeasureClickListener recyclerClickListener;
private DecimalFormat decimalFormat;
private int type = 0;
private Context mContext;

public MeasureListAdapter(Context context, List<Measure> data, int type) {
    mContext = context;
    inflater = LayoutInflater.from(context);
    this.data = data;
    decimalFormat = new DecimalFormat("###.#");
    this.type = type;

}

@Override
public int getItemCount() {

    return data.size();
}

@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
    Measure measure = data.get(position);
    String title = measure.getTitle();
    String note = measure.getNote();
    String date = measure.getFormattedDate();
    double angle = measure.getAnglePhoto();
    // Compass
    double azimuth = measure.getAngleAzimuth();
    double pitch = measure.getAnglePitch();
    double roll = measure.getAngleRoll();
    String bearing = measure.getBearing();

    holder.tvTitle.setText(title);
    holder.tvNote.setText(note);
    holder.tvAngle.setText(
            mContext.getString(R.string.angle) + ": " + decimalFormat.format(angle) + ConstantsApp.DEGREE_ICON);
    // Compass
    holder.tvAzimuth.setText(
            mContext.getString(R.string.azimuth) + ": " + decimalFormat.format(azimuth) + ConstantsApp.DEGREE_ICON);
    holder.tvPitch.setText(
            mContext.getString(R.string.pitch) + ": " + decimalFormat.format(pitch) + ConstantsApp.DEGREE_ICON);
    holder.tvRoll.setText(
            mContext.getString(R.string.roll) + ": " + decimalFormat.format(roll) + ConstantsApp.DEGREE_ICON);
    holder.tvBearing.setText(mContext.getString(R.string.bearing) + " " + bearing);

    holder.tvDate.setText("Date" + ": " + measure.getFormattedDate());
}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int arg1) {
    View view = null;

    view = inflater.inflate(R.layout.custom_row_angle_photo, parent, false);

    MyViewHolder viewHolder = new MyViewHolder(view);
    return viewHolder;
}

/**
 * get an instance of OnRecyclerViewClickListener interface
 * 
 * @param OnRecyclerViewMeasureClickListener
 *            callback that is used by adapter to invoke the method of the
 *            class implements the OnRecyclerViewClickListener interface
 */
public void setClickListener(OnRecyclerViewMeasureClickListener recyclerClickListener) {
    this.recyclerClickListener = recyclerClickListener;
}

public void delete(int position) {
    data.remove(position);
    notifyItemRemoved(position);
}

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    // Views
    private TextView tvTitle, tvNote, tvAngle, tvAzimuth, tvPitch, tvRoll, tvBearing, tvDate;

    public MyViewHolder(View itemView) {
        super(itemView);
        tvTitle = (TextView) itemView.findViewById(R.id.tvDisplayTitle);
        tvAngle = (TextView) itemView.findViewById(R.id.tvDisplayAngle);
        // Compass
        tvAzimuth = (TextView) itemView.findViewById(R.id.tvDisplayAzimuth);
        tvPitch = (TextView) itemView.findViewById(R.id.tvDisplayPitch);
        tvRoll = (TextView) itemView.findViewById(R.id.tvDisplayRoll);
        tvBearing = (TextView) itemView.findViewById(R.id.tvDisplayBearing);

        tvNote = (TextView) itemView.findViewById(R.id.tvDisplayNote);
        tvDate = (TextView) itemView.findViewById(R.id.tvDisplayDate);

        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (recyclerClickListener != null) {
            recyclerClickListener.itemMeasureClicked(v, getLayoutPosition());
        }
    }
}

/**
 * RecyclerViewClickListener interface helps user to set a clickListener to
 * the RecyclerView. By setting this listener, any item of Recycler View can
 * respond to any interaction.
 * 
 * @author Fatih
 *
 */
public interface OnRecyclerViewMeasureClickListener {
    /**
     * This is a callback method that be overriden by the class that
     * implements this interface
     */
    public void itemMeasureClicked(View view, int position);
}

}

Measure类只包含int和String值的setter和getter,所以我不会把它放在一起。

活动布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/layoutMainMeasure"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<android.support.design.widget.CoordinatorLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:background="@android:color/background_light"
    android:paddingBottom="50dp" >

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbarPrevMeasure"
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:fitsSystemWindows="true"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" >

        <android.support.design.widget.CollapsingToolbarLayout
            android:id="@+id/collapsingToolbarPrevMeasure"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layout_scrollFlags="scroll|enterAlwaysCollapsed"
            android:fitsSystemWindows="true"
            app:contentScrim="?attr/colorPrimary"
            app:expandedTitleMarginEnd="64dp"
            app:expandedTitleMarginStart="48dp" >

            <ImageView
                android:id="@+id/backgroundPrevMeasure"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_collapseMode="parallax"
                android:fitsSystemWindows="true"
                android:scaleType="centerCrop"
                android:src="@drawable/bg_material" />

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbarPrevMeasure"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:layout_collapseMode="pin"
                app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
        </android.support.design.widget.CollapsingToolbarLayout>
    </android.support.design.widget.AppBarLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerViewPrevMeasure"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        android:background="#eeeeee"
        android:paddingTop="12dp" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabLog"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="80dp"
        app:layout_anchor="@id/appbarPrevMeasure"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/ic_save_white_36dp"
        android:tint="@android:color/white"
        app:backgroundTint="#FFA500" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fabClearDB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/activity_horizontal_margin"
        app:layout_anchor="@id/appbarPrevMeasure"
        app:layout_anchorGravity="bottom|right|end"
        android:src="@drawable/ic_delete_white_36dp"
        android:tint="@android:color/white"
        app:backgroundTint="#D463C3" />
</android.support.design.widget.CoordinatorLayout>

使用CardView的适配器行的布局

<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:cardview="http://schemas.android.com/apk/res-auto"
android:id="@+id/cardRecord"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:background="#eeeeee"
cardview:cardCornerRadius="5dp"
cardview:cardElevation="5dp" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="8dp" >

    <TextView
        android:id="@+id/tvDisplayTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:textColor="#FF0000" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvDisplayAngle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:text="@string/angle_"
            android:textColor="#525657"
            android:textSize="18sp" />

        <TextView
            android:id="@+id/tvDisplayAzimuth"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:text="@string/angle_"
            android:textColor="#525657"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/tvDisplayBearing"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:text="@string/angle_"
            android:textColor="#525657"
            android:textSize="14sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <TextView
            android:id="@+id/tvDisplayPitch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="12dp"
            android:text="@string/angle_"
            android:textColor="#525657"
            android:textSize="14sp" />

        <TextView
            android:id="@+id/tvDisplayRoll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="12dp"
            android:text="@string/angle_"
            android:textColor="#525657"
            android:textSize="14sp" />
    </LinearLayout>

    <TextView
        android:id="@+id/tvDisplayDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:text="@string/date_"
        android:textColor="#9EA9AD"
        android:textSize="14sp" />

    <TextView
        android:id="@+id/tvDisplayNote"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:text=""
        android:textColor="#828A8C"
        android:textSize="14sp" />
</LinearLayout>

它看起来如何 Coordinator Layout RecyclerView Carview Combo

答案 1 :(得分:2)

这是正确的Documentation 阅读并遵循它。 你必须在Gradle做错事。 所以,问题是你的XML在我们这里没有显示CardView。!

添加以下依赖项。!

   compile 'com.android.support:design:25.3.1'

    compile 'com.android.support:support-v4:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'com.android.support:appcompat-v7:25.3.1'


     testCompile 'junit:junit:4.12'

enter image description here

这是你的XML工作得非常好。!

   <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_gravity="center"
        android:layout_width="200dp"
        android:layout_height="200dp"
        card_view:cardCornerRadius="4dp">
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="16dp"
            >
            <ImageView
                android:layout_height="wrap_content"
                android:layout_weight="0.25"
                android:layout_width="wrap_content"
                android:layout_margin="10dp"
                android:id="@+id/Img"
                android:scaleType="center"
                android:maxHeight="100dp"
                android:maxWidth="150dp"/>
            <TextView
                android:layout_height="wrap_content"
                android:layout_width="wrap_content"
                android:layout_weight="0.25"
                android:id="@+id/Txt"
                android:layout_gravity="center_horizontal|center_vertical"/>
        </RelativeLayout>
    </android.support.v7.widget.CardView>
</LinearLayout>

现在清理并重建您的项目。 好吧,试试这个工作好。现在。!

enter image description here

答案 2 :(得分:1)

您的RecyclerView仅显示ImageView或TextView吗? 如果是,因为您的ViewHolder构造函数是错误的。您必须在ViewHolder的构造函数中调用super(itemView),itemView是在RecyclerView中显示为行的视图。要解决您的问题,我认为您应该更改以下代码:

public ViewHolder createholder(ViewGroup parent, int viewtype) {
    if (typeg.equals("image") || typeg.equals("text")) {
        View root = LayoutInflater.from(parent.getContext()) 
                    .inflate(R.layout.listitems, parent, false);
        return new ViewHolder(root, typeg.equals("text"));
    }
    //FIXME: As my expericence you should NOT return null for ViewHolder. You have to sure the typeg is one of "image" or "text". I think you should change typeg to Boolean variable to not return null ViewHolder.
    return null;
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public ImageView imgg;
    public TextView txtg;
    public CardView cardg;
    public ViewHolder(View itemView, boolean isTypeText) {
        super(itemView);
        imgg = (ImageView) itemView.findViewById(R.id.Img);
        cardg = (CardView) itemView.findViewById(R.id.card_view);
        txtg = (TextView) itemView.findViewById(R.id.Txt);
        imgg.setVisibility(isTypeText ? View.GONE : View.VISIBLE);
        txtg.setVisibility(isTypeText ? View.VISIBLE : View.GONE);
    }
}

答案 3 :(得分:0)

是因为您要删除card_view吗?

((ViewGroup)image.getParent()).removeView(root.findViewById(R.id.card_view));