筆者在實現仿京東商品分類功能時,需要點擊右邊商品小類(RightAdapter)跳轉到相應的商品搜索列表(SortSearchActivity),爲了實現這一功能,需要解決兩個問題:
1.爲RightAdapter中的商品小類設置監聽,通過Intent實現界面的跳轉;
2.跳轉之後將所點擊項目的值(此處爲“oppo”)傳給相應Activity(此處爲SortSearchActivity),實現搜索並將商品詳情顯示出來。
具體實現效果如下圖所示(點擊oppo):
1.如何解決界面跳轉問題,通過Context實現:
Intent intent = new Intent(mContext, SortSearchActivity.class);
mContext.startActivity(intent);
2.如何解決傳值問題,通過SharePreferences實現:
RightAdpter(此處kindItemBean.getName()爲所需要的傳遞的數據):
SharedPreferences sp = mContext.getSharedPreferences("data", MODE_PRIVATE);
//獲取編輯器
SharedPreferences.Editor editor = sp.edit();
//存入String型數據
editor.putString("goodsname", kindItemBean.getName());
Log.i(TAG, "goodsname:" + sp);
//提交修改,否則不生效
editor.commit();
SortSearchActivity:
//獲取分類界面點擊的物品,展示出搜索結果
SharedPreferences sp = getSharedPreferences("data", MODE_PRIVATE);
//第二個參數爲缺省值,如果不存在該key,返回缺省值
String goodsname = sp.getString("goodsname", "");
Log.i(TAG, "goodsname:" + goodsname);
etSearch.setHint(goodsname); //etSearch爲搜索框
goodsKeyWord = goodsname; //goodsKeyWord爲搜索關鍵字