@ItemClick未检测到GridView - android注释

时间:2015-08-05 10:04:08

标签: android gridview android-annotations

您好我在我的活动中使用了Android注释。我无法检测到gridview项目上的点击。 @ItemClick(R.id.orderedItemsList) void itemClicked(int position){ Log.w("CartActivity", "Clicked detected"); }

myactivity

public class CartActivity extends ActionBarActivity implements CartItemListener {

private static final String LOG_TAG = CartActivity.class.getName();

private List<CartOrderItem> orderItems;
private Dialog confirmDialog;

@ViewById(R.id.orderedItemsList)
GridView cartItems;

@ViewById(R.id.buyOptions)
RadioGroup buyOptions;

@ViewById(R.id.clearCart)
Button clearBtn;

@ViewById(R.id.placeOrder)
Button buyBtn;

@ViewById(R.id.totalCost)
TextView totalCost;

@ViewById(R.id.totalHeading)
TextView totalTitle;

@ViewById(R.id.paymentStatus)
TextView payStatus;

@Bean
FudzoneRestClient restClient;

@Bean
FudzonePersistence persistence;

@Extra
long restaurantId;

@Extra
List<CartItems> cart;

private CartAdapter adapter;
private long userId;
private static int attemptedRemove = -1;

@AfterViews
void init(){
    Log.d(LOG_TAG, "cart items got "+cart.toString());

    adapter = new CartAdapter(this, cart);
    adapter.setCartItemListener(this);
    cartItems.setAdapter(adapter);

    cartItems.setVisibility(View.VISIBLE);
    payStatus.setVisibility(View.GONE);

    setBuyStatus();

    try {
        int index = persistence.getEndUserRepository().getAll().size();
        userId = persistence.getEndUserRepository().get(index).getEndUserId();

    } catch (SQLException e) {
        Log.e(LOG_TAG, "could not fetch userId from persistence");
        e.printStackTrace();
    }
}

private void showRemoveConfirmation() {
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(CartActivity.this);

    alertDialog.setTitle("Confirm Delete");
    alertDialog.setMessage("Are you sure you want remove this item?");

    alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            adapter.removeFromCart(attemptedRemove);
            totalCost.setText(String.valueOf(adapter.getTotalCost()));
            if (adapter.getCount() == 0) {
                buyBtn.setEnabled(false);
            }
        }
    });

    alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });
    alertDialog.show();
}
@ItemClick(R.id.orderedItemsList)
   void itemClicked(int position){
   Log.w("CartActivity", "Clicked detected");
}

@Click(R.id.clearCart)
void clearCart(){
    cart.clear();
    adapter.clearAll();
    setBuyStatus();
}

@Click(R.id.placeOrder)
void placeOrder(){

    confirmDialog = new Dialog(this);
        confirmDialog.setCancelable(false);
        confirmDialog.setContentView(R.layout.dialog_order_confirmation);
        Button accept = (Button) confirmDialog.findViewById(R.id.confirmAccept);
        Button cancel = (Button) confirmDialog.findViewById(R.id.confirmCancel);

    accept.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            sendOrder();
        }
    });

    cancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            confirmDialog.dismiss();
        }
    });

    confirmDialog.show();
}

