Recycle
view adapter
The RecyclerView widget is a more advanced and flexible version of ListView. This
widget is a container for displaying large data sets that can be scrolled very
efficiently by maintaining a limited number of views. Use the RecyclerViewwidget
when you have data collections whose elements change at runtime based on user
action or network events.
·
Layout managers for
positioning items
·
Default animations for
common item operations, such as removal or addition of items
You also have the
flexibility to define custom layout managers and animations for RecyclerView widgets.
RecyclerViewFragment.class
public class
RecyclerViewFragment extends Fragment {
private static final String TAG =
"RecyclerViewFragment";
private static final String
KEY_LAYOUT_MANAGER = "layoutManager";
private static final int SPAN_COUNT = 2;
private static final int DATASET_COUNT =
60;
private enum LayoutManagerType {
GRID_LAYOUT_MANAGER,
LINEAR_LAYOUT_MANAGER
}
protected LayoutManagerType
mCurrentLayoutManagerType;
protected RadioButton
mLinearLayoutRadioButton;
protected RadioButton
mGridLayoutRadioButton;
protected RecyclerView mRecyclerView;
protected CustomAdapter mAdapter;
protected RecyclerView.LayoutManager
mLayoutManager;
protected String[] mDataset;
@Override
public void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
// Initialize dataset, this data would
usually come from a local content provider or
// remote server.
initDataset();
}
@Override
public View onCreateView(LayoutInflater
inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView =
inflater.inflate(R.layout.recycler_view_frag, container, false);
rootView.setTag(TAG);
//
BEGIN_INCLUDE(initializeRecyclerView)
mRecyclerView = (RecyclerView)
rootView.findViewById(R.id.recyclerView);
// LinearLayoutManager is used here,
this will layout the elements in a similar fashion
// to the way ListView would layout
elements. The RecyclerView.LayoutManager defines how
// elements are laid out.
mLayoutManager = new
LinearLayoutManager(getActivity());
mCurrentLayoutManagerType =
LayoutManagerType.LINEAR_LAYOUT_MANAGER;
if (savedInstanceState != null) {
// Restore saved layout manager
type.
mCurrentLayoutManagerType =
(LayoutManagerType) savedInstanceState
.getSerializable(KEY_LAYOUT_MANAGER);
}
setRecyclerViewLayoutManager(mCurrentLayoutManagerType);
mAdapter = new CustomAdapter(mDataset);
// Set CustomAdapter as the adapter for
RecyclerView.
mRecyclerView.setAdapter(mAdapter);
// END_INCLUDE(initializeRecyclerView)
mLinearLayoutRadioButton =
(RadioButton) rootView.findViewById(R.id.linear_layout_rb);
mLinearLayoutRadioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER);
}
});
mGridLayoutRadioButton = (RadioButton)
rootView.findViewById(R.id.grid_layout_rb);
mGridLayoutRadioButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setRecyclerViewLayoutManager(LayoutManagerType.GRID_LAYOUT_MANAGER);
}
});
return rootView;
}
/**
* Set RecyclerView's LayoutManager to the
one given.
*
* @param layoutManagerType Type of layout
manager to switch to.
*/
public void
setRecyclerViewLayoutManager(LayoutManagerType layoutManagerType) {
int scrollPosition = 0;
// If a layout manager has already been
set, get current scroll position.
if (mRecyclerView.getLayoutManager() !=
null) {
scrollPosition =
((LinearLayoutManager) mRecyclerView.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
}
switch (layoutManagerType) {
case GRID_LAYOUT_MANAGER:
mLayoutManager = new
GridLayoutManager(getActivity(), SPAN_COUNT);
mCurrentLayoutManagerType =
LayoutManagerType.GRID_LAYOUT_MANAGER;
break;
case LINEAR_LAYOUT_MANAGER:
mLayoutManager = new
LinearLayoutManager(getActivity());
mCurrentLayoutManagerType =
LayoutManagerType.LINEAR_LAYOUT_MANAGER;
break;
default:
mLayoutManager = new
LinearLayoutManager(getActivity());
mCurrentLayoutManagerType =
LayoutManagerType.LINEAR_LAYOUT_MANAGER;
}
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.scrollToPosition(scrollPosition);
}
@Override
public void onSaveInstanceState(Bundle
savedInstanceState) {
// Save currently selected layout manager.
savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER,
mCurrentLayoutManagerType);
super.onSaveInstanceState(savedInstanceState);
}
/**
* Generates Strings for RecyclerView's
adapter. This data would usually come
* from a local content provider or remote
server.
*/
private void initDataset() {
mDataset = new String[DATASET_COUNT];
for (int i = 0; i < DATASET_COUNT;
i++) {
mDataset[i] = "This is element
#" + i;
}
}
}
CustomAdapter.java
public class
CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private static final String TAG =
"CustomAdapter";
private String[] mDataSet;
//
BEGIN_INCLUDE(recyclerViewSampleViewHolder)
/**
* Provide a reference to the type of views
that you are using (custom ViewHolder)
*/
public static class ViewHolder extends
RecyclerView.ViewHolder {
private final TextView textView;
public ViewHolder(View v) {
super(v);
// Define click listener for the
ViewHolder's View.
v.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "Element
" + getPosition() + " clicked.");
}
});
textView = (TextView)
v.findViewById(R.id.textView);
}
public TextView getTextView() {
return textView;
}
}
// END_INCLUDE(recyclerViewSampleViewHolder)
/**
* Initialize the dataset of the Adapter.
*
* @param dataSet String[] containing the
data to populate views to be used by RecyclerView.
*/
public CustomAdapter(String[] dataSet) {
mDataSet = dataSet;
}
//
BEGIN_INCLUDE(recyclerViewOnCreateViewHolder)
// Create new views (invoked by the layout
manager)
@Override
public ViewHolder
onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// Create a new view.
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.text_row_item, viewGroup, false);
return new ViewHolder(v);
}
//
END_INCLUDE(recyclerViewOnCreateViewHolder)
//
BEGIN_INCLUDE(recyclerViewOnBindViewHolder)
//
Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder
viewHolder, final int position) {
Log.d(TAG, "Element " +
position + " set.");
// Get element from your dataset at
this position and replace the contents of the view
// with that element
viewHolder.getTextView().setText(mDataSet[position]);
}
//
END_INCLUDE(recyclerViewOnBindViewHolder)
// Return the size of your dataset (invoked
by the layout manager)
@Override
public int getItemCount() {
return mDataSet.length;
}
}
public class
MainActivity extends SampleActivityBase {
public static final String TAG =
"MainActivity";
// Whether the Log Fragment is currently
shown
private boolean mLogShown;
@Override
protected void onCreate(Bundle
savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
FragmentTransaction transaction =
getSupportFragmentManager().beginTransaction();
RecyclerViewFragment fragment = new
RecyclerViewFragment();
transaction.replace(R.id.sample_content_fragment,
fragment);
transaction.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu
menu) {
getMenuInflater().inflate(R.menu.main,
menu);
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu
menu) {
MenuItem logToggle =
menu.findItem(R.id.menu_toggle_log);
logToggle.setVisible(findViewById(R.id.sample_output) instanceof
ViewAnimator);
logToggle.setTitle(mLogShown ?
R.string.sample_hide_log : R.string.sample_show_log);
return
super.onPrepareOptionsMenu(menu);
}
@Override
public boolean
onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_toggle_log:
mLogShown = !mLogShown;
ViewAnimator output =
(ViewAnimator) findViewById(R.id.sample_output);
if (mLogShown) {
output.setDisplayedChild(1);
} else {
output.setDisplayedChild(0);
}
supportInvalidateOptionsMenu();
return true;
}
return
super.onOptionsItemSelected(item);
}
/** Create a chain of targets that will
receive log data */
@Override
public void initializeLogging() {
// Wraps Android's native log
framework.
LogWrapper logWrapper = new
LogWrapper();
// Using Log, front-end to the logging
chain, emulates android.util.log method signatures.
Log.setLogNode(logWrapper);
// Filter strips out everything except
the message text.
MessageOnlyLogFilter msgFilter = new
MessageOnlyLogFilter();
logWrapper.setNext(msgFilter);
// On screen logging via a fragment
with a TextView.
LogFragment logFragment = (LogFragment)
getSupportFragmentManager()
.findFragmentById(R.id.log_fragment);
msgFilter.setNext(logFragment.getLogView());
Log.i(TAG, "Ready");
}
}
Activitymain.xml
<!--
Copyright 2013 The Android Open Source
Project
Licensed under the Apache License, Version
2.0 (the "License");
you may not use this file except in
compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed
to in writing, software
distributed under the License is distributed
on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied.
See the License for the specific language
governing permissions and
limitations under the License.
-->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/sample_main_layout">
<ViewAnimator
android:id="@+id/sample_output"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1">
<ScrollView
style="@style/Widget.SampleMessageTile"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
style="@style/Widget.SampleMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="@dimen/horizontal_page_margin"
android:paddingRight="@dimen/horizontal_page_margin"
android:paddingTop="@dimen/vertical_page_margin"
android:paddingBottom="@dimen/vertical_page_margin"
android:text="@string/intro_message" />
</ScrollView>
<fragment
android:name="com.example.android.common.logger.LogFragment"
android:id="@+id/log_fragment"
android:layoout_width="match_parent"
android:layout_height="match_parent" />
</ViewAnimator>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:backgrund="@android:color/darker_gray" />
<FrameLayout
android:id="@+id/sample_content_fragment"
android:layout_weight="2"
android:layout_width="match_parent"
android:layout_height="0px"
/>
</LinearLayout>
Recycle_view_fragment.xml
<?xml
version="1.0" encoding="UTF-8"?>
<!--
Copyright 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0
(the "License");
you may not use this file except in compliance
with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to
in writing, software
distributed under the License is distributed
on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied.
See the License for the specific language
governing permissions and
limitations under the License.
-->
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:checkedButton="@+id/linear_layout_rb">
<RadioButton
android:id="@+id/linear_layout_rb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/linear_layout_manager"/>
<RadioButton
android:id="@+id/grid_layout_rb"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/grid_layout_manager"/>
</RadioGroup>
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Text_row_item.xml
<?xml
version="1.0" encoding="utf-8"?>
<!--
Copyright 2014 The Android Open Source Project
Licensed under the Apache License, Version 2.0
(the "License");
you may not use this file except in compliance
with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to
in writing, software
distributed under the License is distributed
on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
express or implied.
See the License for the specific language
governing permissions and
limitations under the License.
-->
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="@dimen/list_item_height"
android:layout_marginLeft="@dimen/margin_medium"
android:layout_marginRight="@dimen/margin_medium"
android:gravity="center_vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/element_text"/>
</FrameLayout>
Comments
Post a Comment