卡片视图不可见

时间:2016-03-02 05:31:47

标签: java android android-recyclerview visible android-cardview

我正在尝试使用回收站视图添加卡片视图。但它没有显示任何东西,只是一个空白视图。

我在这里已经看到了这方面的问题,它有回答为回收者视图和卡片视图添加依赖关系。这存在于我的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);
      }
  }
}

TimeTableList活动

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>

摇篮:

    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;
    }
}

创建表格:

  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);

谢谢..

3 个答案:

答案 0 :(得分:2)

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

只需将您的活动代码更改为此,此处我所做的更改是添加@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();
    }


}

答案 1 :(得分:2)

You did not added content in your list as i can see in your code, thats why its showing blank because list size is ZERO at that time.

You just initialize your list and set the adapter. Add some data in your list before initializing adapter.

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);
            }
        });

答案 2 :(得分:1)

从我所看到的,您将空列表传递到TableListAdapter(活动)中的TimeTableList。 由于在创建适配器期间列表大小为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 。 :)