介紹
最近用淘寶客戶端的時候,編輯地址的時候有個地區選擇的功能。看上面的效果覺得挺酷,滾動的時候,是最後一個從下面飛上來挨著前一個。就自己鼓搗一個出來玩玩。
說了效果可能不太直觀,下面上兩張圖看看效果
淘寶地區選擇效果
再來一張自己的效果
gif的效果可能不太好,大家自己用Android手機打開淘寶看看
實現分析
展示很簡單,ListView就可以了。對於動畫效果,只需要在getView的時候獲取到要展示的View,通過屬性動畫修改translationY就ok啦。由於地區選擇是一個界面,所以這裡還用到了Fragment的 addToBackStack知識
1、用來展示的Fragment
用一個Fragment來接受parentCode參數來獲取父地區的所有子地區,然後進行顯示。這裡用Fragment來做是因為用Activity的話,這樣的連續點擊都是同一類的界面不太適合。
Java代碼
- public class AreaFragment extends Fragment implements AdapterView.OnItemClickListener {
-
- private static final String ARG_PARAM1 = "parentCode";
- @Bind(R.id.refresh_list_view)
- ListView mRefreshListView;
- @Bind(R.id.loadingBar)
- ProgressBar mLoadingBar;
-
- private String mParam1;//parentCode參數
-
- OkHttpClient mOkHttpClient = new OkHttpClient();
-
- private OnFragmentInteractionListener mListener;
-
- private AreaAdapter adapter;//地區adapter
-
- public AreaFragment() {
- }
-
- /**
- * Use this factory method to create a new instance of
- * this fragment using the provided parameters.
- *
- * @param param1 Parameter 1.
- * @return A new instance of fragment AreaFragment.
- */
- public static AreaFragment newInstance(String param1) {
- AreaFragment fragment = new AreaFragment();
- Bundle args = new Bundle();
- args.putString(ARG_PARAM1, param1);
- fragment.setArguments(args);
- return fragment;
- }
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- if (getArguments() != null) {
- //獲取父地區的code,用來查詢子地區
- mParam1 = getArguments().getString(ARG_PARAM1);
-
- }
- }
-
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- // Inflate the layout for this fragment
- View view = inflater.inflate(R.layout.fragment_area, container, false);
- ButterKnife.bind(this, view);
- mRefreshListView.setOnItemClickListener(this);
-
- FormEncodingBuilder builder = new FormEncodingBuilder();
- builder.add(ARG_PARAM1,mParam1);
-
- //通過parentCode來請求地區,如果parentCode不存在就是第一級
- final Request request = new Request.Builder()
- .url("http://123.184.16.19:8008/area/list")
- .post(builder.build())
- .build();
- mOkHttpClient.newCall(request).enqueue(new Callback(){
- @Override
- public void onFailure(Request request, IOException e) {
-
- }
-
- @Override
- public void onResponse(Response response) throws IOException {
- final String res = response.body().string();
- if (res!=null){
- Gson gson = new Gson();
- JsonResult jsonResult = gson.fromJson(res, JsonResult.class);
- if (jsonResult.isSuccess()){
- List list = (List) jsonResult.getResult();
-
- List newList = new ArrayList();
- Iterator iterator = list.iterator();
- while (iterator.hasNext()){
- Map map = (Map) iterator.next();
- AreaInfo areaInfo = gson.fromJson(gson.toJson(map),AreaInfo.class);
- newList.add(areaInfo);
- }
- adapter = new AreaAdapter(getContext(),newList);
- getActivity().runOnUiThread(new Runnable() {
- @Override
- public void run() {
- //拿到數據進行展示
- mRefreshListView.setAdapter(adapter);
- }
- });
- }
- }
- }
- });
-
- return view;
- }
-
- @Override
- public void onAttach(Context context) {
- super.onAttach(context);
- if (context instanceof OnFragmentInteractionListener) {
- mListener = (OnFragmentInteractionListener) context;
- } else {
- throw new RuntimeException(context.toString()
- + " must implement OnFragmentInteractionListener");
- }
- }
-
- @Override
- public void onDetach() {
- super.onDetach();
- mListener = null;
- }
-
- @Override
- public void onDestroyView() {
- super.onDestroyView();
- ButterKnife.unbind(this);
- }
-
-
-
- @Override
- public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
- //單擊的時候需要處理地區點擊事件,統一交給Activity處理
- AreaInfo areaInfo = (AreaInfo) parent.getAdapter().getItem(position);
- if (areaInfo==null) return;
- if (mListener!=null){
- mListener.onFragmentInteraction(areaInfo);
- }
- }
-
-
- //用來和Activity交互的回調接口
- public interface OnFragmentInteractionListener {
- void onFragmentInteraction(AreaInfo areaInfo);
- }
我們用了一個Fragment來接受parentCode,用於請求下一級的地區,獲取成功之後進行了展示。並且提供了一個OnFragmentInteractionListener用來在onItemClick時與Activity交互。
接下來看adapter,最開始我們提到了要實現淘寶的效果我們只需要拿到即將顯示的View,設置動畫就可以了。
2、處理顯示效果的adapter
Java代碼
- class AreaAdapter extends BaseAdapter {
-
- private List list;
-
- private int lastPosition;
-
- public AreaAdapter(Context context, List<AreaInfo> list) {
- this.list = list;
- }
-
-
- @Override
- public int getCount() {
- return list.size();
- }
-
- @Override
- public Object getItem(int position) {
- return list.get(position);
- }
-
- @Override
- public long getItemId(int position) {
- return 0;
- }
-
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- ViewHolder viewHolder = null;
- if (convertView==null){
- convertView = LayoutInflater.from(getContext()).inflate(R.layout.area_list_item,parent,false);
- viewHolder = new ViewHolder();
- viewHolder.textView = (TextView) convertView.findViewById(android.R.id.text1);
- convertView.setTag(viewHolder);
- }
- viewHolder = (ViewHolder) convertView.getTag();
- AreaInfo item = (AreaInfo) list.get(position);
- viewHolder.textView.setText(item.getAreaName());
- if (lastPosition<position&&lastPosition!=0){
- ObjectAnimator.ofFloat(convertView,"translationY",convertView.getHeight()*2,0).setDuration(500).start();
-
- }
- lastPosition = position;
- return convertView;
- }
-
- class ViewHolder{
- TextView textView;
- }
- }
很常見的一個Adapter寫法,只是在getView當中獲取到了要顯示的view,通過
ObjectAnimator.ofFloat(convertView,"translationY",convertView.getHeight()*2,0).setDuration(500).start()為veiw設置了動畫,
這裡還用了個變量position來區別只有在向上滾動的時候才會有動畫。不過我覺得不加position區別的效果也不錯,大家可以試試。
其實這樣已經實現了效果,接下來順便提一下Activity對Framgnet中onItemClick的處理。
3、Activity和fragment的交互處理
Java代碼
- public class AreaSelectActivity extends AppCompatActivity implements AreaFragment.OnFragmentInteractionListener{
-
- private Fragment oneFragment;
- private Fragment twoFragment;
-
-
- private Map map = new HashMap();
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_area_select);
- ButterKnife.bind(this);
- //新建第一級地區,parentCode參數為null
- oneFragment = AreaFragment.newInstance("");
- FragmentManager fragmentManager = getSupportFragmentManager();
- fragmentManager.beginTransaction().replace(R.id.content,oneFragment).commit();
- }
-
-
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()){
- case android.R.id.home:
- FragmentManager fragmentManager = getSupportFragmentManager();
- if (fragmentManager.getBackStackEntryCount()>0){
- fragmentManager.popBackStack();
- }else{
- finish();
- }
- break;
- }
- return true;
- }
-
-
-
- /**
- * 處理交互,hide前一個fragment,並且調用addToBackStack讓Fragment可以點擊back的時候顯示前一個fragment
- * 如果是第三級地區則直接返回地區選擇數據給上個Activity
- * @param areaInfo 被點擊的地區信息
- */
- @Override
- public void onFragmentInteraction(AreaInfo areaInfo) {
- if (areaInfo==null){
- return;
- }
- FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
- int level = areaInfo.getLevel();
- switch (level){
- case 1:
- map.put("provId",areaInfo.getId());
- map.put("provName",areaInfo.getAreaName());
- if (areaInfo.isLeaf()){
- Intent intent = new Intent();
- intent.putExtra("addressInfo", (Serializable) map);
- setResult(RESULT_OK,intent);
- finish();
- }else{
- transaction.hide(oneFragment);
- transaction.add(R.id.content,twoFragment=AreaFragment.newInstance(areaInfo.getAreaCode()+"")).addToBackStack(null).commit();
- }
- break;
- case 2:
- map.put("cityId",areaInfo.getId());
- map.put("cityName",areaInfo.getAreaName());
- if (areaInfo.isLeaf()){
- Intent intent = new Intent();
- intent.putExtra("addressInfo", (Serializable) map);
- setResult(RESULT_OK,intent);
- finish();
- }else {
- transaction.hide(twoFragment);
- transaction.add (R.id.content, AreaFragment.newInstance(areaInfo.getAreaCode()+"")).addToBackStack(null).commit();
- }
- break;
- case 3:
- map.put("districtId",areaInfo.getId());
- map.put("districtName",areaInfo.getAreaName());
- Intent intent = new Intent();
- intent.putExtra("addressInfo", (Serializable) map);
- setResult(RESULT_OK,intent);
- finish();
- break;
- }
-
- }
- }
這樣仿淘寶地區選擇就實現啦!
結語
大家可以自己寫測試接口,也可以直接調用我寫好的接口:
http://123.184.16.19:8008/area/list
源碼提供給大家參考:
Android仿淘寶地區選擇