我为每件商品longClick
采用click
和longClick
方法,选择商品以RecycleViewAdapter
开头,然后单击允许用户选择,如您所见所选项目的背景颜色会发生变化,现在我需要再做一件事,当用户按下按钮时我想清除此选项并将背景更改为透明,这里是public class Channel_Show_Adapter extends RecyclerView.Adapter<Channel_Show_Adapter.ViewHolder> {
private Context mContext;
private ArrayList<Channel_Show_Model> Data_1;
private static String TAG = "val";
public onLongClickInterface longClick;
public onClickInterface shortClick;
private boolean longClickDone;
private boolean shortClickActivated=false;
public Channel_Show_Adapter(Context mContext, ArrayList<Channel_Show_Model> data, onLongClickInterface click1, onClickInterface click2) {
this.mContext = mContext;
this.Data_1 = data;
this.longClick = click1;
this.shortClick = click2;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener, View.OnClickListener {
AppCompatImageView image;
TextView title, text, date, user;
RelativeLayout singlePostLayout;
public ViewHolder(View itemView) {
super(itemView);
image = (AppCompatImageView) itemView.findViewById(R.id.ch_msg_image);
title = (TextView) itemView.findViewById(R.id.ch_msg_title);
text = (TextView) itemView.findViewById(R.id.ch_msg_message);
date = (TextView) itemView.findViewById(R.id.ch_msg_date);
user = (TextView) itemView.findViewById(R.id.ch_msg_user);
singlePostLayout = (RelativeLayout) itemView.findViewById(R.id.channel_single_post_layout);
itemView.setOnLongClickListener(this);
itemView.setOnClickListener(this);
}
@Override
public boolean onLongClick(View v) {
if(!shortClickActivated) {
singlePostLayout.setBackgroundColor(mContext.getResources().getColor(R.color.blueTransparent));
longClick.posClickedLong((short) getAdapterPosition());
longClickDone = true;
shortClickActivated=true;
}
return true;
}
@Override
public void onClick(View v) {
if(longClickDone) {
singlePostLayout.setBackgroundColor(mContext.getResources().getColor(R.color.blueTransparent));
shortClick.posClickedShort((short) getAdapterPosition());
shortClickActivated=true;
}
}
}
@Override
public Channel_Show_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.channel_show_recycler, parent, false);
return new Channel_Show_Adapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(final Channel_Show_Adapter.ViewHolder holder, int position) {
holder.title.setText(Data_1.get(position).getTitle());
holder.text.setText(Data_1.get(position).getMessage());
holder.date.setText(Data_1.get(position).getDate());
if (Application_Class.userDataArray.get(0).isSuperAdmin() || Application_Class.userDataArray.get(0).isAdmin()) {
holder.user.setText(Data_1.get(position).getUser());
} else {
holder.user.setText("");
}
Picasso.get().load(Data_1.get(position).getImage().getUrl()).noFade().into(holder.image);
}
@Override
public int getItemCount() {
return Data_1.size();
}
interface onLongClickInterface{void posClickedLong(short p);}
interface onClickInterface{void posClickedShort(short p);}
}
@Override
public void posClickedLong(short p) {
longClickOk=true;
itemsTempArray.add(data.get(p).getId());
}
@Override
public void posClickedShort(short p) {
itemsTempArray.add(data.get(p).getId());
}
@Override
public void onBackPressed() {
backPressed=true;
if(longClickOk && itemsTempArray.size()>0){
longClickOk=false;
for (int i = 0; i < itemsTempArray.size(); i++)
itemsTempArray.remove(i);
}else{
super.onBackPressed();
}
}
和活动
billing models.py
from django.conf import settings
from django.db import models
from django.db.models.signals import post_save,pre_save
from accounts.models import GuestEmail
import stripe
User=settings.AUTH_USER_MODEL
STRIP_SECRET_KEY= getattr(settings,"STRIP_SECRET_KEY","sk_test_I2eGCibhrZeFd9N0ipx9ac4I")
#STRIP_PUB_KEY=getattr(settings,"STRIP_PUB_KEY","pk_test_nvw3qh6iGMtKSGHMW5MHVwQD")
stripe.api_key=STRIP_SECRET_KEY
class BillingProfileManager(models.Manager):
def new_or_get(self,request):
user=request.user
guest_email_id=request.session.get('guest_email_id')
created=False
obj=None
if user.is_authenticated:
obj,created= self.model.objects.get_or_create(
user=user, email=user.email)
elif guest_email_id is not None:
guest_email_obj = GuestEmail.objects.get(id=guest_email_id)
obj, created = self.model.objects.get_or_create(
email=guest_email_obj.email)
else:
pass
return obj,created
class BillingProfile(models.Model):
user=models.OneToOneField(User,null=True,blank=True,on_delete=models.CASCADE)
email=models.EmailField()
active=models.BooleanField(default=True)
update = models.DateTimeField(auto_now=True)
timestamp=models.DateTimeField(auto_now_add=True)
customer_id=models.CharField(max_length=120,null=True,blank=True)
objects=BillingProfileManager()
def __str__(self):
return self.email
def charge(self,order_obj,card=None):
return Charge.objects.do(self,order_obj,card)
def get_cards(self):
return self.card_set.all()
@property
def has_card(self):
card_qs=self.get_cards()
return card_qs.exists()
@property
def default_card(self):
default_cards=self.get_cards().filter(default=True)
if default_cards.exists():
return self.default_cards.first()
return None
def billing_profile_created_receiver(sender,instance,*args,**kwargs):
if not instance.customer_id and instance.email:
print("ACTUAL AIL REQUEST SEND")
customer=stripe.Customer.create(
email=instance.email
)
print (customer)
instance.customer_id=customer.id
pre_save.connect(billing_profile_created_receiver,sender=BillingProfile)
class CardManager(models.Manager):
def all(self, *args, **kwargs): # ModelKlass.objects.all() --> ModelKlass.objects.filter(active=True)
return self.get_queryset().filter(active=True)
def add_new(self, billing_profile, token):
if token:
customer = stripe.Customer.retrieve(billing_profile.customer_id)
stripe_card_response = customer.sources.create(source=token)
new_card = self.model(
billing_profile=billing_profile,
stripe_id = stripe_card_response.id,
brand = stripe_card_response.brand,
country = stripe_card_response.country,
exp_month = stripe_card_response.exp_month,
exp_year = stripe_card_response.exp_year,
last4 = stripe_card_response.last4
)
new_card.save()
return new_card
return None
def user_created_receiver(sender,instance,created,*args,**kwargs):
if created and instance.email:
BillingProfile.objects.get_or_create(user=instance,email=instance.email)
post_save.connect(user_created_receiver,sender=User)
class ChargeManager(models.Manager):
def do(self, billing_profile, order_obj, card=None): # Charge.objects.do()
card_obj = card
if card_obj is None:
cards = billing_profile.card_set.filter(default=True) # card_obj.billing_profile
if cards.exists():
card_obj = cards.first()
if card_obj is None:
return False, "No cards available"
c = stripe.Charge.create(
amount = int(order_obj.total * 100), # 39.19 --> 3919
currency = "usd",
customer = billing_profile.customer_id,
source = card_obj.stripe_id,
metadata={"order_id":order_obj.order_id},
)
new_charge_obj = self.model(
billing_profile = billing_profile,
stripe_id = c.id,
paid = c.paid,
refunded = c.refunded,
outcome = c.outcome,
outcome_type = c.outcome['type'],
seller_message = c.outcome.get('seller_message'),
risk_level = c.outcome.get('risk_level'),
)
new_charge_obj.save()
return new_charge_obj.paid, new_charge_obj.seller_message
class Charge(models.Model):
billing_profile = models.ForeignKey(BillingProfile,on_delete=models.CASCADE)
stripe_id = models.CharField(max_length=120)
paid = models.BooleanField(default=False)
refunded = models.BooleanField(default=False)
outcome = models.TextField(null=True, blank=True)
outcome_type = models.CharField(max_length=120, null=True, blank=True)
seller_message = models.CharField(max_length=120, null=True, blank=True)
risk_level = models.CharField(max_length=120, null=True, blank=True)
objects = ChargeManager()
class Card(models.Model):
billing_profile=models.ForeignKey(BillingProfile,on_delete=models.CASCADE)
stripe_id=models.CharField(max_length=120)
brand=models.CharField(max_length=120,null=True,blank=True)
country = models.CharField(max_length=12, null=True, blank=True)
exp_month=models.IntegerField(null=True,blank=True)
exp_year=models.IntegerField(null=True,blank=True)
last4=models.CharField(max_length=4,null=True,blank=True)
default=models.BooleanField(default=True)
objects = CardManager()
def __str__(self):
return "{} {}".format(self.brand, self.last4)
checkout.html
{% extends "base.html" %}
{% block content %}
{% if not billing_profile%}
<div class="row text-center">
<div class="col-12 col-md-6">
<p class="lead">Login</p>
{% include 'accounts/snippets/form.html' with form=login_form next_url=request.build_absolute_uri %}
</div>
<div class="col-12 col-md-6">
Continue as Guest
{% url "guest_register" as guest_register_url %}
{% include 'accounts/snippets/form.html' with form=guest_form next_url=request.build_absolute_uri action_url=guest_register_url %}
</div>
</div>
{% else %}
{% if not object.shipping_address %}
<div class="row">
<div class="col-12">
<p class="lead">Shipping Address</p>
<hr/>
</div>
<div class="col-6">
{% url "checkout_address_create" as checkout_address_create %}
{% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipping' %}'
</div>
<div class="col-6">
{% url 'checkout_address_reuse' as checkout_address_reuse %}
{% include 'addresses/prev_addresses.html' with address_qs=address_qs next_url=request.build_absolute_uri address_type='shipping' action_url=checkout_address_reuse %}
</div>
</div>
{% elif not object.billing_address %}
<div class="row">
<div class="col-12">
<p class="lead">Billing Address</p>
<hr/>
</div>
<div class="col-md-6">
{% url "checkout_address_create" as checkout_address_create %}
{% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='billing' %}
</div>
<div class="col-6">
{% url 'checkout_address_reuse' as checkout_address_reuse %}
{% include 'addresses/prev_addresses.html' with address_qs=address_qs next_url=request.build_absolute_uri address_type='billing' action_url=checkout_address_reuse %}
</div>
</div>
{% else%}
{% if not has_card %}
<!-- enter credit card here -->
<div class='stripe-payment-form' data-token='{{ publish_key }}' data-next-url='{{ request.build_absolute_uri }}' data-btn-title='Add Payment Method'></div>
{% else %}
<h1>Finalize Checkout</h1>
<p>Cart Item:{% for product in object.cart.products.all %}{{ product}}{% if not forloop.last %},{% endif %},{% endfor %}</p>
<p>Shipping Address:{{object.shipping_address.get_address}}</p>
<p>Billing Address:{{object.shipping_address.get_address}}</p>
<p>Cart Total:{{object.cart.total}}</p>
<p>Shipping Total:{{object.shipping_total}}</p>
<p>Order Total:{{object.total}}</p>
<form class="form" method="POST" action="">{% csrf_token %}
<button type="submit btn btn-success">Checkout</button>
</form>
{% endif %}
{% endif %}
{% endif %}
{% endblock %}
答案 0 :(得分:3)
将此添加到您的模型类:
private boolean isSelected = false;
在模型类中创建相同的getter setter
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
从您的适配器中选择要选择项目的位置:
holder.title.setTag(position);
holder.title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int pos = (int) view.getTag();
setSelectedPosition(pos);
}
}
选择方法
public void setSelectedPosition(int position) {
for (int i = 0; i < list.size(); i++) {
list.get(i).setSelected(i == position);
}
notifyDataSetChanged();
}
如果您想清除选择
public void clearSelection() {
for (int i = 0; i < list.size(); i++) {
list.get(i).setSelected(false);
}
notifyDataSetChanged();
}
您也可以使用适配器对象从父片段/ Activity调用此方法。就像你用接口编码一样。如下所示
@Override
public void posClickedLong(short p) {
adapter.setSelectedPosition(p);
}
@Override
public void posClickedShort(short p) {
adapter.setSelectedPosition(p);
}
@Override
public void onBackPressed() {
backPressed=true;
if(longClickOk && itemsTempArray.size()>0){
adapter.clearSelection();
} else{
super.onBackPressed();
}
}
如果您想提供指定所选/取消选择状态的特定背景,请将下面的
selector drawable
命名为 my_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/drawable_shape_rectangle_border_orange" android:state_selected="true" /> // drawable to show when selected
<item android:drawable="@drawable/drawable_shape_rectangle_border_white" /> // drawable for default state
</selector>
drawable_shape_rectangle_border_white
的代码
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<stroke
android:width="@dimen/_1sdp"
android:color="@color/white" />
<corners android:radius="@dimen/_4sdp" />
</shape>
为您的布局设置背景
android:background="@drawable/my_selector"
BindViewHolder中的
holder.title.setSelected(model.isSelected()); // here I have tried changing background for your title view only. you can set these on your relative layout or any other needed layout.
答案 1 :(得分:1)
将boolean标志放入你的pojo类中,就像定义上面的channel_show_model类定义下面的代码一样..
private boolean selectedFlag;
public boolean isSelectedFlag() {
return selectedFlag;
}
public void setSelectedFlag(boolean selectedFlag) {
this.selectedFlag = selectedFlag;
}
然后制作两个用于处理longclick的界面并单击如下代码..
onItemClickListner onItemClickListner;
onItemLongClickListner onItemLongClickListner;
public void setOnItemLongClickListner(RecyclerViewAdpater.onItemLongClickListner onItemLongClickListner) {
this.onItemLongClickListner = onItemLongClickListner;
}
public void setOnItemClickListner(RecyclerViewAdpater.onItemClickListner onItemClickListner) {
this.onItemClickListner = onItemClickListner;
}
public interface onItemClickListner {
void onClick(Channel_Show_Model str);//pass your object types.
}
public interface onItemLongClickListner{
void onLongClick(Channel_Show_Model str);
}
@Override
public void onBindViewHolder(ItemViewHolder holder, int position) {
Channel_Show_Model data = mStringList.get(position); // if you pass object of class then create that class object.
if(data.isSelectedFlag)
holder.textView.setBackgroundColor(Color.RED);
// below code handle click event on recycler view item.
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onItemClickListner.onClick(data);
}
});
holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
onItemLongClickListner.onLongClick(data);
return false;
}
});
}
然后在活动之后将适配器绑定到使用下面代码的回收器视图中。
recyclerViewAdpater.setOnItemClickListner(new RecyclerViewAdpater.onItemClickListner() {
@Override
public void onClick(Channel_Show_Model str) {
str.setSelectedFlag(true);
recyclerViewAdpater.notifyDataSetChanged();
}
});
recyclerViewAdpater.setOnItemLongClickListner(new RecyclerViewAdpater.onItemLongClickListner() {
@Override
public void onLongClick(Channel_Show_Model str) {
str.setSelectedFlag(true);
recyclerViewAdpater.notifyDataSetChanged();
}
});
你可以管理长按,单击两个布尔值。