magic00 2019-12-24
学习自:博客园 CSDN Android 官方文档
Android 呈现数据的方式有很多种,使用自定义控件,使用 ListView
,使用Recyclerview
.
那么我们今天看一下Android 中 如是使用 Recyclerview
。
官方文档所示,我们需要声明以下依赖性:
dependencies { implementation "androidx.recyclerview:recyclerview:1.1.0" // For control over item selection of both touch and mouse driven selection implementation "androidx.recyclerview:recyclerview-selection:1.1.0-beta01" }
<?xml version="1.0" encoding="utf-8"?> <androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:card_view="http://schemas.android.com/apk/res-auto" xmlns:tool="http://schemas.android.com/tools" android:id="@+id/drawLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:animateLayoutChanges="true" android:orientation="vertical" tool:context=".MainPackage.MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbarLibrary" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#517EB9" android:fitsSystemWindows="true" app:layout_scrollFlags="scroll|enterAlways" app:popupTheme="@style/Theme.AppCompat.Light" app:titleTextColor="#fff" /> <AutoCompleteTextView android:id="@+id/auto2" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:text="MultiAutoCompleteTextView" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/LibraryListview" class="androidx.appcompat.app.AlertController$RecycleListView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:overScrollMode="never"> </androidx.recyclerview.widget.RecyclerView> <MultiAutoCompleteTextView android:id="@+id/multiAutoCompleteTextView" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="MultiAutoCompleteTextView" /> </LinearLayout> <com.google.android.material.navigation.NavigationView android:id="@+id/navigationViewLilbary" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="start" app:menu="@menu/library_items_menu" /> </androidx.drawerlayout.widget.DrawerLayout>
这样 我们的布局文件就创建完成了。这边不做过多的解释。
Recyclerview
我们已经在布局文件中创建好了我们的Recyclerview
。
接着我们看一下如何使用它吧。
public class LibraryMainActivity extends AppCompatActivity { NavigationView navigationView; DrawerLayout drawerLayout; TextView txtEmail; TextView txtName; ImageView UserImageView; List<String> listImage = new ArrayList<>(); Toolbar toolbar; RecyclerView recyclerView; LinearLayoutManager linearLayoutManager; List<String> list = new ArrayList<>(); List<String> SearchNameList = new ArrayList<>(); AutoCompleteTextView SearchAuto; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_library_main); //region -实例化基础控件等- drawerLayout = findViewById(R.id.drawLayout); navigationView = findViewById(R.id.navigationViewLilbary); txtEmail = findViewById(R.id.txtEmail); txtName = findViewById(R.id.txtName); toolbar = findViewById(R.id.toolbarLibrary); toolbar.setTitle("欢迎使用图书馆"); toolbar.setLogo(R.drawable.ic_action_name); this.setSupportActionBar(toolbar); // endregion //region -基础设置- toolbar.setOnClickListener(v -> { drawerLayout.openDrawer(navigationView); }); GetUserInformation(); //设置 沉浸式体验 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN); } //endregion linearLayoutManager = new LinearLayoutManager(this); recyclerView = findViewById(R.id.LibraryListview); StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL); recyclerView.setLayoutManager(layoutManager); recyclerView.setItemAnimator(new DefaultItemAnimator()); int a = 100; for (int i = 0; i < a; i++) { list.add("第一行代码 - 郭霖\t(第二版)" + String.valueOf(i)); SearchNameList.add("第一行代码 - 郭霖\t(第二版)" + String.valueOf(i)); } recyclerView.setAdapter(new RecyclerViewAdapter(LibraryMainActivity.this, list)); SearchAuto = findViewById(R.id.auto2); SearchAuto.setAdapter(new ArrayAdapter<>(LibraryMainActivity.this, android.R.layout.simple_spinner_dropdown_item, SearchNameList)); } /** *@ClassName:LibraryMainActivity - 用于获取 当前登录用户的个人信息,头像等。 *@author:CaoJiaHao *@Param: **/ void GetUserInformation() { new Thread(new Runnable() { @Override public void run() { String ImageString = Global.HttpGet("UserInformations/" + SessionClass.userClass.get(0).getUserId(), null); listImage = UserImageJSON.modelJson(ImageString); String imageString = listImage.get(0); final Bitmap Userbitmap = Global.StringToBitmap(imageString); runOnUiThread(new Runnable() { @Override public void run() { View viewHearder = navigationView.inflateHeaderView(R.layout.nav_header); txtName = viewHearder.findViewById(R.id.txtName); txtEmail = viewHearder.findViewById(R.id.txtEmail); UserImageView = viewHearder.findViewById(R.id.UserImageView); txtName.setText("User Name: " + SessionClass.userClass.get(0).getUserName()); txtEmail.setText("Email: " + SessionClass.userClass.get(0).getEmail()); UserImageView.setImageBitmap(Userbitmap); //处理当前登录这没有头像的情况 if (Userbitmap == null || Userbitmap.isRecycled()) UserImageView.setImageResource(R.drawable.user_image); } }); } }).start(); } }
这样我们在活动中使用使用我们的Recyclerview
就完成了。
当时我们可以看到,在程序中我们使用到了适配器。
接下来我们就看一下适配器是如何编写的。
如果之前学过Recyclerview的人可能知道。在Recyclerview中并没有给你封装好的单击事件和长按事件等。那么这就意味着。我们需要自己写。
我们先看一下我们的适配器源码:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private Context mContext; private List<String> mList = new ArrayList<>(); TextView textView; ImageView booksImage; public RecyclerViewAdapter(Context mContext, List<String> mList) { this.mContext = mContext; this.mList = mList; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.r_view_items, parent, false); textView = view.findViewById(R.id.text_view); booksImage = view.findViewById(R.id.booksImageView); return new ViewHodel(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) { textView.setText(mList.get(position)); holder.itemView.setOnClickListener(v -> { Toast.makeText(mContext, "Hello android", Toast.LENGTH_SHORT).show(); }); holder.itemView.setOnLongClickListener(v -> { View viewInformation = LayoutInflater.from(mContext).inflate(R.layout.book_information, null, false); ImageView imageView = viewInformation.findViewById(R.id.booksInformationImageView); TextView txtName = viewInformation.findViewById(R.id.txtBookName); txtName.setText(textView.getText()); Bitmap bitmap = ((BitmapDrawable) booksImage.getDrawable()).getBitmap(); imageView.setImageBitmap(bitmap); AlertDialog dialog = new AlertDialog.Builder(mContext).setView(viewInformation).show(); return true; }); } @Override public int getItemCount() { return mList.size(); } } class ViewHodel extends RecyclerView.ViewHolder { private TextView txtName; public ViewHodel(@NonNull View itemView) { super(itemView); txtName = itemView.findViewById(R.id.text_view); } }
然后我们根据源码来看一下:
RecyclerviewAdapter
并且继承于RecyclerView.Adapter<RecyclerView.ViewHolder>
Context
onCreateViewHolder
方法。onBindViewHolder
方法了。这边我注册了部分的点击事件。getItemCount();
的方法了。他的主要用途返回我们的items数量。看一下效果:
这篇可能不太对因为个人工作问题,在开发中不会去使用任何依赖。所以这篇只是拓展视野而已。??