卡片视图不可见

Card view is not visible

我正在尝试添加带有回收站视图的卡片视图。但它没有显示任何内容,只是一个空白视图。

我在这里看到了这方面的问题,它有为回收站视图和卡片视图添加依赖项的答案。这存在于我的 gradle 中。另一种是像这样使用 getItemCount:

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

这也是我认为是对的我用过list.size(); 我不明白发生了什么。我想从数据库中检索数据,可能是出错了。有谁能帮忙吗

TableListAdapter

    public class TableListAdapter extends RecyclerView.Adapter<TableListAdapter.TableViewHolder> {

    TimeTableHelper db;

    private List<TimeTable> List;

    public TableListAdapter(List<TimeTable> List) {
            this.List = List;
    }

    @Override
    public int getItemCount() {
          return List.size();
    }

    @Override
    public void onBindViewHolder(TableViewHolder contactViewHolder, int i) {

        TimeTable table = db.getTables(i);
        TimeTable ci = List.get(i);
        contactViewHolder.tableTitle.setText(table.getTitle());
   }

   @Override
   public TableViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View itemView = LayoutInflater.
                    from(viewGroup.getContext()).
                    inflate(R.layout.table_card, viewGroup, false);

        return new TableViewHolder(itemView);
   }

  public static class TableViewHolder extends RecyclerView.ViewHolder {

      protected TextView tableTitle;
      protected CardView cv;
      protected Switch aSwitch;


      public TableViewHolder(View v) {
          super(v);
          tableTitle =  (TextView) v.findViewById(R.id.tableTitle);
          cv = (CardView)  v.findViewById(R.id.card_view);
          aSwitch = (Switch)  v.findViewById(R.id.switch2);
      }
  }
}

时间表列表Activity

public class TimeTableList extends AppCompatActivity {

    private RecyclerView recyclerView;
    public ArrayList<TimeTable> items;
    public TableListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_table_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Time Table");
        toolbar.setTitleTextColor(Color.parseColor("#FFFFFF"));

        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        recyclerView = (RecyclerView)findViewById(R.id.RecyclerView);
        LinearLayoutManager llm = new LinearLayoutManager(this);

        items=new ArrayList<>();
        recyclerView.setLayoutManager(llm);

        recyclerView.setHasFixedSize(true);

        initRecyclerAdapter();

        ImageButton fab = (ImageButton) findViewById(R.id.imgbtn_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),NewTimeTable.class);
                startActivity(i);
            }
        });
    }

    private void initRecyclerAdapter() {
        adapter = new TableListAdapter(items);
        recyclerView.setAdapter(adapter);
    }
}

列表xml布局:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    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" android:fitsSystemWindows="true"
    tools:context="com.example.siddhi.timetablelayout.activities.TimeTableList">

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

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

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

    <android.support.v7.widget.RecyclerView
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:id="@+id/RecyclerView"
        android:background="@android:color/white"
        android:layout_below="@+id/view5" />
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentRight="true"
        android:layout_gravity="bottom|end">

        <include layout="@layout/myfab"/>
    </LinearLayout>
</RelativeLayout>

table_card xml :

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
    android:orientation="vertical"
    android:measureWithLargestChild="false">
    <!-- A CardView that contains a TextView -->

    <android.support.v7.widget.CardView
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        card_view:cardCornerRadius="4dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/white">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginLeft="20dp"
                android:textAppearance="@android:style/TextAppearance.Medium"
                android:id="@+id/tableTitle" />

            <Switch
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/switch2"
                android:layout_centerVertical="true"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                android:layout_marginRight="20dp" />


        </RelativeLayout>

        </android.support.v7.widget.CardView>

</LinearLayout>

Gradle:

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion '23.0.1'

    defaultConfig {
        applicationId "com.example.siddhi.timetablelayout"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:design:23.1.1'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:cardview-v7:23.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.1'
    compile 'com.google.android.gms:play-services:8.3.0'
    compile 'com.google.android.gms:play-services-wearable:8.3.0'
    compile 'com.google.android.gms:play-services-maps:7.5.0'
    compile 'com.google.android.support:wearable:1.3.0'
}

