从onOptionsItemSelected

时间:2015-04-27 05:44:24

标签: android android-listview expandablelistview

在购物车活动中,我有一个listview,我在其上放置了imagebutton,如class_list_group.xml所示。当我开始活动时,我想要隐藏imagebutton。但是一旦按下操作栏中的编辑按钮(活动类中的onOptionsItemSelected),我想显示一个相对布局,它带有imagebutton,如xml文件中所示。

这是我的问题,我的问题是我该怎么做?任何帮助将不胜感激。它与我所说的零点异常有关。

Shoppingcartactivity.java类

    public class ShoppingCartActivity extends Activity {

    private TextView totalTV;
    private TextView discountTV;
    private TextView totalExclTV;
    private TextView totalTaxTV;
    private TextView netPriceTV;
    private ProductAdapter mProductAdapter;
    private ExpandableListView expListView;
    private EditText couponET;
    private ImageButton couponBTN;
    private List<Product> mCartList;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;
    private String Strdiscount;
    private double discount;
    public JSONObject DiscountObj;
    private double addSubTotal;
    RelativeLayout hiddenEditDelete;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cart_activity);

        ActionBar actionBar = getActionBar();
        getActionBar().setIcon(
                new ColorDrawable(getResources().getColor(
                        android.R.color.transparent)));
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        // Enabling Back navigation on Action Bar icon
        actionBar.setDisplayHomeAsUpEnabled(true);

        mCartList = ShoppingCartHelper.getCartList();

        expListView = (ExpandableListView) findViewById(R.id.lvExp);
        mProductAdapter = new ProductAdapter(this, mCartList,
                getLayoutInflater(), true);

        // setting list adapter
        expListView.setAdapter(mProductAdapter);

        totalTV = (TextView) findViewById(R.id.total_valueamount);
        discountTV = (TextView) findViewById(R.id.discount_valueamount);
        totalExclTV = (TextView) findViewById(R.id.exl_tax_valueamount);
        totalTaxTV = (TextView) findViewById(R.id.ttl_tax_valueamount);
        netPriceTV = (TextView) findViewById(R.id.net_price_valueamount);
        couponBTN = (ImageButton) findViewById(R.id.btncoupon);
        couponET = (EditText) findViewById(R.id.ET_coupon);
        hiddenEditDelete = (RelativeLayout) findViewById(R.id.rl_cartedit);
        hiddenEditDelete.setVisibility(View.GONE);
        couponET.setEnabled(false);
        couponBTN.setEnabled(false);
        priceCalculation();

        double taxamount = (addSubTotal * 5) / 100;
        double netTotal = addSubTotal + taxamount;

        DecimalFormat df = new DecimalFormat("#.##");

        addSubTotal = Double.valueOf(df.format(addSubTotal));
        taxamount = Double.valueOf(df.format(taxamount));
        netTotal = Double.valueOf(df.format(netTotal));

        totalTV.setText(Double.toString(addSubTotal));
        discountTV.setText("0.0");
        totalExclTV.setText(Double.toString(addSubTotal));
        totalTaxTV.setText(Double.toString(taxamount));
        netPriceTV.setText(Double.toString(netTotal));