@Background
protected void sendOrder() {
    CartOrders cartOrders = new CartOrders();
    cartOrders.setRestaurantId(restaurantId);
    cartOrders.setEndUserId(userId);
    switch (buyOptions.getCheckedRadioButtonId()) {
        case R.id.takeAway:
            cartOrders.setDeliveryType(DeliveryType.TAKE_AWAY);
            cartOrders.setDeliveryLocationId(null);
            break;
        case R.id.delivery:
            cartOrders.setDeliveryType(DeliveryType.HOME_DELIVERY);
            break;
    }

    orderItems = null;
    orderItems = new ArrayList<CartOrderItem>();
    double totalCst = 0;
    for(CartItems item : cart){
        CartOrderItem temp = new CartOrderItem();
        temp.setProductId(item.getCartOrder().getFoodId());
        temp.setQuantity(item.getCartOrder().getQuantity());
        orderItems.add(temp);
        totalCst += item.getCartOrder().getPrice() * item.getCartOrder().getQuantity();
    }

    cartOrders.setCartOrderItem(orderItems);
    cartOrders.setTotalCost(totalCst);

    Gson gson = new Gson();

    /*RETROFIT CODE*/
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(ConnectionUtil.baseUrl)  //call your base url
            .build();

    ICartController cartController = restAdapter.create(ICartController.class);
    cartController.sendOrder(gson.toJson(cartOrders), new Callback<CartResponse>() {
        @Override
        public void success(CartResponse cartResponse, Response response) {
            if (response.getReason().equals("OK")) {
                Crouton.showText(CartActivity.this, "Order was successfully Placed. Order Number is " + cartResponse.getOrderId(), Style.CONFIRM);
                clearCart();
                cartItems.setVisibility(View.GONE);
                payStatus.setVisibility(View.VISIBLE);
                totalTitle.setText("Order Number is : ");
                totalCost.setText(String.valueOf(cartResponse.getOrderId()));
                payStatus.setText("Order will be processed after Payment is processed.");
                openPaymentOptions(cartResponse);
            }
        }

        @Override
        public void failure(RetrofitError error) {
            Crouton.showText(CartActivity.this, "Order couldn't be placed, Please try after sometime.", Style.CONFIRM);
            error.printStackTrace();
        }
    });

    /*RETROFIT CODE END*/

    Log.d(LOG_TAG, gson.toJson(cartOrders));
    confirmDialog.dismiss();

}

private void setBuyStatus(){
    if (cart.size() == 0) {
        buyBtn.setEnabled(false);
        clearBtn.setEnabled(false);
    }else {
        buyBtn.setEnabled(true);
        clearBtn.setEnabled(true);
    }
    totalCost.setText(String.valueOf(adapter.getTotalCost()));
}

void openPaymentOptions(CartResponse cartResponse){
    if (cartResponse != null) {
        PaymentPageActivity_.intent(CartActivity.this)
                .txUrl(cartResponse.getTransactionUrl())
                .startForResult(PaymentPageActivity.PAYMENT_GATEWAY);
    }
}

@Override
public void onBackPressed() {
    if(cart.size() == 0) {
        adapter = null;
        super.onBackPressed();
    }
    Crouton.showText(this, "Cart needs to be empty before you can exit", Style.INFO);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    setTitle("Cart");
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        // Respond to the action bar's Up/Home button
        case android.R.id.home:
            if(cart.size() == 0) {
                adapter = null;
                super.onOptionsItemSelected(item);
                return true;
            }

    }
    Crouton.showText(this, "Cart needs to be empty before you can exit", Style.INFO);
    return false;
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if(requestCode == PaymentPageActivity.PAYMENT_GATEWAY){
        switch(resultCode){
            case -1:
                Crouton.showText(CartActivity.this, "Error Processing Payment : Aborted", Style.ALERT);
                break;
            case -2:
                Crouton.showText(CartActivity.this, "Error Processing Payment : Failed Payment", Style.ALERT);
                break;
            case -3:
                Crouton.showText(CartActivity.this, "Error Processing Payment : User Termination", Style.ALERT);
                break;
            default:
                totalCost.setText("");
                updatePaymentinBackend(data);
        }
    }
}

@Background
void updatePaymentinBackend(final Intent data){
    if(data != null) {
        if(restClient.getOrderController().updatePayment(data.getStringExtra("txNo"))){

            updatePaymentInfo(true, data.getStringExtra("orderId"),
                    data.getStringExtra("bankRef"),
                    data.getStringExtra("txNo"));
        }else{
            updatePaymentInfo(false, "", "", "");
        }
    }else{
        updatePaymentInfo(false, "", "", "");
    }
}

@UiThread
 void updatePaymentInfo(boolean done, String orderId, String bankRef, String txNo) {
    if(done) {
        Crouton.showText(CartActivity.this, "Payment was Successful.", Style.CONFIRM);
        cartItems.setVisibility(View.GONE);
        payStatus.setVisibility(View.VISIBLE);
        totalTitle.setText("Please Note these details for reference.");

        payStatus.setText("\nOrder Number : " + orderId +
                "\nBank Ref number : " + bankRef +
                "\nTransaction number : " + txNo);

    }else{
        totalTitle.setText("Payment Processing has failed, contact support or retry from MyOrders");
        /*todo : add retry button and call doPayment*/
    }
}

@Override
public void removeItemListener(int pos) {
    attemptedRemove = pos;
    showRemoveConfirmation();
}

}