TimeTableHelper:

    public class TimeTableHelper extends SQLiteOpenHelper{


    private static final String TABLE_TIME_TABLE = "timetables";
    private static final String KEY_TABLE_TITLE = "tabletitle";
    private static final String KEY_STATUS = "status";
    private static final String KEY_TABLE_ID = "tableid";
    private static final String KEY_TABLE_COLOR = "tablecolor";

    public TimeTableHelper(Context context) {
        super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);

    }


    @Override
    public void onCreate(SQLiteDatabase db) {
    }
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        db.execSQL("DROP TABLE IF EXISTS " + TABLE_TIME_TABLE);

        // createTable(db);
        // onCreate(db);
    }
    public void addTimeTable(TimeTable table) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();

        values.put(KEY_TABLE_TITLE, table.getTitle());
        values.put(KEY_STATUS, table.getStatus());
        values.put(KEY_TABLE_COLOR, table.getTableColor());

        db.insert(TABLE_TIME_TABLE, null, values);

        db.close();
    }

    public TimeTable getTables(int id) {

        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_TIME_TABLE, new String[] { KEY_TABLE_ID,
                        KEY_TABLE_TITLE, KEY_TABLE_COLOR ,KEY_STATUS}, KEY_TABLE_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);

        cursor.moveToFirst();

        TimeTable table = new TimeTable(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), Integer.parseInt(cursor.getString(2)),Integer.parseInt(cursor.getString(3)));

        return table;

    }

    public List<TimeTable> getAllTables() {
        List<TimeTable> conList = new ArrayList<TimeTable>();

        String selectQuery = "SELECT  * FROM " + TABLE_TIME_TABLE;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {

                TimeTable table = new TimeTable();

                table.setId(Integer.parseInt(cursor.getString(0)));
                table.setTitle(cursor.getString(1));
                table.setStatus(cursor.getInt(2));
                table.setTableColor(Integer.parseInt(cursor.getString(3)));

                conList.add(table);
            } while (cursor.moveToNext());
        }

        return conList;
    }
}

创建 table:

  String CREATE_TIME_TABLE = "CREATE TABLE " + TABLE_TIME_TABLE + "("
            + KEY_TABLE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + KEY_TABLE_TITLE + " TEXT,"
            + KEY_STATUS + " TEXT,"
            + KEY_TABLE_COLOR + " TEXT" + ")";

    db.execSQL(CREATE_TIME_TABLE);

谢谢..

据我所知,您将一个空列表传递到 TimeTableList (activity) 中的 TableListAdapter。 由于在创建适配器期间列表大小为 0,因此不会为 RecyclerView 创建任何 cardView。

在创建 TableListAdapter

的实例 之前,您应该 在列表中添加一些数据点

TableListAdapter 中有一个 public void updateRecyclerAdapter(List itemList),您可以调用 post 创建适配器的实例。 该方法可能类似于下面的代码

public void updateAdapaterList(List<TimeTable> newTimeTableList) {   
    //Replace the current list with new list
    this.List = newTimeTableList;
    //notify the adapter that the data set has changed
    notifyDataSetChanged();
}

还有

确保重写 RecyclerAdapter 中的 getItemCount() 方法,如下所示。

@Override
public int getItemCount() {
    return List.size();
}

此外,我强烈建议在编码时使用适当的 camelCasing。 :)

从您的代码中我可以看出您忘记将数据点添加到 items 变量

只需将您的 activity 代码更改为此,我所做的更改是添加了@VaibhavSinghal 提供的功能来更新您的回收器视图适配器,然后通过传递您从 TimeTableHelper.getAllTables()

public class TimeTableList extends AppCompatActivity {

    private RecyclerView recyclerView;
    public ArrayList<TimeTable> items;
    public TableListAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_time_table_list);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("Time Table");
        toolbar.setTitleTextColor(Color.parseColor("#FFFFFF"));

        toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        recyclerView = (RecyclerView)findViewById(R.id.RecyclerView);
        LinearLayoutManager llm = new LinearLayoutManager(this);

        items=new ArrayList<>();
        recyclerView.setLayoutManager(llm);

        recyclerView.setHasFixedSize(true);

        initRecyclerAdapter();
        // Get reference to your time tableHelper
        TimeTableHelper timeTableHelper = new TimeTableHelper(this);
        // Update your adapter with elements returned by getAllTables() function
        updateAdapterList(timeTableHelper.getAllTables());

        ImageButton fab = (ImageButton) findViewById(R.id.imgbtn_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),NewTimeTable.class);
                startActivity(i);
            }
        });
    }

    private void initRecyclerAdapter() {
        adapter = new TableListAdapter(items);
        recyclerView.setAdapter(adapter);
    }

    public void updateAdapaterList(List<TimeTable> newTimeTableList) {   
        //Replace the current list with new list
        this.List = newTimeTableList;
        //notify the adapter that the data set has changed
        notifyDataSetChanged();
    }


}

正如我在您的代码中看到的那样,您没有在列表中添加内容,这就是它显示空白的原因,因为当时列表大小为 ZERO

您只需初始化您的列表并设置适配器。在初始化适配器之前在您的列表中添加一些数据。

Your code

recyclerView = (RecyclerView)findViewById(R.id.RecyclerView);
        LinearLayoutManager llm = new LinearLayoutManager(this);

        items=new ArrayList<>();   // **Add data to list after initialization**
        recyclerView.setLayoutManager(llm);

        recyclerView.setHasFixedSize(true);

        initRecyclerAdapter();

        ImageButton fab = (ImageButton) findViewById(R.id.imgbtn_fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(getApplicationContext(),NewTimeTable.class);
                startActivity(i);
            }
        });