我正在尝试用RecyclerView替换ListView。我为它设置的点击监听器看起来像这样(这是来自Activity):
//Road Trip selection
roadTripList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
RoadTrip trip = trips.get(i);
Intent intent= new Intent(RoadTripListActivity.this, RoadTripActivity.class);
intent.putExtra("startLocation", trip.getStart());
intent.putExtra("endLocation", trip.getEnd());
intent.putExtra("routeType", trip.getType());
setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
finish();
overridePendingTransition(R.anim.in_right, R.anim.out_left);
}
});
//Road Trip deletion
roadTripList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
new AlertDialog.Builder(RoadTripListActivity.this)
.setTitle("Delete this Road Trip?")
.setMessage("Are you sure you want to delete this road trip from your saved trips?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
trips.remove(i);
tripStrings.remove(i);
tinyDB.putListString("roadtrips", tripStrings);
//roadTripList.setAdapter(adapter);
adapter.updateAdapter(trips);
}
}).setNegativeButton("Cancel", null)
.create().show();
return true;
}
});
适配器看起来像这样:
public class RoadTripListAdapter extends RecyclerView.Adapter<RoadTripListAdapter.ViewHolder> {
protected ArrayList<RoadTrip> trips;
protected Context context;
public RoadTripListAdapter(Context context, ArrayList<RoadTrip> trips) {
this.context = context;
this.trips = trips;
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView startTextView;
private final TextView endTextView;
private final ImageView imageView;
private final LinearLayout itemLayout;
public ViewHolder(View v) {
super(v);
startTextView = (TextView) v.findViewById(R.id.roadtrip_list_start);
endTextView = (TextView) v.findViewById(R.id.roadtrip_list_end);
imageView = (ImageView) v.findViewById(R.id.roadtrip_list_icon);
itemLayout = (LinearLayout) v.findViewById(R.id.roadtrip_list_item_layout);
}
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
//Get the corresponding step
final RoadTrip trip = trips.get(position);
holder.startTextView.setText(trip.getStart());
holder.endTextView.setText(trip.getEnd());
if (trip.getType().equals(SearchType.walking.name())) {
holder.imageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_directions_walk_24dp));
} else {
holder.imageView.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.ic_directions_car_24dp));
}
}
@Override
public int getItemCount() {
return trips.size();
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.road_trip_list_item, parent, false);
return new ViewHolder(v);
}
public void updateAdapter(ArrayList<RoadTrip> trips) {
this.trips = trips;
this.notifyDataSetChanged();
}
}
列表项xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/roadtrip_list_item_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="@+id/roadtrip_list_icon"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center_vertical"
android:layout_margin="5dp"
android:src="@drawable/ic_directions_car_24dp"/>
<LinearLayout
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:id="@+id/roadtrip_list_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@color/black"
android:text="Start: "/>
<TextView
android:id="@+id/roadtrip_list_end"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:textColor="@color/black"
android:text="End: "/>
</LinearLayout>
</LinearLayout>
如何设置RecyclerView的等效项?我在这个主题上找到的所有东西都说要在适配器里面设置它,但在这种情况下这不起作用......有没有办法在Activity中设置它?
答案 0 :(得分:0)
在onBindViewHolder
中,像这样添加OnClickListener
和OnLongClickListener
:
itemLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RoadTrip trip = trips.get(position);
Intent intent= new Intent(RoadTripListActivity.this, RoadTripActivity.class);
intent.putExtra("startLocation", trip.getStart());
intent.putExtra("endLocation", trip.getEnd());
intent.putExtra("routeType", trip.getType());
setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
finish();
overridePendingTransition(R.anim.in_right, R.anim.out_left);
}
});
//Road Trip deletion
itemLayout.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
new AlertDialog.Builder(RoadTripListActivity.this)
.setTitle("Delete this Road Trip?")
.setMessage("Are you sure you want to delete this road trip from your saved trips?")
.setCancelable(true)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
trips.remove(position);
tripStrings.remove(position);
tinyDB.putListString("roadtrips", tripStrings);
notifyItemRemoved(position);
notifyItemRangeChanged(position, trips.size());
}
}).setNegativeButton("Cancel", null)
.create().show();
return true;
}
});
答案 1 :(得分:0)
我明白了:
((Activity) context).setResult(RoadTripActivity.ROADTRIP_LIST_INTENT_RESULT, intent);
((Activity) context).finish();
((Activity) context).overridePendingTransition(R.anim.in_right, R.anim.out_left);
我一直使用getApplicationContext作为适配器的上下文传递,因此我将其更改为
adapter = new RoadTripListAdapter(this, trips);
在活动中。
答案 2 :(得分:0)
**RecyclerView On Item Click Listner**
**Interface :**
public interface MyClickListener
{
void onClick(View view, int adapterPosition);
}
**Make class RecyclerTouchListener :**
public class RecyclerTouchListener implements RecyclerView.OnItemTouchListener{
private ClickListener clicklistener;
private GestureDetector gestureDetector;
public RecyclerTouchListener(Context context, final RecyclerView recycleView, final ClickListener clicklistener){
this.clicklistener=clicklistener;
gestureDetector=new GestureDetector(context,new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
/* @Override
public void onLongPress(MotionEvent e) {
View child=recycleView.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null){
clicklistener.onLongClick(child,recycleView.getChildAdapterPosition(child));
}
}*/
});
}
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child=rv.findChildViewUnder(e.getX(),e.getY());
if(child!=null && clicklistener!=null && gestureDetector.onTouchEvent(e)){
clicklistener.onClick(child,rv.getChildAdapterPosition(child));
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
**Make Event in Activity Or Fragment**
recyclerview_country.addOnItemTouchListener(new RecyclerTouchListener(RegisterActivity.this,
recyclerview_country, new MyClickListener()
{
@Override
public void onClick(View view, final int position)
{
}
}));
**Device Contact For All Phone**
<uses-permission android:name="android.permission.READ_CONTACTS"/>
**activity_main**
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@+id/lvContacts"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
**raw_contact_item**
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:padding="3dp"
android:layout_height="match_parent" >
<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Bob Marley"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textStyle="bold" />
<TextView
android:id="@+id/tvPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/tvName"
android:text="(626) 336-5889"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/tvEmail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#575757"
android:layout_alignBaseline="@+id/tvPhone"
android:layout_alignBottom="@+id/tvPhone"
android:paddingLeft="5dp"
android:layout_toRightOf="@+id/tvPhone"
android:layout_alignParentRight="true"
android:text="bob@fake.com"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
**MainActivity**
ArrayList<Contact> listContacts;
ListView lvContacts;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listContacts = new ContactFetcher(this).fetchAll();
lvContacts = (ListView) findViewById(R.id.lvContacts);
ContactsAdapter adapterContacts = new ContactsAdapter(this, listContacts);
lvContacts.setAdapter(adapterContacts);
}
**ContactsAdapter**
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ContactsAdapter extends ArrayAdapter<Contact> {
public ContactsAdapter(Context context, ArrayList<Contact> contacts) {
super(context, 0, contacts);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item
Contact contact = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
View view = convertView;
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
view = inflater.inflate(R.layout.adapter_contact_item, parent, false);
}
// Populate the data into the template view using the data object
TextView tvName = (TextView) view.findViewById(R.id.tvName);
TextView tvEmail = (TextView) view.findViewById(R.id.tvEmail);
TextView tvPhone = (TextView) view.findViewById(R.id.tvPhone);
tvName.setText(contact.name);
tvEmail.setText("");
tvPhone.setText("");
if (contact.emails.size() > 0 && contact.emails.get(0) != null) {
tvEmail.setText(contact.emails.get(0).address);
}
if (contact.numbers.size() > 0 && contact.numbers.get(0) != null) {
tvPhone.setText(contact.numbers.get(0).number);
}
return view;
}
}
**ContactPhone**
public class ContactPhone {
public String number;
public String type;
public ContactPhone(String number, String type) {
this.number = number;
this.type = type;
}
}
**ContactFetcher**
import android.content.Context;
import android.database.Cursor;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.support.v4.content.CursorLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
// new ContactFetcher(this).fetchAll();
public class ContactFetcher {
private final Context context;
public ContactFetcher(Context c) {
this.context = c;
}
public ArrayList<Contact> fetchAll() {
String[] projectionFields = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
ArrayList<Contact> listContacts = new ArrayList<>();
CursorLoader cursorLoader = new CursorLoader(context,
ContactsContract.Contacts.CONTENT_URI,
projectionFields, // the columns to retrieve
null, // the selection criteria (none)
null, // the selection args (none)
null // the sort order (default)
);
Cursor c = cursorLoader.loadInBackground();
final Map<String, Contact> contactsMap = new HashMap<>(c.getCount());
if (c.moveToFirst()) {
int idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);
int nameIndex = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
do {
String contactId = c.getString(idIndex);
String contactDisplayName = c.getString(nameIndex);
Contact contact = new Contact(contactId, contactDisplayName);
contactsMap.put(contactId, contact);
listContacts.add(contact);
} while (c.moveToNext());
}
c.close();
matchContactNumbers(contactsMap);
matchContactEmails(contactsMap);
return listContacts;
}
public void matchContactNumbers(Map<String, Contact> contactsMap) {
// Get numbers
final String[] numberProjection = new String[]{
Phone.NUMBER,
Phone.TYPE,
Phone.CONTACT_ID,
};
Cursor phone = new CursorLoader(context,
Phone.CONTENT_URI,
numberProjection,
null,
null,
null).loadInBackground();
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);
final int contactIdColumnIndex = phone.getColumnIndex(Phone.CONTACT_ID);
while (!phone.isAfterLast()) {
final String number = phone.getString(contactNumberColumnIndex);
final String contactId = phone.getString(contactIdColumnIndex);
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
final int type = phone.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
CharSequence phoneType = Phone.getTypeLabel(context.getResources(), type, customLabel);
contact.addNumber(number, phoneType.toString());
phone.moveToNext();
}
}
phone.close();
}
public void matchContactEmails(Map<String, Contact> contactsMap) {
// Get email
final String[] emailProjection = new String[]{
Email.DATA,
Email.TYPE,
Email.CONTACT_ID,
};
Cursor email = new CursorLoader(context,
Email.CONTENT_URI,
emailProjection,
null,
null,
null).loadInBackground();
if (email.moveToFirst()) {
final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);
final int contactIdColumnsIndex = email.getColumnIndex(Email.CONTACT_ID);
while (!email.isAfterLast()) {
final String address = email.getString(contactEmailColumnIndex);
final String contactId = email.getString(contactIdColumnsIndex);
final int type = email.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
CharSequence emailType = Email.getTypeLabel(context.getResources(), type, customLabel);
contact.addEmail(address, emailType.toString());
email.moveToNext();
}
}
email.close();
}
}
**ContactEmail**
public class ContactEmail {
public String address;
public String type;
public ContactEmail(String address, String type) {
this.address = address;
this.type = type;
}
}
**Contact**
import java.util.ArrayList;
public class Contact {
public String id;
public String name;
public ArrayList<ContactEmail> emails;
public ArrayList<ContactPhone> numbers;
public Contact(String id, String name) {
this.id = id;
this.name = name;
this.emails = new ArrayList<ContactEmail>();
this.numbers = new ArrayList<ContactPhone>();
}
@Override
public String toString() {
String result = name;
if (numbers.size() > 0) {
ContactPhone number = numbers.get(0);
result += " (" + number.number + " - " + number.type + ")";
}
if (emails.size() > 0) {
ContactEmail email = emails.get(0);
result += " [" + email.address + " - " + email.type + "]";
}
return result;
}
public void addEmail(String address, String type) {
emails.add(new ContactEmail(address, type));
}
public void addNumber(String number, String type) {
numbers.add(new ContactPhone(number, type));
}
}