text RecyclerView
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text RecyclerView相关的知识,希望对你有一定的参考价值。
package com.example.android.recyclerview;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
/**
* We couldn't come up with a good name for this class. Then, we realized
* that this lesson is about RecyclerView.
*
* RecyclerView... Recycling... Saving the planet? Being green? Anyone?
* #crickets
*
* Avoid unnecessary garbage collection by using RecyclerView and ViewHolders.
*
* If you don't like our puns, we named this Adapter GreenAdapter because its
* contents are green.
*/
// @@4
public class GreenAdapter extends RecyclerView.Adapter<GreenAdapter.NumberViewHolder> {
private static final String TAG = GreenAdapter.class.getSimpleName();
// Create a final private ListItemClickListener called mOnClickListener
/*
* An on-click handler that we've defined to make it easy for an Activity to interface with
* our RecyclerView
*/
final private ListItemClickListener mOnClickListener;
/*
* The number of ViewHolders that have been created. Typically, you can figure out how many
* there should be by determining how many list items fit on your screen at once and add 2 to 4
* to that number. That isn't the exact formula, but will give you an idea of how many
* ViewHolders have been created to display any given RecyclerView.
*
* Here's some ASCII art to hopefully help you understand:
*
* ViewHolders on screen:
*
* *-----------------------------*
* | ViewHolder index: 0 |
* *-----------------------------*
* | ViewHolder index: 1 |
* *-----------------------------*
* | ViewHolder index: 2 |
* *-----------------------------*
* | ViewHolder index: 3 |
* *-----------------------------*
* | ViewHolder index: 4 |
* *-----------------------------*
* | ViewHolder index: 5 |
* *-----------------------------*
* | ViewHolder index: 6 |
* *-----------------------------*
* | ViewHolder index: 7 |
* *-----------------------------*
*
* Extra ViewHolders (off screen)
*
* *-----------------------------*
* | ViewHolder index: 8 |
* *-----------------------------*
* | ViewHolder index: 9 |
* *-----------------------------*
* | ViewHolder index: 10|
* *-----------------------------*
* | ViewHolder index: 11|
* *-----------------------------*
*
* Total number of ViewHolders = 11
*/
private static int viewHolderCount;
private int mNumberItems;
// Add an interface called ListItemClickListener
// Within that interface, define a void method called onListItemClick that takes an int as a parameter
/**
* The interface that receives onClick messages.
*/
public interface ListItemClickListener {
void onListItemClick(int clickedItemIndex);
}
// Add a ListItemClickListener as a parameter to the constructor and store it in mOnClickListener
/**
* Constructor for GreenAdapter that accepts a number of items to display and the specification
* for the ListItemClickListener.
*
* @param numberOfItems Number of items to display in list
* @param listener Listener for list item clicks
*/
public GreenAdapter(int numberOfItems, ListItemClickListener listener) {
mNumberItems = numberOfItems;
mOnClickListener = listener;
viewHolderCount = 0;
}
/**
*
* This gets called when each new ViewHolder is created. This happens when the RecyclerView
* is laid out. Enough ViewHolders will be created to fill the screen and allow for scrolling.
*
* @param viewGroup The ViewGroup that these ViewHolders are contained within.
* @param viewType If your RecyclerView has more than one type of item (which ours doesn't) you
* can use this viewType integer to provide a different layout. See
* {@link android.support.v7.widget.RecyclerView.Adapter#getItemViewType(int)}
* for more details.
* @return A new NumberViewHolder that holds the View for each list item
*/
// @@6
@Override
public NumberViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
Context context = viewGroup.getContext();
int layoutIdForListItem = R.layout.number_list_item;
LayoutInflater inflater = LayoutInflater.from(context);
boolean shouldAttachToParentImmediately = false;
View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
NumberViewHolder viewHolder = new NumberViewHolder(view);
viewHolder.viewHolderIndex.setText("ViewHolder index: " + viewHolderCount);
int backgroundColorForViewHolder = ColorUtils
.getViewHolderBackgroundColorFromInstance(context, viewHolderCount);
viewHolder.itemView.setBackgroundColor(backgroundColorForViewHolder);
viewHolderCount++;
Log.d(TAG, "onCreateViewHolder: number of ViewHolders created: "
+ viewHolderCount);
return viewHolder;
}
/**
* OnBindViewHolder is called by the RecyclerView to display the data at the specified
* position. In this method, we update the contents of the ViewHolder to display the correct
* indices in the list for this particular position, using the "position" argument that is conveniently
* passed into us.
*
* @param holder The ViewHolder which should be updated to represent the contents of the
* item at the given position in the data set.
* @param position The position of the item within the adapter's data set.
*/
@Override
public void onBindViewHolder(NumberViewHolder holder, int position) {
Log.d(TAG, "#" + position);
holder.bind(position);
}
/**
* This method simply returns the number of items to display. It is used behind the scenes
* to help layout our Views and for animations.
*
* @return The number of items available
*/
@Override
public int getItemCount() {
return mNumberItems;
}
// COMPLETED (5) Implement OnClickListener in the NumberViewHolder class
/**
* Cache of the children views for a list item.
*/
// @@5
class NumberViewHolder extends RecyclerView.ViewHolder
implements OnClickListener {
// Will display the position in the list, ie 0 through getItemCount() - 1
TextView listItemNumberView;
// Will display which ViewHolder is displaying this data
TextView viewHolderIndex;
/**
* Constructor for our ViewHolder. Within this constructor, we get a reference to our
* TextViews and set an onClickListener to listen for clicks. Those will be handled in the
* onClick method below.
* @param itemView The View that you inflated in
* {@link GreenAdapter#onCreateViewHolder(ViewGroup, int)}
*/
public NumberViewHolder(View itemView) {
super(itemView);
listItemNumberView = (TextView) itemView.findViewById(R.id.tv_item_number);
viewHolderIndex = (TextView) itemView.findViewById(R.id.tv_view_holder_instance);
// COMPLETED (7) Call setOnClickListener on the View passed into the constructor (use 'this' as the OnClickListener)
itemView.setOnClickListener(this);
}
/**
* A method we wrote for convenience. This method will take an integer as input and
* use that integer to display the appropriate text within a list item.
* @param listIndex Position of the item in the list
*/
void bind(int listIndex) {
listItemNumberView.setText(String.valueOf(listIndex));
}
// COMPLETED (6) Override onClick, passing the clicked item's position (getAdapterPosition()) to mOnClickListener via its onListItemClick method
/**
* Called whenever a user clicks on an item in the list.
* @param v The View that was clicked
*/
@Override
public void onClick(View v) {
int clickedPosition = getAdapterPosition();
mOnClickListener.onListItemClick(clickedPosition);
}
}
}
package com.example.android.recyclerview;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
// COMPLETED (8) Implement GreenAdapter.ListItemClickListener from the MainActivity
public class MainActivity extends AppCompatActivity
implements GreenAdapter.ListItemClickListener {
private static final int NUM_LIST_ITEMS = 100;
/*
* References to RecyclerView and Adapter to reset the list to its
* "pretty" state when the reset menu item is clicked.
*/
private GreenAdapter mAdapter;
private RecyclerView mNumbersList;
// COMPLETED (9) Create a Toast variable called mToast to store the current Toast
/*
* If we hold a reference to our Toast, we can cancel it (if it's showing)
* to display a new Toast. If we didn't do this, Toasts would be delayed
* in showing up if you clicked many list items in quick succession.
*/
private Toast mToast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* Using findViewById, we get a reference to our RecyclerView from xml. This allows us to
* do things like set the adapter of the RecyclerView and toggle the visibility.
*/
mNumbersList = (RecyclerView) findViewById(R.id.rv_numbers);
/*
* A LinearLayoutManager is responsible for measuring and positioning item views within a
* RecyclerView into a linear list. This means that it can produce either a horizontal or
* vertical list depending on which parameter you pass in to the LinearLayoutManager
* constructor. By default, if you don't specify an orientation, you get a vertical list.
* In our case, we want a vertical list, so we don't need to pass in an orientation flag to
* the LinearLayoutManager constructor.
*
* There are other LayoutManagers available to display your data in uniform grids,
* staggered grids, and more! See the developer documentation for more details.
*/
//@@7
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mNumbersList.setLayoutManager(layoutManager);
/*
* Use this setting to improve performance if you know that changes in content do not
* change the child layout size in the RecyclerView
*/
mNumbersList.setHasFixedSize(true);
// COMPLETED (13) Pass in this as the ListItemClickListener to the GreenAdapter constructor
/*
* The GreenAdapter is responsible for displaying each item in the list.
*/
mAdapter = new GreenAdapter(NUM_LIST_ITEMS, this);
mNumbersList.setAdapter(mAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
/*
* When you click the reset menu item, we want to start all over
* and display the pretty gradient again. There are a few similar
* ways of doing this, with this one being the simplest of those
* ways. (in our humble opinion)
*/
case R.id.action_refresh:
// COMPLETED (14) Pass in this as the ListItemClickListener to the GreenAdapter constructor
mAdapter = new GreenAdapter(NUM_LIST_ITEMS, this);
mNumbersList.setAdapter(mAdapter);
return true;
}
return super.onOptionsItemSelected(item);
}
// COMPLETED (10) Override ListItemClickListener's onListItemClick method
/**
* This is where we receive our callback from
* {@link com.example.android.recyclerview.GreenAdapter.ListItemClickListener}
*
* This callback is invoked when you click on an item in the list.
*
* @param clickedItemIndex Index in the list of the item that was clicked.
*/
@Override
public void onListItemClick(int clickedItemIndex) {
// COMPLETED (11) In the beginning of the method, cancel the Toast if it isn't null
/*
* Even if a Toast isn't showing, it's okay to cancel it. Doing so
* ensures that our new Toast will show immediately, rather than
* being delayed while other pending Toasts are shown.
*
* Comment out these three lines, run the app, and click on a bunch of
* different items if you're not sure what I'm talking about.
*/
// @@8
if (mToast != null) {
mToast.cancel();
}
// COMPLETED (12) Show a Toast when an item is clicked, displaying that item number that was clicked
/*
* Create a Toast and store it in our Toast field.
* The Toast that shows up will have a message similar to the following:
*
* Item #42 clicked.
*/
String toastMessage = "Item #" + clickedItemIndex + " clicked.";
mToast = Toast.makeText(this, toastMessage, Toast.LENGTH_LONG);
mToast.show();
}
}
<?xml version="1.0" encoding="utf-8"?>
<!-- @@3 -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<TextView
android:id="@+id/tv_item_number"
style="@style/TextAppearance.AppCompat.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|start"
android:fontFamily="monospace"
android:textSize="42sp"
tools:text="#42" />
<TextView
android:id="@+id/tv_view_holder_instance"
style="@style/TextAppearance.AppCompat.Title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|end"
android:fontFamily="monospace"
android:textColor="#000"
tools:text="ViewHolder instance: 7" />
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- @@2 Add the Recycler View -->
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_numbers"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
applicationId "com.example.android.recyclerview"
minSdkVersion 10
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:25.1.0'
// @@1 Adding REcyclerView Dependency
compile 'com.android.support:recyclerview-v7:25.1.0'
}
## Steps to implement RecyclerView
1. Add recyclerView dependency in build.gradle file
2. Add RecyclerView in the layout
3. Create a list_item.xml file and craft the layout
4. Create a Adapter class that extends from RecyclerView.Adapter<GreenAdapter.NumberViewHolder>
5. Create a inner class NumberViewHolder extends RecyclerView.ViewHolder and implements OnClickListener
6. Implement onCreateViewHolder, obbindViewHolder and getItemCount methods
7. Wire it all up in the MainActivity
8. Write code to avoid queuing of toast message
以上是关于text RecyclerView的主要内容,如果未能解决你的问题,请参考以下文章
text Android的瀑布流优化,解决Recyclerview展示大批量图片时项目自动切换,闪烁,空白等问题
多种viewType的recyclerView使用MultipleItemRvAdapter示例