1 /* 2 * Copyright (C) 2015 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.example.android.support.design.widget; 18 19 import android.content.Context; 20 import android.util.TypedValue; 21 import android.view.LayoutInflater; 22 import android.view.ViewGroup; 23 import android.widget.TextView; 24 25 import androidx.recyclerview.widget.RecyclerView; 26 27 import com.example.android.support.design.R; 28 29 import java.util.ArrayList; 30 import java.util.Collections; 31 32 public class SimpleStringRecyclerViewAdapter 33 extends RecyclerView.Adapter<SimpleStringRecyclerViewAdapter.ViewHolder> { 34 35 private int mBackground; 36 37 private ArrayList<String> mValues; 38 39 public static class ViewHolder extends RecyclerView.ViewHolder { 40 public String mBoundString; 41 public TextView mTextView; 42 ViewHolder(TextView v)43 public ViewHolder(TextView v) { 44 super(v); 45 mTextView = v; 46 } 47 48 @Override toString()49 public String toString() { 50 return super.toString() + " '" + mTextView.getText(); 51 } 52 } 53 getValueAt(int position)54 public String getValueAt(int position) { 55 return mValues.get(position); 56 } 57 SimpleStringRecyclerViewAdapter(Context context, String[] strings)58 public SimpleStringRecyclerViewAdapter(Context context, String[] strings) { 59 TypedValue val = new TypedValue(); 60 if (context.getTheme() != null) { 61 context.getTheme().resolveAttribute(R.attr.selectableItemBackground, val, true); 62 } 63 mBackground = val.resourceId; 64 mValues = new ArrayList<>(); 65 Collections.addAll(mValues, strings); 66 } 67 68 @Override onCreateViewHolder(ViewGroup parent, int viewType)69 public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 70 TextView textView = (TextView) LayoutInflater.from(parent.getContext()) 71 .inflate(android.R.layout.simple_list_item_1, parent, false); 72 textView.setBackgroundResource(mBackground); 73 return new ViewHolder(textView); 74 } 75 76 @Override onBindViewHolder(ViewHolder holder, int position)77 public void onBindViewHolder(ViewHolder holder, int position) { 78 holder.mBoundString = mValues.get(position); 79 holder.mTextView.setText(position + ": " + mValues.get(position)); 80 } 81 82 @Override getItemCount()83 public int getItemCount() { 84 return mValues.size(); 85 } 86 } 87