//      couponBTN.setOnClickListener(new View.OnClickListener() {
//          public void onClick(View v) {
//
//              try {
//                  String CouponCode = couponET.getText().toString();
//
//                  if (!Utility.isNotNull(CouponCode)) {
//                      Toast.makeText(getApplicationContext(),
//                              "Insert coupon code", Toast.LENGTH_LONG).show();
//                  } else {
//                      new CouponAsyncTask(ShoppingCartActivity.this)
//                              .execute(CouponCode);
//                  }
//              } catch (Exception e) {
//                  e.printStackTrace();
//              }
//          }
//      });

    }

    public void loadCouponData() {

        Strdiscount = DiscountObj.optString("Discount");
        try {
            Log.i("Discount", DiscountObj.getString("Discount"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public void priceCalculation() {

        for (int i = 0; i < mCartList.size(); i++) {

            if (!mCartList.isEmpty()) {
                couponET.setEnabled(true);
                couponBTN.setEnabled(true);
            }
            Product cat = mCartList.get(i);
            addSubTotal += cat.subTotal;
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_cart, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Take appropriate action for each action item click
        switch (item.getItemId()) {
        case android.R.id.home:
            onBackPressed();
            finish();
            overridePendingTransition(R.anim.slide_in_left,
                    R.anim.slide_out_right);
            return true;
        case R.id.action_edit:
            hiddenEditDelete.setVisibility(View.VISIBLE);
            overridePendingTransition(R.anim.slide_in_right,
                    R.anim.slide_out_left);
            return true;

        default:
            return super.onOptionsItemSelected(item);
        }
    }
}

class_list_group.xml类

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/shareLILayout1"
        android:layout_width="fill_parent"
        android:layout_height="30dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal"
        android:paddingTop="3dp"
        android:weightSum="5" >

        <TextView
            android:id="@+id/lblListHeader"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_weight="3"
            android:paddingBottom="4dp"
            android:paddingLeft="28dp"
            android:paddingTop="4dp"
            android:singleLine="true"
            android:textColor="#000000"
            android:textSize="13sp"
            android:textStyle="bold" />

    </LinearLayout>

    <RelativeLayout
        android:id="@+id/rl_cartedit"
        android:layout_width="60dp"
        android:layout_height="30dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingBottom="4dp" >

        <ImageButton
            android:id="@+id/btneditcartitem"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="8dp"
            android:layout_marginTop="8dp"
            android:background="#ffffff"
            android:src="@drawable/edititem" />

    </RelativeLayout>

</RelativeLayout>

ProductAdapter .java

public class ProductAdapter extends BaseExpandableListAdapter {

    private List<Product> mCartList;
    private Context _context;
    private List<Product> _cartList;
    private boolean mShowQuantity;

    public ProductAdapter(Context context, List<Product> cartList,
            LayoutInflater inflater, boolean showQuantity) {
        this._context = context;
        this._cartList = cartList;
        mShowQuantity = showQuantity;
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return _cartList.get(groupPosition).getItems().get(childPosition);
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return _cartList.get(groupPosition).getItems().get(childPosition)
                .hashCode();
    }

    @Override
    public View getChildView(int groupPosition, int childPosition,
            boolean isLastChild, View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) _context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.cart_list_item, parent, false);
        }

        TextView itemSize = (TextView) v.findViewById(R.id.lblListItemSize);

        Item det = _cartList.get(groupPosition).getItems().get(childPosition);

        itemSize.setText(det.itemName + " ( " + det.price + " ) ");

        mCartList = ShoppingCartHelper.getCartList();

        return v;
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        int size = _cartList.get(groupPosition).getItems().size();
        System.out.println("Child for group [" + groupPosition + "] is ["
                + size + "]");
        return size;
    }

    @Override
    public Object getGroup(int groupPosition) {
        return this._cartList.get(groupPosition);
    }

    @Override
    public int getGroupCount() {
        return this._cartList.size();
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public View getGroupView(final int groupPosition, boolean isExpanded,
            View convertView, ViewGroup parent) {

        View v = convertView;

        if (v == null) {
            LayoutInflater inflater = (LayoutInflater) _context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = inflater.inflate(R.layout.cart_list_group, parent, false);
        }

        TextView groupName = (TextView) v.findViewById(R.id.lblListHeader);
        TextView groupQty = (TextView) v.findViewById(R.id.lbl_qty);
        TextView groupSubtotal = (TextView) v.findViewById(R.id.lblsubtotal);

        final Product cat = _cartList.get(groupPosition);

//      ShoppingCartEntry catalog = ShoppingCartHelper.getByProduct(cat);
//      int productIndex = getIntent().getExtras().getInt(
//              ShoppingCartHelper.PRODUCT_INDEX);
//      final Product selectedProduct = catalog.get(productIndex);


        groupName.setText(cat.description);
        groupQty.setText(String.valueOf(cat.quantity));
        groupSubtotal.setText(Double.toString(cat.subTotal));

        ImageButton editIB = (ImageButton) v.findViewById(R.id.btneditcartitem);

        if (cat.itemCategory != null && cat.itemCategory.equals("Pizza"))
            editIB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent next = new Intent(_context, ActivityEdit.class);
                Bundle b = new Bundle();
                b.putDouble("subTotal", cat.subTotal);
                next.putExtras(b);
                next.putExtra("description", cat.description);

                _context.startActivity(next);
                ((Activity) _context).overridePendingTransition(
                        R.anim.slide_in_right, R.anim.slide_out_left);
            }
        });


        return v;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }

}

cart_Activity

 <ExpandableListView
    android:id="@+id/lvExp"
    android:layout_width="match_parent"
    android:layout_height="162dp"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/grid_topics"
    android:cacheColorHint="#00000000"
    android:groupIndicator="@drawable/group_indicator" >
</ExpandableListView>

enter image description here

2 个答案:

答案 0 :(得分:0)

您尚未在hiddenEditDelete方法中使用它之前初始化onCreate,这就是为什么会抛出NPE的原因。另外,我认为setContentView最后应该被称为

    @Override
    public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      expListView = (ExpandableListView) findViewById(R.id.lvExp);
      mProductAdapter = new ProductAdapter(this, mCartList,
            getLayoutInflater(), true);

      expListView.setAdapter(mProductAdapter);

      hiddenEditDelete = (RelativeLayout) findViewById(R.id.rl_cartedit);
      hiddenEditDelete.setVisibility(View.GONE);

      setContentView(R.layout.cart_activity);
   }

答案 1 :(得分:0)

问题是你在访问之前没有对hiddenEditDelete(如expListView)进行任何引用,在使用它之前必须使用正确的布局ID对其进行实例化。然后你可以用布局做任何你想做的事。 onCreate()

中的其他所有内容都是正确的
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.cart_activity);

    expListView = (ExpandableListView) findViewById(R.id.lvExp);
mProductAdapter = new ProductAdapter(this, mCartList,
        getLayoutInflater(), true);

expListView.setAdapter(mProductAdapter);

    hiddenEditDelete.setVisibility(View.GONE);

}