适配器

public class CartAdapter extends BaseAdapter {

private static final String LOG_TAG = CartAdapter.class.getName();
private List<CartItems> cartItems;
private LayoutInflater inflater;
private Context context;
private ImageLoaderService_ imageLoaderService;
private double totalCost;
CartItemListener itemListener;

public CartAdapter(Context context, List<CartItems> cartItems) {
    this.cartItems = cartItems;
    this.context = context;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    imageLoaderService = ImageLoaderService_.getInstance_(context);
}

public void setCartItemListener(CartItemListener itemListener){
    this.itemListener = itemListener;
}

@Override
public int getCount() {
    return cartItems.size();
}

@Override
public Object getItem(int position) {
    return cartItems.get(position);
}

@Override
public long getItemId(int position) {
//TODO :I think it will be better to disable click on cart items.
    try {
        return cartItems.get(position).getFoodId();
    }catch (NullPointerException e) {
        Log.e(LOG_TAG, "Something when wrong and get(position) returned null, returning 0 to avoid crash");
        e.printStackTrace();
        return 0;
    }
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    if(convertView == null){
        convertView = inflater.inflate(R.layout.hotel_menu_item, null);
    }

    ImageView menuImg = (ImageView) convertView.findViewById(R.id.menuImg);
    ImageView menuTypeImg = (ImageView) convertView.findViewById(R.id.foodTypeImg);
    TextView inCart = (TextView) convertView.findViewById(R.id.noOfItems);
    TextView menuItemName = (TextView) convertView.findViewById(R.id.menuItemName);
    TextView menuItemCost = (TextView) convertView.findViewById(R.id.menuItemCost);
    LinearLayout btnHolder = (LinearLayout) convertView.findViewById(R.id.buttonHolder);

    btnHolder.setVisibility(View.GONE);

    imageLoaderService.getLoader().displayImage(ConnectionUtil.baseUrl+"/"+cartItems.get(position).getPhoto(), menuImg);

    switch(cartItems.get(position).getFoodType()){
        case VEGETARIAN:
            menuTypeImg.setImageDrawable(context.getResources().getDrawable(R.drawable.veg));
            menuTypeImg.setContentDescription("Contains veg.");
            break;
        case NON_VEGETARIAN:
            menuTypeImg.setImageDrawable(context.getResources().getDrawable(R.drawable.non_veg));
            menuTypeImg.setContentDescription("Contains non-veg.");
            break;
        case CONTAINS_EGG:
            menuTypeImg.setImageDrawable(context.getResources().getDrawable(R.drawable.egg));
            menuTypeImg.setContentDescription("Contains egg.");
            break;
    }

    inCart.setText(cartItems.get(position).getCartOrder().getQuantity().toString());
    menuItemName.setText(cartItems.get(position).getCartOrder().getFoodName());
    menuItemCost.setText(cartItems.get(position).getCartOrder().getPrice().toString());

    /*convertView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            itemListener.removeItemListener(position);
        }
    });*/

    return convertView;
}
}

完全没有检测到点击。我试过@ItemLongClick,@ ItemSelect,但没有检测到点击事件。任何人都有任何建议。

由于

1 个答案:

答案 0 :(得分:0)

您好首先有3条建议: -

1。)带注释 activity EActivityEActivity(R.layout.activity_layout_cartActivity)

2。)注册您的活动Manifest.xmlCartActivity_而不是 CartActivity

3。)检查您的build.gradle 文件现在 androidannotations 可用替代 roboguice 所以你的gradle gile看起来像......

<强> app.gradle: -

apply plugin: 'com.neenbedankt.android-apt'
def AAVersion = '3.3.2' // change this to your desired version, for example the latest stable: 3.3.2

.......

apt {
    arguments {
        androidManifestFile variant.outputs[0].processResources.manifestFile
        // if you have multiple outputs (when using splits), you may want to have other index than 0

        // you should set your package name here if you are using different application IDs
        // resourcePackageName "your.package.name"

        // You can set optional annotation processing options here, like these commented options:
        // logLevel 'INFO'
        // logFile '/var/log/aa.log'
    }
}

...

dependencies {
  apt "org.androidannotations:androidannotations:$AAVersion"
compile "org.androidannotations:androidannotations-api:$AAVersion"}

--------多数民众赞成。

谢谢希望这可以帮助你