当前位置: 代码迷 >> Android >> 如何使用RecyclerView显示空视图?
  详细解决方案

如何使用RecyclerView显示空视图?

热度:74   发布时间:2023-08-04 12:18:02.0

我知道如何在ListView中显示EmptyView,但它确实使我在RecyclerView中感到困惑,并且也从firebasedabase获取数据。 有人可以告诉我如何在下面的代码中显示空视图吗?

XML文件

<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:id="@+id/content_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.dexter.ddiary.MainActivity"
    tools:showIn="@layout/app_bar_main">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


    <LinearLayout
        android:id="@+id/main_date_display"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="4dp">


        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/main_date"
            android:gravity="center"
            android:textSize="24sp" />


    </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">


            <android.support.v7.widget.RecyclerView
                android:id="@+id/notes_list"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

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


        </LinearLayout>

    </LinearLayout>



</RelativeLayout>

MainActivity.java

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener {

    private LinearLayoutManager mlinearLayoutManager;

    private RecyclerView mNotesList;

    private FirebaseAuth auth;
    private FirebaseAuth.AuthStateListener mAuthListener;

    private DatabaseReference mDatabase;
    private DatabaseReference mDatabaseUsers;

    private DatabaseReference mDatabaseLike;
    private DatabaseReference mDataCurrentUser;

    private boolean mProcessLike = false;

    private TextView userName;

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

        auth = FirebaseAuth.getInstance();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

                if (firebaseAuth.getCurrentUser() == null) {

                    Intent loginIntent = new Intent(MainActivity.this, AccountActivity.class);
                    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(loginIntent);
                }

            }
        };

        String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(new Date());

        TextView textView = (TextView) findViewById(R.id.main_date);
        textView.setText(currentDateString);

        mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
        mDatabase = FirebaseDatabase.getInstance().getReference().child("Notes");
        mDatabaseUsers = FirebaseDatabase.getInstance().getReference().child("Users");


        mDatabase.keepSynced(true);
        mDatabaseUsers.keepSynced(true);
        mDatabaseLike.keepSynced(true);


        mNotesList = (RecyclerView) findViewById(R.id.notes_list);
        mNotesList.setHasFixedSize(true);
        mlinearLayoutManager = new LinearLayoutManager(this);
        mlinearLayoutManager.setStackFromEnd(true);
        mlinearLayoutManager.setReverseLayout(true);
        mNotesList.setLayoutManager(mlinearLayoutManager);


        checkUserExist();


        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(this);

        FloatingActionButton fab_chat = (FloatingActionButton) findViewById(R.id.fab_chat);
        fab_chat.setOnClickListener(this);

        FloatingActionButton fab_post = (FloatingActionButton) findViewById(R.id.fab_post);
        fab_post.setOnClickListener(this);


        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        userName = (TextView)navigationView.getHeaderView(0).findViewById(R.id.user_name);
    }


    @Override
    protected void onStart() {
        super.onStart();


        auth.addAuthStateListener(mAuthListener);

        FirebaseRecyclerAdapter<Notes, NotesViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Notes, NotesViewHolder>(

                Notes.class,
                R.layout.notes_row,
                NotesViewHolder.class,
                mDatabase

        ) {
            @Override
            protected void populateViewHolder(NotesViewHolder viewHolder, Notes model, int position) {

                final String post_key = getRef(position).getKey();

                viewHolder.setDate(model.getDate());
                viewHolder.setTime(model.getTime());
                viewHolder.setTitle(model.getTitle());
                viewHolder.setDesc(model.getDesc());
                viewHolder.setImage(getApplicationContext(), model.getImage());
                viewHolder.setUsername(model.getUsername());
                viewHolder.setUserImage(getApplicationContext(), model.getUserimage());

                viewHolder.setLikeBtn(post_key);

                viewHolder.mView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        //Toast.makeText(MainActivity.this, "View clicked", Toast.LENGTH_SHORT).show();

                        Intent singleNotesIntent = new Intent(MainActivity.this, NotesSingleActivity.class);
                        singleNotesIntent.putExtra("notes_id", post_key);
                        startActivity(singleNotesIntent);

                    }
                });

                viewHolder.mLikebtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        mProcessLike = true;


                        mDatabaseLike.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {

                                if (mProcessLike) {

                                    if (dataSnapshot.child(post_key).hasChild(auth.getCurrentUser().getUid())) {

                                        mDatabaseLike.child(post_key).child(auth.getCurrentUser().getUid()).removeValue();

                                        mProcessLike = false;

                                    } else {

                                        mDatabaseLike.child(post_key).child(auth.getCurrentUser().getUid()).setValue("ramdom");

                                        mProcessLike = false;

                                    }
                                }

                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {

                            }
                        });

                    }
                });

            }
        };

        mNotesList.setAdapter(firebaseRecyclerAdapter);
    }

    private void checkUserExist() {

        if (auth.getCurrentUser() != null) {



        final String user_id = auth.getCurrentUser().getUid();

        mDatabaseUsers.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {


                if (!dataSnapshot.hasChild(user_id)) {

                    Intent setupIntent = new Intent(MainActivity.this, SetupActivity.class);
                    setupIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(setupIntent);

                }


            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }

        });

        }else {
            startActivity(new Intent(MainActivity.this, AccountActivity.class));
        }
    }

    public static class NotesViewHolder extends RecyclerView.ViewHolder {

        View mView;

        ImageButton mLikebtn;

        DatabaseReference mDatabaseLike;
        FirebaseAuth mAuth;

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

            mView = itemView;

            mLikebtn = (ImageButton) mView.findViewById(R.id.like_button);

            mAuth = FirebaseAuth.getInstance();
            mDatabaseLike = FirebaseDatabase.getInstance().getReference().child("Likes");
            mDatabaseLike.keepSynced(true);


        }

        public void setLikeBtn(final String post_key) {

            if (mAuth.getCurrentUser() != null) {



            mDatabaseLike.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    if (dataSnapshot.child(post_key).hasChild(mAuth.getCurrentUser().getUid())) {

                        mLikebtn.setImageResource(R.drawable.like_it_48p);

                    } else {

                        mLikebtn.setImageResource(R.drawable.like_it_48);

                    }

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

            }

        }

        public void setDate(String date) {

            TextView notes_date = (TextView) mView.findViewById(R.id.notes_date);
            notes_date.setText(date);

        }

        public void setTime(String time) {

            TextView notes_time = (TextView) mView.findViewById(R.id.notes_time);
            notes_time.setText(time);
        }

        public void setTitle(String title) {

            TextView notes_title = (TextView) mView.findViewById(R.id.notes_title);
            notes_title.setText(title);
        }

        public void setDesc(String desc) {

            TextView notes_desc = (TextView) mView.findViewById(R.id.notes_desc);
            notes_desc.setText(desc);
        }

        public void setUsername(String username) {

            TextView notes_username = (TextView) mView.findViewById(R.id.notes_username);
            notes_username.setText(username);
        }

        public void setUserImage(final Context context, final String image) {
            final ImageView user_image = (ImageView) mView.findViewById(R.id.notes_userimage);

            // Load image from offline first
            Glide.with(context).load(image).fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL).into(user_image);
        }

        public void setImage(final Context context, final String image) {
            final ImageView notes_image = (ImageView) mView.findViewById(R.id.notes_image);

            // Load image from offline first
            Glide.with(context).load(image).fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL).into(notes_image);
        }
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);

        MenuItem item = menu.findItem(R.id.action_image);
        item.setVisible(false);

        MenuItem item2 = menu.findItem(R.id.action_share);
        item2.setVisible(false);

        MenuItem item3 = menu.findItem(R.id.action_delete);
        item3.setVisible(false);


        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_search) {
            return true;
        }

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_logout) {

            logout();
            return true;
        }

        if (item.getItemId() == R.id.action_my_post) {
            startActivity(new Intent(MainActivity.this, MyNotesActivity.class));
        }

        if (item.getItemId() == R.id.action_private_post) {
            startActivity(new Intent(MainActivity.this, PrivateNotesActivity.class));
        }

        return super.onOptionsItemSelected(item);
    }

    private void logout() {
        AuthUI.getInstance()
                .signOut(this)
                .addOnCompleteListener(new OnCompleteListener<Void>() {
                    @Override
                    public void onComplete(@NonNull Task<Void> task) {

                        Log.d("AUTH", "USER LOGGED OUT!");
                        finish();
                        ;
                    }
                });
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_account) {
            // Handle the camera action
            Intent intent = new Intent(this, AccountActivity.class);
            startActivity(intent);

            // Handle shared notes action
        } else if (id == R.id.nav_shared_notes) {
            Intent intent = new Intent(this, MyNotesActivity.class);
            startActivity(intent);

            // Handle private notes action
        } else if (id == R.id.nav_private_notes) {
            Intent intent = new Intent(this, PrivateNotesActivity.class);
            startActivity(intent);

            // Handle the Data action
        } else if (id == R.id.nav_data) {
            Intent intent = new Intent(this, DataActivity.class);
            startActivity(intent);

            // Handle the Reminders action
        } else if (id == R.id.nav_reminders) {
            Intent intent = new Intent(this, RemindersActivity.class);
            startActivity(intent);

            // Handle the help action
        } else if (id == R.id.nav_help) {
            Intent intent = new Intent(this, HelpActivity.class);
            startActivity(intent);

            // Handle the upgrade action
        } else if (id == R.id.nav_upgrade) {
            Intent intent = new Intent(this, UpgradeActivity.class);
            startActivity(intent);

            // Handle the logout action
        } else if (id == R.id.nav_logout) {
            Intent intent = new Intent(this, LogoutActivity.class);
            startActivity(intent);

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fab:
                startActivity(new Intent(MainActivity.this, EntryEditActivity.class));
                break;
            case R.id.fab_chat:
                startActivity(new Intent(MainActivity.this, ChatActivity.class));
                break;

        }
    }

}

您可以使用以下示例:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/emptyView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

    <android.support.v7.widget.RecyclerView    
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

内部适配器:

@Override
public int getItemCount() {
  if (mItems.size() == 0) {
     mRecyclerView.setVisibility(View.INVISIBLE);
  } else {
     mRecyclerView.setVisibility(View.VISIBLE);
  }
  return mItems.size();
}

您还可以使用跟随并设置其高度。

<View
        android:id="@+id/emptyview"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        />
  相关解决方案