从 onOptionsItemSelected 访问列表视图
Posted
技术标签:
【中文标题】从 onOptionsItemSelected 访问列表视图【英文标题】:Accessing the listview from onOptionsItemSelected 【发布时间】:2015-07-05 10:50:07 【问题描述】:在购物车活动中,我有一个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_
android:layout_
android:orientation="vertical" >
<LinearLayout
android:id="@+id/shareLILayout1"
android:layout_
android:layout_
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal"
android:paddingTop="3dp"
android:weightSum="5" >
<TextView
android:id="@+id/lblListHeader"
android:layout_
android:layout_
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_
android:layout_
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:orientation="horizontal"
android:paddingBottom="4dp" >
<ImageButton
android:id="@+id/btneditcartitem"
android:layout_
android:layout_
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_
android:layout_
android:layout_alignParentLeft="true"
android:layout_below="@+id/grid_topics"
android:cacheColorHint="#00000000"
android:groupIndicator="@drawable/group_indicator" >
</ExpandableListView>
【问题讨论】:
你为什么不用.setVisibility(View.)
?
我在我的活动中使用了这个 hiddenEditDelete.setVisibility(View.GONE);。但导致崩溃
显示崩溃报告。
这是第 79 行,它崩溃了。 hiddenEditDelete.setVisibility(View.GONE);
hiddenEditDelete
是您在 class_list_group.xml
中,而不是在 cart_activity
中。这会导致空指针异常。
【参考方案1】:
在 onCreate
方法中使用之前,您还没有初始化 hiddenEditDelete
,这就是抛出 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);
【讨论】:
在方法结束时调用setContenView
还是一样的结果。兄弟可以从主要活动中访问列表视图项目吗?我认为问题在于。在不使用 hiddenEditDelete 行的情况下运行应用程序时,它可以工作。
您会在问题中添加cart_activity
xml 代码吗?
我只有一个列表查看这个id,lvExp
如果我们看不到代码很难帮助你,我也注意到expListView
,mProductAdapter
和mCartList
没有在你的活动中声明,所以我是想知道这段代码是如何构建的,而且即使它可以构建,mCartList
应该是 null
因此你的适配器会抛出 NPE【参考方案2】:
问题是您在访问 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);
【讨论】:
好的,我明白了。那么你能告诉我应该在 onCreate() 中添加什么吗? 在访问布局之前在 create 中写入 hiddenEditDelete=(RelativeLayout)findViewById(YOUR_XML_ID); 我有这一行 hiddenEditDelete = (RelativeLayout) findViewById(R.id.rl_cartedit); 那么它应该可以工作。您能否提供错误的堆栈跟踪? 您能否检查一下 rl_cartedit 在您的 cart_activity xml 中是否可用?以上是关于从 onOptionsItemSelected 访问列表视图的主要内容,如果未能解决你的问题,请参考以下文章
OnOptionsItemSelected 未通过使用 ScrollView 实现的方法调用
onOptionsItemSelected() 方法不会在 Fragment 上调用
OnOptionsItemSelected 在 Xamarin 中不起作用
在 Fragment 中添加 onOptionsItemSelected 调用