Я хотел бы удалить поведение щелчка из этого действия. На прилагаемом снимке экрана, если вы коснетесь / щелкните имя контакта, приложение выйдет из строя (кнопка редактирования работает правильно). Однако я действительно не хочу исправлять эту ошибку, я бы предпочел удалить поведение касания / щелчка в этой области. Мне также нужно сохранить возможность выбора контакта в действии добавления контактов. Я прикрепил снимок экрана, «Мои контакты», «Добавить контакты» и адаптер. Что еще нужно?
Скриншот ! [введите описание изображения здесь
Активность в моих контактах
public class MyContactsActivity extends BaseAppCompatActivity {
private static final String TAG = "MyContactsActivity";
private final int PICK_CONTACT_REQUEST = 9001;
private Toolbar mToolbar;
private IndexFastScrollRecyclerView recyclerContacts;
private ContactsAdapter mAdapter;
private ArrayList<ContactInfo> mLegalContacts = new ArrayList<>();
public static void startActivity(Context context) {
Intent intent = new Intent(context, MyContactsActivity.class);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_contacts);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
recyclerContacts = (IndexFastScrollRecyclerView) findViewById(R.id.contact_recycler);
//recyclerContacts.setIndexTextSize(12);
recyclerContacts.setIndexBarTextColor(String.format("#%X", ContextCompat.getColor(this, R.color.mainColor)));
recyclerContacts.setIndexBarColor(String.format("#%X", ContextCompat.getColor(this, R.color.white)));
recyclerContacts.setIndexbarMargin(0);
recyclerContacts.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerContacts.setLayoutManager(layoutManager);
recyclerContacts.setItemAnimator(new DefaultItemAnimator());
checkAndAskPermission(Manifest.permission.READ_CONTACTS, LegalEqualizerApp.READ_CONTACTS_REQUEST_CODE, permissionDelegate);
}
private Delegate.PermissionDelegate permissionDelegate = new Delegate.PermissionDelegate() {
@Override
public void granted(int requestCode) {
super.granted(requestCode);
mLegalContacts = getLegalContacts();
mAdapter = new ContactsAdapter(mLegalContacts, null);
recyclerContacts.setAdapter(mAdapter);
}
@Override
public void denied(int requestCode) {
super.denied(requestCode);
showDialog(getString(R.string.title_permission), getString(R.string.permission_contact));
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.edit, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
case R.id.edit:
AddContactsActivity.startActivityForResult(MyContactsActivity.this, PICK_CONTACT_REQUEST);
break;
}
return super.onOptionsItemSelected(item);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_CONTACT_REQUEST && resultCode == RESULT_OK) {
checkAndAskPermission(Manifest.permission.READ_CONTACTS, LegalEqualizerApp.READ_CONTACTS_REQUEST_CODE, permissionDelegate);
}
}
private ArrayList<ContactInfo> getLegalContacts() {
showProgress(getString(R.string.please_wait));
ArrayList<ContactInfo> legalContacts = new ArrayList<>();
List<String> contacts = loadLegalContacts();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber != null) {
phoneNumber = phoneNumber.replace("(", "");
phoneNumber = phoneNumber.replace(")", "");
phoneNumber = phoneNumber.replace("-", "");
phoneNumber = phoneNumber.replace(" ", "");
phoneNumber = phoneNumber.replace("+", "");
}
if (contacts.contains(id)) {
ContactInfo info = new ContactInfo(id, name, phoneNumber);
boolean isNew = true;
for (int i = 0; i < legalContacts.size(); i++) {
if (TextUtils.equals(legalContacts.get(i).name, name)) {
isNew = false;
break;
}
}
if (isNew) {
legalContacts.add(info);
}
}
}
phones.close();
hideProgress();
return legalContacts;
}
private List<String> loadLegalContacts() {
List<String> contacts = new ArrayList<>();
Set<String> set = SharedPrefUtil.getInstance().getStringSet("LegalContacts");
if (set != null) {
contacts.addAll(set);
}
return contacts;
}
}
Адаптер контактов Java
public class ContactsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements SectionIndexer {
public interface OnContactListItemActionInterface {
void onContactItemClicked(int position);
}
private static final String TAG = "ContactsAdapter";
private static final int VIEW_TYPE_CONTACT = 1;
private static final int VIEW_TYPE_HEADER = 2;
private OnContactListItemActionInterface clickListener = null;
ArrayList<ContactInfo> mContactsArray = new ArrayList<>();
private ArrayList<Integer> mSectionPositions;
private ArrayList<String> mSelectedIDs = new ArrayList<>();
@Override
public Object[] getSections() {
List<String> sections = new ArrayList<>();
mSectionPositions = new ArrayList<>();
for (int i = 0, size = mContactsArray.size(); i < size; i++) {
if (TextUtils.equals(mContactsArray.get(i).id, "-1")) {
sections.add(String.valueOf(mContactsArray.get(i).name.charAt(0)).toUpperCase());
mSectionPositions.add(i);
}
}
return sections.toArray(new String[0]);
}
public void setOnContactItemListener(OnContactListItemActionInterface listener) {
this.clickListener = listener;
}
@Override
public int getPositionForSection(int sectionIndex) {
return mSectionPositions.get(sectionIndex);
}
@Override
public int getSectionForPosition(int position) {
return 0;
}
public ContactsAdapter(ArrayList<ContactInfo> arrContacts, ArrayList<String> selectedIDs) {
if (selectedIDs == null) {
this.mSelectedIDs = new ArrayList<>();
} else {
this.mSelectedIDs = selectedIDs;
}
this.mContactsArray = convertContacts(arrContacts);
}
private ArrayList<ContactInfo> convertContacts(ArrayList<ContactInfo> arrContacts) {
ArrayList<ContactInfo> newArray = new ArrayList<>();
char currentChar = ' ';
char lastChar = ' ';
if (mSelectedIDs.size() == 0) {
for (int i = 0; i < arrContacts.size(); i++) {
if (arrContacts.get(i).isSelected()) {
mSelectedIDs.add(arrContacts.get(i).id);
}
}
}
for (int i = 0; i < arrContacts.size(); i++) {
if (arrContacts.get(i).name == null) continue;
currentChar = Character.toUpperCase(arrContacts.get(i).name.charAt(0));
if (newArray.size() == 0) {
if (Character.isLetter(currentChar)) {
newArray.add(new ContactInfo("-1", String.valueOf(currentChar), "0"));
lastChar = currentChar;
} else {
newArray.add(new ContactInfo("-1", "#", "0"));
lastChar = '#';
}
} else if (currentChar != lastChar) {
if (Character.isLetter(currentChar)) {
newArray.add(new ContactInfo("-1", String.valueOf(currentChar), "0"));
lastChar = currentChar;
} else {
newArray.add(new ContactInfo("-1", "#", "0"));
lastChar = '#';
}
}
newArray.add(arrContacts.get(i));
}
return newArray;
}
public boolean onClickItem(int position) {
if (!TextUtils.equals(mContactsArray.get(position).id, "-1")) {
if (mContactsArray.get(position).isSelected()) {
mContactsArray.get(position).unSelect();
mSelectedIDs.remove(mContactsArray.get(position).id);
notifyItemChanged(position);
return true;
} else if (mSelectedIDs == null || mSelectedIDs.size() < 5) {
mContactsArray.get(position).select();
mSelectedIDs.add(mContactsArray.get(position).id);
notifyItemChanged(position);
return true;
} else {
return false;
}
} else {
return true;
}
}
public int getSelectedCount() {
if (mSelectedIDs == null || mSelectedIDs.size() == 0) {
return 0;
} else {
return mSelectedIDs.size();
}
}
public ArrayList<String> getSelectedContacts() {
return mSelectedIDs;
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
RecyclerView.ViewHolder viewHolder = null;
if (viewType == VIEW_TYPE_HEADER) {
View view = layoutInflater.inflate(R.layout.contact_header, parent, false);
viewHolder = new HeaderViewHolder(view);
} else {
View view = layoutInflater.inflate(R.layout.contact_list, parent, false);
viewHolder = new ContactViewHolder(view);
}
return viewHolder;
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int position) {
final ContactInfo contact = mContactsArray.get(position);
if (!TextUtils.equals(contact.id, "-1")) {
ContactViewHolder contactViewHolder = (ContactViewHolder) holder;
contactViewHolder.txtName.setText(contact.name);
if (mContactsArray.size()-1 <= position || (mContactsArray.size()-1 > position && TextUtils.equals(mContactsArray.get(position+1).id, "-1"))) {
contactViewHolder.splitView.setVisibility(View.GONE);
} else {
contactViewHolder.splitView.setVisibility(View.VISIBLE);
}
if (contact.isSelected()) {
contactViewHolder.imgChecked.setVisibility(View.VISIBLE);
} else {
contactViewHolder.imgChecked.setVisibility(View.GONE);
}
contactViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clickListener.onContactItemClicked(position);
}
});
} else {
HeaderViewHolder headerViewHolder = (HeaderViewHolder) holder;
headerViewHolder.txtName.setText(contact.name);
}
}
@Override
public int getItemCount() {
return mContactsArray.size();
}
@Override
public int getItemViewType(int position) {
final ContactInfo contact = mContactsArray.get(position);
if (TextUtils.equals(contact.id, "-1")) {
return VIEW_TYPE_HEADER;
} else {
return VIEW_TYPE_CONTACT;
}
}
private static class ContactViewHolder extends RecyclerView.ViewHolder {
private TextView txtName;
private ImageView imgChecked;
private View splitView;
public ContactViewHolder(View itemView) {
super(itemView);
txtName = (TextView) itemView.findViewById(R.id.txt_name);
imgChecked = (ImageView) itemView.findViewById(R.id.checked_image);
splitView = itemView.findViewById(R.id.split_line);
}
}
private static class HeaderViewHolder extends RecyclerView.ViewHolder {
private TextView txtName;
public HeaderViewHolder(View itemView) {
super(itemView);
txtName = (TextView) itemView.findViewById(R.id.txt_name);
}
}
}
Активность добавления контактов
public class AddContactsActivity extends BaseAppCompatActivity {
private static final String TAG = "AddContactsActivity";
private IndexFastScrollRecyclerView recyclerContacts;
private ContactsAdapter mAdapter;
private EditText mEditSearch;
private TextView mTxtCancel;
private ArrayList<ContactInfo> mAllContacts = new ArrayList<>();
private Toolbar mToolbar;
public static void startActivity(Context context, boolean fromNewUser) {
Intent intent = new Intent(context, AddContactsActivity.class);
intent.putExtra("NewUser", fromNewUser);
context.startActivity(intent);
}
public static void startActivityForResult(Activity activity, int requestCode) {
Intent intent = new Intent(activity, AddContactsActivity.class);
intent.putExtra("NewUser", false);
activity.startActivityForResult(intent, requestCode);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_contacts);
mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
// if (!getIntent().getExtras().getBoolean("NewUser")) {
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// }
mEditSearch = (EditText) findViewById(R.id.search_bar);
mTxtCancel = (TextView) findViewById(R.id.txt_cancel);
mEditSearch.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
filterContacts(s);
}
@Override
public void afterTextChanged(Editable s) {
}
});
mEditSearch.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mTxtCancel.setVisibility(View.VISIBLE);
}
}
});
mTxtCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mEditSearch.setText("");
hideSoftKeyboard();
mEditSearch.clearFocus();
mTxtCancel.setVisibility(View.GONE);
}
});
recyclerContacts = (IndexFastScrollRecyclerView) findViewById(R.id.contact_recycler);
//recyclerContacts.setIndexTextSize(12);
recyclerContacts.setIndexBarTextColor(String.format("#%X", ContextCompat.getColor(this, R.color.mainColor)));
recyclerContacts.setIndexBarColor(String.format("#%X", ContextCompat.getColor(this, R.color.white)));
recyclerContacts.setIndexbarMargin(0);
recyclerContacts.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
recyclerContacts.setLayoutManager(layoutManager);
recyclerContacts.setItemAnimator(new DefaultItemAnimator());
// recyclerContacts.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
// @Override
// public boolean onInterceptTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
// return false;
// }
//
// @Override
// public void onTouchEvent(@NonNull RecyclerView rv, @NonNull MotionEvent e) {
//
// }
//
// @Override
// public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
//
// }
// });
// recyclerContacts.addOnItemTouchListener(
// new RecyclerItemClickListener(this, recyclerContacts, new RecyclerItemClickListener.OnItemClickListener() {
//
// @Override
// public void onItemClick(View view, int position) {
// int number = mAdapter.getSelectedCount();
// boolean retValue = mAdapter.onClickItem(position);
// if (!retValue) {
// if (number >= 5) {
// showErrorDialog("No more than 5 contacts can be added.");
// }
// }
// Log.d(TAG, String.valueOf(position));
// }
//
// @Override
// public void onLongItemClick(View view, int position) {
// Log.d(TAG, String.valueOf(position));
// }
// })
// );
checkAndAskPermission(Manifest.permission.READ_CONTACTS, LegalEqualizerApp.READ_CONTACTS_REQUEST_CODE, permissionDelegate);
}
private void contactClickHandler(int pos) {
int number = mAdapter.getSelectedCount();
boolean retValue = mAdapter.onClickItem(pos);
if (!retValue) {
if (number >= 5) {
showErrorDialog("No more than 5 contacts can be added.");
}
}
Log.d(TAG, String.valueOf(pos));
}
private void filterContacts(CharSequence filter) {
if (filter.length() > 0) {
ArrayList<ContactInfo> contacts = new ArrayList<>();
for (int i = 0; i < mAllContacts.size(); i++) {
String name = mAllContacts.get(i).name.toLowerCase();
if (name.contains(filter.toString().toLowerCase())) {
contacts.add(mAllContacts.get(i));
}
}
mAdapter = new ContactsAdapter(contacts, mAdapter.getSelectedContacts());
mAdapter.setOnContactItemListener(new ContactsAdapter.OnContactListItemActionInterface() {
@Override
public void onContactItemClicked(int position) {
contactClickHandler(position);
}
});
recyclerContacts.setAdapter(mAdapter);
} else {
mAdapter = new ContactsAdapter(mAllContacts, mAdapter.getSelectedContacts());
mAdapter.setOnContactItemListener(new ContactsAdapter.OnContactListItemActionInterface() {
@Override
public void onContactItemClicked(int position) {
contactClickHandler(position);
}
});
recyclerContacts.setAdapter(mAdapter);
}
}
private Delegate.PermissionDelegate permissionDelegate = new Delegate.PermissionDelegate() {
@Override
public void granted(int requestCode) {
super.granted(requestCode);
mAllContacts = getAllContacts();
mAdapter = new ContactsAdapter(mAllContacts, null);
mAdapter.setOnContactItemListener(new ContactsAdapter.OnContactListItemActionInterface() {
@Override
public void onContactItemClicked(int position) {
contactClickHandler(position);
}
});
recyclerContacts.setAdapter(mAdapter);
}
@Override
public void denied(int requestCode) {
super.denied(requestCode);
showDialog(getString(R.string.title_permission), getString(R.string.permission_contact));
}
};
private ArrayList<ContactInfo> getAllContacts() {
showProgress(getString(R.string.please_wait));
List<String> contacts = loadLegalContacts();
ArrayList<ContactInfo> allContacts = new ArrayList<>();
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if (phoneNumber != null) {
phoneNumber = phoneNumber.replace("(", "");
phoneNumber = phoneNumber.replace(")", "");
phoneNumber = phoneNumber.replace("-", "");
phoneNumber = phoneNumber.replace(" ", "");
phoneNumber = phoneNumber.replace("+", "");
}
ContactInfo info;
if (contacts.contains(id)) {
info = new ContactInfo(id, name, phoneNumber, true);
} else {
info = new ContactInfo(id, name, phoneNumber);
}
boolean isNew = true;
for (int i = 0; i < allContacts.size(); i++) {
if (TextUtils.equals(allContacts.get(i).name, name)) {
isNew = false;
break;
}
}
if (isNew) {
allContacts.add(info);
}
}
phones.close();
hideProgress();
return allContacts;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.done, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
if (getIntent().getExtras().getBoolean("NewUser")) {
showConfirmDialog(getString(R.string.setting_item_signout), getString(R.string.message_signout), new Delegate.DialogDelegate() {
@Override
public void complete(int result) {
super.complete(result);
if (result == RESULT_OK) {
FirebaseManager.signOut();
//MainActivity.startActivity(SettingsActivity.this);
finish();
}
}
});
} else {
finish();
}
break;
case R.id.done:
if (saveLegalContacts()) {
if (getIntent().getExtras().getBoolean("NewUser")) {
Home2Activity.startActivity(AddContactsActivity.this);
} else {
setResult(RESULT_OK);
}
finish();
}
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onBackPressed() {
if (getIntent().getExtras().getBoolean("NewUser")) {
showConfirmDialog(getString(R.string.setting_item_signout), getString(R.string.message_signout), new Delegate.DialogDelegate() {
@Override
public void complete(int result) {
super.complete(result);
if (result == RESULT_OK) {
FirebaseManager.signOut();
finish();
}
}
});
} else {
super.onBackPressed();
}
}
private boolean saveLegalContacts() {
if (mAllContacts.size() > 0) {
List<String> contacts = mAdapter.getSelectedContacts();
if (contacts == null || contacts.size() == 0) {
showErrorDialog(getString(R.string.error_no_contacts));
return false;
} else {
Set<String> set = new HashSet<>();
set.addAll(mAdapter.getSelectedContacts());
return SharedPrefUtil.getInstance().saveStringSet("LegalContacts", set);
}
} else {
return true;
}
}
private List<String> loadLegalContacts() {
List<String> contacts = new ArrayList<>();
Set<String> set = SharedPrefUtil.getInstance().getStringSet("LegalContacts");
if (set != null) {
contacts.addAll(set);
}
return contacts;
}
}