protected boolean prepareModelData(int state, int commandId) {
    switch (state) {
      case STATE_CUSTOM_PLACE:
        {
          if (commandId == CMD_CUSTOM_PLACE_DONE) {
            if (addressEditView != null) {
              String label = addressEditView.getText().trim().toString();
              model.put(KEY_S_PLACE_LABEL, label);
            }
          }
          if (commandId == CMD_CUSTOM_PLACE_DONE || commandId == CMD_ADD_CATEGORY) {
            if (categoryList != null) {
              Vector categories = AddPlaceViewTouch.this.model.getVector(KEY_V_ALL_CATEGORIES);
              int position = categoryList.getCheckedItemPosition();
              if (position >= categoryList.getHeaderViewsCount()
                  && position < categoryList.getHeaderViewsCount() + categories.size() + 1) {
                int selectedCategoryIndex = position - categoryList.getHeaderViewsCount() - 1;
                AddPlaceViewTouch.this.model.put(
                    KEY_I_SELECTED_CATEGORY_INDEX, selectedCategoryIndex);
              }
            }
          }

          break;
        }
      default:
        break;
    }

    return true;
  }
 @MediumTest
 public void testPreconditions() {
   assertTrue("listview.getItemsCanFocus()", mListView.getItemsCanFocus());
   assertFalse("out of touch-mode", mListView.isInTouchMode());
   assertEquals("header view count", 1, mListView.getHeaderViewsCount());
   assertTrue("header does not have focus", mListView.getChildAt(0).isFocused());
 }
 @Override
 public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
   try {
     if (leader_kind == null || leader_kind.equals("FRIENDS") || leader_kind.equals("CLOSEST")) {
       if (listView.getHeaderViewsCount() > 0) position--;
       try {
         if (player != null && player.getUser() != null) {
           if (!player.getUser().getId().equals(usersExts.get(position))) {
             showOptionAlert(position);
           }
         }
       } catch (Exception e) {
         e.printStackTrace();
       }
     } else if (leader_kind.equals("ALLIANCES")) {
       if (player != null && player.getUser() != null) {
         UserAlliance ua =
             new UserAlliance(
                 currentContext, UserAlliance.SHOW_ALLIANCE, usersExts.get(position - 1));
         ua.show();
       }
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
 protected static String getId(ListView l, int position) {
   // Get the cursor and fetch the stop ID from that.
   SimpleCursorAdapter cursorAdapter = (SimpleCursorAdapter) l.getAdapter();
   Cursor c = cursorAdapter.getCursor();
   c.moveToPosition(position - l.getHeaderViewsCount());
   return c.getString(Columns.COL_ID);
 }
 @Override
 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   ListView listView = (ListView) getRefreshView();
   position -= listView.getHeaderViewsCount();
   if (position >= 0 && position < getAdapterCount())
     BizFragment.getBizFragment(this).replyComment(null, getAdapterItems().get(position));
 }
示例#6
0
  @Override
  public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;

    int actualPos = info.position - tagListView.getHeaderViewsCount();
    if (actualPos < 0) return;
    Tag tagClicked = tags.getTags().get(actualPos);

    // Log.i("occm", tagClicked.getParent_id() + " " +
    // tagClicked.getComment().toString());

    String userId = tagInfo.getString("user_id", "error");

    boolean isOwnTag = (tagClicked.getUser_id().equals(userId));

    menu.setHeaderTitle(R.string.context_menu_header);
    menu.add(0, v.getId(), 6, R.string.context_menu_reply);
    if (!tagClicked.getParent_id().equals("0")) {
      menu.add(0, v.getId(), 5, R.string.context_menu_show_orig);
    }
    if (isOwnTag) return;

    if (!tagClicked.getIs_thumbedup()) menu.add(0, v.getId(), 1, R.string.context_menu_thumbup);

    if (Session.getFollowerSet().contains(tagClicked.getUser_id()))
      menu.add(0, v.getId(), 3, R.string.context_menu_unfollow);
    else menu.add(0, v.getId(), 4, R.string.context_menu_follow);
  }
  /**
   * This simple implementation creates a Bitmap copy of the list item currently shown at ListView
   * <code>position</code>.
   */
  @Override
  public View onCreateFloatView(int position) {
    // Guaranteed that this will not be null? I think so. Nope, got
    // a NullPointerException once...
    View v =
        mListView.getChildAt(
            position + mListView.getHeaderViewsCount() - mListView.getFirstVisiblePosition());

    if (v == null) {
      return null;
    }

    v.setPressed(false);

    // Create a copy of the drawing cache so that it does not get
    // recycled by the framework when the list tries to clean up memory
    // v.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
    v.setDrawingCacheEnabled(true);
    mFloatBitmap = Bitmap.createBitmap(v.getDrawingCache());
    v.setDrawingCacheEnabled(false);

    if (mImageView == null) {
      mImageView = new ImageView(mListView.getContext());
    }
    mImageView.setBackgroundColor(mFloatBGColor);
    mImageView.setPadding(0, 0, 0, 0);
    mImageView.setImageBitmap(mFloatBitmap);
    mImageView.setLayoutParams(new ViewGroup.LayoutParams(v.getWidth(), v.getHeight()));

    return mImageView;
  }
 /** @return Actual selected groups from adapter. */
 public ArrayList<String> getSelected() {
   ArrayList<String> groups = new ArrayList<>();
   for (int position = 0; position < arrayAdapter.getCount(); position++)
     if (listView.isItemChecked(position + listView.getHeaderViewsCount())) {
       groups.add(arrayAdapter.getItem(position));
     }
   return groups;
 }
 @Override
 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
   int pos = position - listView.getHeaderViewsCount();
   if (pos >= 0 && pos < maopaoObjectList.size()) {
     MaopaoDetailActivity_.intent(getActivity())
         .mMaopaoObject(maopaoObjectList.get(pos))
         .start();
   }
 }
示例#10
0
 /** 设置listView的 HeaderView */
 private void setHeaderViewWithListView() {
   if (mListView.getHeaderViewsCount() == 0) {
     TextView tv = new TextView(context);
     tv.setText("查询历史-清空");
     mListView.addHeaderView(tv);
     mListView.setHeaderDividersEnabled(true);
     tv.setOnClickListener(l);
   }
 }
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    hideSoftKeyboard();

    int adjPosition = position - mListView.getHeaderViewsCount();
    if (adjPosition >= 0) {
      onItemClick(adjPosition, id);
    }
  }
 public void addStickHeaderView(View view, Object data, boolean isSelectable) {
   if (view == null) {
     return;
   }
   mHeaderViews.add(view);
   mStickHeaderMap.put(view, new StickView(mListView.getHeaderViewsCount()));
   mListView.addHeaderView(mStickHeaderMap.get(view).placeHolderView, data, isSelectable);
   addView(view);
 }
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    switch (requestCode) {
      case ADD_ACCOUNT_REQUEST:
        if (resultCode == RESULT_OK) {
          // new blog has been added, so rebuild cache of blogs and
          // setup current blog
          getBlogNames();
          setupCurrentBlog();
          initMenuDrawer();
          mMenuDrawer.peekDrawer(0);
        } else {
          finish();
        }
        break;
      case SETTINGS_REQUEST:
        if (resultCode == RESULT_OK) {
          if (mMenuDrawer != null) {
            updateMenuDrawer();
            String[] blogNames = getBlogNames();
            // If we need to add or remove the blog spinner, init the drawer again
            if ((blogNames.length > 1 && mListView.getHeaderViewsCount() == 0)
                || blogNames.length == 1 && mListView.getHeaderViewsCount() > 0)
              this.initMenuDrawer();
            else if (blogNames.length > 1 && mBlogSpinner != null) {
              SpinnerAdapter mSpinnerAdapter =
                  new ArrayAdapter<String>(
                      getSupportActionBar().getThemedContext(),
                      R.layout.sherlock_spinner_dropdown_item,
                      blogNames);
              mBlogSpinner.setAdapter(mSpinnerAdapter);
            }

            if (blogNames.length >= 1) {
              setupCurrentBlog();
              onBlogChanged();
            }
          }
        }
        break;
    }
  }
示例#14
0
 /**
  * Sets new list of groups and select specified groups.
  *
  * @param groups
  * @param selected
  */
 void setGroups(Collection<String> groups, Collection<String> selected) {
   ArrayList<String> list = new ArrayList<>(groups);
   Collections.sort(list);
   arrayAdapter.clear();
   for (int position = 0; position < list.size(); position++) {
     String group = list.get(position);
     arrayAdapter.add(group);
     listView.setItemChecked(position + listView.getHeaderViewsCount(), selected.contains(group));
   }
 }
  @Override
  public void onListItemClick(ListView l, View v, int position, long id) {

    Log.d(THIS_FILE, "Checked " + position + " et " + id);

    ListView lv = getListView();
    lv.setItemChecked(position, true);

    curCheckPosition = id;
    Cursor c = (Cursor) getListAdapter().getItem(position - lv.getHeaderViewsCount());
    showDetails(id, c.getString(c.getColumnIndex(SipProfile.FIELD_WIZARD)));
  }
示例#16
0
  // TODO sync
  public void animateDismiss(final int pos) {
    final int actionPos =
        pos - mListView.getFirstVisiblePosition() + mListView.getHeaderViewsCount();
    final View view = mListView.getChildAt(actionPos);
    final ViewGroup.LayoutParams lp = view.getLayoutParams();
    final int originWidth = view.getWidth();
    final int originHeight = view.getHeight();

    Animator translationXAnim = ObjectAnimator.ofFloat(view, "x", 0, -originWidth);
    Animator alphaAnim = ObjectAnimator.ofFloat(view, "alpha", 1, 0);
    ValueAnimator layoutParamYAnim = ValueAnimator.ofInt(originHeight, 0);
    layoutParamYAnim.addUpdateListener(
        new ValueAnimator.AnimatorUpdateListener() {

          @Override
          public void onAnimationUpdate(ValueAnimator anim) {
            lp.height = (Integer) anim.getAnimatedValue();
            view.setLayoutParams(lp);
          }
        });

    AnimatorSet animSet = new AnimatorSet();
    animSet.setDuration(1000);
    animSet.setTarget(view);
    animSet.setInterpolator(new AccelerateInterpolator());
    animSet.playTogether(translationXAnim, alphaAnim, layoutParamYAnim);
    layoutParamYAnim.setStartDelay(200);
    animSet.addListener(
        new Animator.AnimatorListener() {

          @Override
          public void onAnimationStart(Animator arg0) {}

          @Override
          public void onAnimationRepeat(Animator arg0) {}

          @Override
          public void onAnimationCancel(Animator arg0) {}

          @Override
          public void onAnimationEnd(Animator arg0) {
            // 还原 View 的状态
            lp.height = originHeight;
            view.setLayoutParams(lp);
            ViewHelper.setX(view, 0);
            ViewHelper.setAlpha(view, 1);

            mAdapter.getData().remove(pos);
            mAdapter.notifyDataSetChanged();
          }
        });
    animSet.start();
  }
 @Override
 public void onSuccess(Object obj) {
   refreshComplete();
   SystemPromotion module = (SystemPromotion) obj;
   if (serviceHeaderView != null) {
     serviceHeaderView.stopBannerTurning();
     listView.removeHeaderView(serviceHeaderView);
   }
   if (listView.getHeaderViewsCount() == 0) {
     serviceHeaderView = new ServiceHeaderView(getActivity(), module.content.banner);
     listView.addHeaderView(serviceHeaderView);
   }
   adapter = new SystemPromotionListAdapter(getActivity(), module.content.recommend);
   listView.setAdapter(adapter);
 }
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
          DraftInfo info =
              (DraftInfo) mlistViewAdapter.getItem(arg2 - mlistView.getHeaderViewsCount());

          mDraftInfo = info;
          DraftMgr.instance().deleteDraft(info.id);
          mlistViewAdapter.notifyDataSetChanged();
          // resend(info);
          Intent i = new Intent(Statuses_Draft_Activity.this, Statuses_Send_Activity.class);
          i.setAction(Statuses_Send_Activity.ACTION_DRAFT);
          startActivity(i);

          finish();
        }
  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    final ListView list = (ListView) parent;
    final int headerCount = list.getHeaderViewsCount();

    if (position < headerCount) {
      // The click is on a header, don't do anything.
      return;
    }

    // Absolute position for the adapter.
    position -= headerCount;

    final BookmarksListAdapter adapter = getBookmarksListAdapter();
    if (adapter.isShowingChildFolder()) {
      if (position == 0) {
        // If we tap on an opened folder, move back to parent folder.
        adapter.moveToParentFolder();
        return;
      }

      // Accounting for the folder view.
      position--;
    }

    final Cursor cursor = adapter.getCursor();
    if (cursor == null) {
      return;
    }

    cursor.moveToPosition(position);

    int type = cursor.getInt(cursor.getColumnIndexOrThrow(Bookmarks.TYPE));
    if (type == Bookmarks.TYPE_FOLDER) {
      // If we're clicking on a folder, update adapter to move to that folder
      final int folderId = cursor.getInt(cursor.getColumnIndexOrThrow(Bookmarks._ID));
      final String folderTitle = adapter.getFolderTitle(parent.getContext(), cursor);
      adapter.moveToChildFolder(folderId, folderTitle);
    } else {
      // Otherwise, just open the URL
      final String url = cursor.getString(cursor.getColumnIndexOrThrow(URLColumns.URL));

      // This item is a TwoLinePageRow, so we allow switch-to-tab.
      getOnUrlOpenListener()
          .onUrlOpen(url, EnumSet.of(OnUrlOpenListener.Flags.ALLOW_SWITCH_TO_TAB));
    }
  }
  protected boolean updateScreen(int state, TnScreen screen) {
    switch (state) {
      case STATE_MAIN:
        {
          PoiDataWrapper poiDataManager = (PoiDataWrapper) model.get(KEY_O_POI_DATA_WRAPPER);
          updateCurrentLocationItem();
          if (!poiDataManager.isDoingRequest()) {

            if (placeList != null && placeListAdapter != null) {
              if (poiDataManager.getAddressSize() > 0) {
                placeListAdapter.setPoiDataWrapper(poiDataManager.getPublisher());
                (placeListAdapter).notifyDataSetChanged();
                stopLoad(placeList);
              }
              if (model.getBool(KEY_B_FORBID_LIST_HITBOTTOM)) {
                placeList.setHitBottomLoadEnable(false);
                placeList.setPullLoadEnable(true);
              } else {
                placeList.setHitBottomLoadEnable(poiDataManager.isHasMorePoi());
              }
            }
          } else {
            if (placeList != null && placeListAdapter != null) {
              placeList.setHitBottomLoadEnable(true);
            }
          }
          break;
        }
      case STATE_CUSTOM_PLACE:
        {
          ListView categoryListView =
              (ListView)
                  ((View) ((CitizenScreen) screen).getContentContainer().getNativeUiComponent())
                      .findViewById(R.id.addplaceCustomCategoryList);
          int selectedIndex = this.model.getInt(KEY_I_SELECTED_CATEGORY_INDEX);
          categoryListView.setItemChecked(
              selectedIndex + categoryListView.getHeaderViewsCount() + 1, true);
          if (categoryListAdapter != null) {
            categoryListAdapter.notifyDataSetChanged();
          }
          return true;
        }
    }
    return false;
  }
示例#21
0
  @Override
  public boolean onContextItemSelected(MenuItem item) {
    AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    Tag currentTag = null;
    int actualPos = 0;
    try {
      if (UpdateTagService.tagUpdateLock.tryLock(500, TimeUnit.MILLISECONDS)) {
        actualPos = info.position - tagListView.getHeaderViewsCount();
        if (actualPos < 0) {
          return false;
        }
        currentTag = tags.getTags().get(actualPos);
      } else return false;
    } catch (InterruptedException e) {
      e.printStackTrace();
      return false;
    }

    TagRequestHandler tagHandler = new TagRequestHandler();

    if (item.getTitle().equals("Thumb Up")) {
      currentTag.setIs_thumbedup(true);
      currentTag.setThumbup_count(currentTag.getThumbup_count() + 1);
      adapter.notifyDataSetChanged();
      tagHandler.thumbupAction(
          currentTag.get_id(), currentTag.getLocation(), currentTag.getLocation_type());
      return true;
    } else if (item.getTitle().equals("Follow")) {
      tagHandler.createFollowing(currentTag.getUser_id(), currentTag.getLocation_type());
      return true;
    } else if (item.getTitle().equals("Unfollow")) {
      tagHandler.unfollow(currentTag.getUser_id());
      return true;
    } else if (item.getTitle().equals("Show Original")) {
      tagHandler.showOrig(currentTag.getParent_id(), currentTag.get_id());
      return true;
    } else if (item.getTitle().equals("Reply")) {
      tagHandler.loadReply(currentTag);
      return true;
    } else {
      return super.onContextItemSelected(item);
    }
  }
  @Override
  protected void onResume() {
    super.onResume();

    // the current blog may have changed while we were away
    setupCurrentBlog();
    if (mMenuDrawer != null) {
      updateMenuDrawer();
    }

    Blog currentBlog = WordPress.getCurrentBlog();

    if (currentBlog != null && mListView != null && mListView.getHeaderViewsCount() > 0) {
      for (int i = 0; i < blogIDs.length; i++) {
        if (blogIDs[i] == currentBlog.getId()) {
          mBlogSpinner.setSelection(i);
        }
      }
    }
  }
 @Override
 public void handleMsg(Message msg) {
   String json = msg.getData().getString(Constant.JSON_DATA);
   if (TextUtils.equals(json, getString(R.string.try_agin))) {
     setRefreFalse();
     return;
   }
   switch (msg.what) {
     case TAG_SALE_BUSSINESS_LIST:
       data = JosnUtil.gson.fromJson(json, new TypeToken<KeFuData>() {}.getType());
       if (TextUtils.equals("0", data.getResult())) {
         break;
       }
       if (listView.getHeaderViewsCount() < 1) {
         break;
       }
       ((TextView) headView.findViewById(R.id.name)).setText(data.getSaledetail().getS_showname());
       ((TextView) headView.findViewById(R.id.time))
           .setText(MethodUtils.returnTime(data.getSaledetail().getS_lastim()));
       if (TextUtils.equals("0", data.getSaledetail().getS_sex())) {
         ((ImageView) headView.findViewById(R.id.avatar)).setImageResource(R.mipmap.male_yewu);
       } else {
         ((ImageView) headView.findViewById(R.id.avatar)).setImageResource(R.mipmap.meal_yewu);
       }
       if (adapter != null) {
         conversationList.clear();
         conversationList.addAll(loadConversationsWithRecentChat());
         for (int i = 0; i < conversationList.size(); i++) {
           EMConversation emcon = conversationList.get(i);
           if (TextUtils.equals(emcon.getUserName(), data.getSaledetail().getS_imid())) {
             if (headView != null) {
               listView.removeHeaderView(headView);
               listView.setAdapter(adapter);
             }
           }
         }
       }
       break;
   }
 }
  @Override
  public boolean onContextItemSelected(MenuItem item) {
    boolean handled = false;
    boolean deleteMessage = false;
    if (item.getItemId() == R.id.delete_message) {
      deleteMessage = true;
      handled = true;
    } else if (item.getItemId() == R.id.delete_conversation) {
      deleteMessage = false;
      handled = true;
    }
    if (listView.getHeaderViewsCount() >= 1) {
      EMConversation tobeDeleteCons =
          adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position - 1);
      // 删除此会话
      EMChatManager.getInstance()
          .deleteConversation(
              tobeDeleteCons.getUserName(), tobeDeleteCons.isGroup(), deleteMessage);
      InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
      inviteMessgeDao.deleteMessage(tobeDeleteCons.getUserName());
      adapter.remove(tobeDeleteCons);
      adapter.notifyDataSetChanged();
    } else {
      EMConversation tobeDeleteCons =
          adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
      // 删除此会话
      EMChatManager.getInstance()
          .deleteConversation(
              tobeDeleteCons.getUserName(), tobeDeleteCons.isGroup(), deleteMessage);
      InviteMessgeDao inviteMessgeDao = new InviteMessgeDao(getActivity());
      inviteMessgeDao.deleteMessage(tobeDeleteCons.getUserName());
      adapter.remove(tobeDeleteCons);
      adapter.notifyDataSetChanged();
    }

    // 更新消息未读数
    //		((MainActivity) getActivity()).updateUnreadLabel();

    return handled ? true : super.onContextItemSelected(item);
  }
示例#25
0
  @Override
  public boolean onContextItemSelected(MenuItem item) {

    AdapterView.AdapterContextMenuInfo info =
        (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();

    int longClickItemIndex = info.position - mListView.getHeaderViewsCount();
    if (longClickItemIndex < mWeiboList.size()) {
      int menuItemIndex = item.getItemId();
      FavoriteItem favoriteItem = mWeiboList.get(longClickItemIndex);
      switch (menuItemIndex) {
        case 0:
          canclefavoriteMoving(favoriteItem.id, longClickItemIndex);
          break;

        default:
          break;
      }
    }

    return true;
  }
  @Override
  protected void initView() {
    ivUserLogo.setImageResource(R.drawable.ic_head_default);
    ivUserLogo.setOnClickListener(this);
    btnSetting.setOnClickListener(this);
    ivScan.setOnClickListener(this);
    // 不启动任何刷新
    plServiceList.setMode(Mode.PULL_FROM_START);
    // 不显示指示器
    plServiceList.setShowIndicator(false);
    plServiceList
        .getLoadingLayoutProxy()
        .setLastUpdatedLabel(SharedPreferenceManager.getInstance().getString(getFragmentTag(), ""));
    plServiceList.setOnPullEventListener(pullEventListener);
    plServiceList.setOnRefreshListener(this);
    listView = plServiceList.getRefreshableView();
    listView.setOnItemClickListener(itemClick);
    initUserMsg();

    if (serviceHeaderView != null) listView.removeHeaderView(serviceHeaderView);
    if (listView.getHeaderViewsCount() == 0) {
      serviceHeaderView =
          new ServiceHeaderView(getActivity(), new ArrayList<SystemPromotionBanner>());
      listView.addHeaderView(serviceHeaderView);
    }

    adapter =
        new SystemPromotionListAdapter(getActivity(), new ArrayList<SystemPromotionDiscovery>());
    listView.setAdapter(adapter);

    requestSystemMessage();
    if (!SharedPreferenceManager.getInstance().getBoolean("isClickSetting", false)
        && SharedPreferenceManager.getInstance().getBoolean("isHaveNewVersion", false)) {
      ivVersionFlag.setVisibility(View.VISIBLE);
    } else {
      ivVersionFlag.setVisibility(View.GONE);
    }
  }
  @Override
  public boolean onTouch(View view, MotionEvent motionEvent) {
    if (mViewWidth < 2) {
      mViewWidth = mListView.getWidth();
    }

    switch (motionEvent.getActionMasked()) {
      case MotionEvent.ACTION_DOWN:
        {
          if (mPaused) {
            return false;
          }

          if (mSwiping) {
            return true;
          }

          // TODO: ensure this is a finger, and set a flag

          // Find the child view that was touched (perform a hit test)
          Rect rect = new Rect();
          int childCount = mListView.getChildCount();
          int headerCount = mListView.getHeaderViewsCount();
          int footerCount = mListView.getFooterViewsCount();
          int[] listViewCoords = new int[2];
          mListView.getLocationOnScreen(listViewCoords);
          int x = (int) motionEvent.getRawX() - listViewCoords[0];
          int y = (int) motionEvent.getRawY() - listViewCoords[1];
          View child = null;
          for (int i = headerCount; i < (childCount - footerCount); i++) {
            child = mListView.getChildAt(i);
            child.getHitRect(rect);
            if (rect.contains(x, y)) {
              mDownView = child;
              break;
            }
          }

          if (mDownView != null) {

            mDownX = motionEvent.getRawX();
            mDownY = motionEvent.getRawY();
            mDownPosition = mListView.getPositionForView(mDownView);
            if (mDownPosition != ListView.INVALID_POSITION
                && mDownPosition < mListView.getAdapter().getCount()) {
              if (mListView.getAdapter().getItem(mDownPosition) instanceof Card) {
                if (mCallbacks.canDismiss(
                    mDownPosition, (Card) mListView.getAdapter().getItem(mDownPosition))) {
                  mVelocityTracker = VelocityTracker.obtain();
                  mVelocityTracker.addMovement(motionEvent);
                } else {
                  mDownView = null;
                }
              } else {
                mDownView = null;
              }
            } else {
              mDownView = null;
            }
          }
          view.onTouchEvent(motionEvent);
          return true;
          // return false;
        }

      case MotionEvent.ACTION_UP:
        {
          if (mVelocityTracker == null) {
            break;
          }

          float deltaX = motionEvent.getRawX() - mDownX;
          mVelocityTracker.addMovement(motionEvent);
          mVelocityTracker.computeCurrentVelocity(1000);
          float velocityX = mVelocityTracker.getXVelocity();
          float absVelocityX = Math.abs(velocityX);
          float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
          boolean dismiss = false;
          boolean dismissRight = false;
          if (Math.abs(deltaX) > mViewWidth / swipeDistanceDivisor && mSwiping) {
            dismiss = true;
            dismissRight = deltaX > 0;
          } else if (mMinFlingVelocity <= absVelocityX
              && absVelocityX <= mMaxFlingVelocity
              && absVelocityY < absVelocityX
              && mSwiping) {
            // dismiss only if flinging in the same direction as dragging
            dismiss = (velocityX < 0) == (deltaX < 0);
            dismissRight = mVelocityTracker.getXVelocity() > 0;
          }
          if (dismiss && mDownPosition != ListView.INVALID_POSITION) {
            // dismiss
            dismiss(mDownView, mDownPosition - mListView.getHeaderViewsCount(), dismissRight);

          } else {
            // cancel
            mDownView
                .animate()
                .translationX(0)
                .alpha(1)
                .setDuration(mAnimationTime)
                .setListener(null);
          }

          mVelocityTracker.recycle();
          mVelocityTracker = null;
          mDownX = 0;
          mDownY = 0;
          mDownView = null;
          mDownPosition = ListView.INVALID_POSITION;
          if (mSwiping) {
            // To prevent onClick event with a fast swipe
            mSwiping = false;
            return true;
          }
          mSwiping = false;
          break;
        }

      case MotionEvent.ACTION_CANCEL:
        {
          if (mVelocityTracker == null) {
            break;
          }

          if (mDownView != null) {
            // cancel
            mDownView
                .animate()
                .translationX(0)
                .alpha(1)
                .setDuration(mAnimationTime)
                .setListener(null);
          }
          mVelocityTracker.recycle();
          mVelocityTracker = null;
          mDownX = 0;
          mDownY = 0;
          mDownView = null;
          mDownPosition = ListView.INVALID_POSITION;
          mSwiping = false;
          break;
        }

      case MotionEvent.ACTION_MOVE:
        {
          if (mVelocityTracker == null || mPaused) {
            break;
          }

          mVelocityTracker.addMovement(motionEvent);
          float deltaX = motionEvent.getRawX() - mDownX;
          float deltaY = motionEvent.getRawY() - mDownY;
          boolean movementAllowed = isSwipeMovementAllowed(deltaX);
          if (Math.abs(deltaX) > mSlop
              && Math.abs(deltaY) < Math.abs(deltaX) / 2
              && movementAllowed) {
            mSwiping = true;
            mSwipingSlop = (deltaX > 0 ? mSlop : -mSlop);
            mListView.requestDisallowInterceptTouchEvent(true);

            // Cancel ListView's touch (un-highlighting the item)
            MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
            cancelEvent.setAction(
                MotionEvent.ACTION_CANCEL
                    | (motionEvent.getActionIndex() << MotionEvent.ACTION_POINTER_INDEX_SHIFT));
            mListView.onTouchEvent(cancelEvent);
            view.onTouchEvent(cancelEvent);
            cancelEvent.recycle();
          }

          if (mSwiping) {
            mDownView.setTranslationX(deltaX - mSwipingSlop);
            mDownView.setAlpha(Math.max(0f, Math.min(1f, 1f - 2f * Math.abs(deltaX) / mViewWidth)));
            return true;
          }
          break;
        }
    }
    return false;
  }
 @Override
 public void onListItemClick(final ListView l, final View v, final int position, final long id) {
   if (mAccountId <= 0) return;
   final int adapter_pos = position - l.getHeaderViewsCount();
   final twitter4j.Activity item = mAdapter.getItem(adapter_pos);
   final User[] sources = item.getSources();
   final Status[] target_statuses = item.getTargetStatuses();
   final int sources_length = sources != null ? sources.length : 0;
   final Action action = item.getAction();
   final boolean hires_profile_image = getResources().getBoolean(R.bool.hires_profile_image);
   if (sources_length > 0) {
     final Status[] target_objects = item.getTargetObjectStatuses();
     switch (action.getActionId()) {
       case Action.ACTION_FAVORITE:
         {
           if (sources_length == 1) {
             openUserProfile(
                 getActivity(), new ParcelableUser(sources[0], mAccountId, hires_profile_image));
           } else {
             if (target_statuses != null && target_statuses.length > 0) {
               final Status status = target_statuses[0];
               openStatus(
                   getActivity(),
                   new ParcelableStatus(status, mAccountId, false, hires_profile_image));
             }
           }
           break;
         }
       case Action.ACTION_FOLLOW:
         {
           if (sources_length == 1) {
             openUserProfile(
                 getActivity(), new ParcelableUser(sources[0], mAccountId, hires_profile_image));
           } else {
             openUserFollowers(getActivity(), mAccountId, mAccountId, null);
           }
           break;
         }
       case Action.ACTION_MENTION:
         {
           if (target_objects != null && target_objects.length > 0) {
             final Status status = target_objects[0];
             openStatus(
                 getActivity(),
                 new ParcelableStatus(status, mAccountId, false, hires_profile_image));
           }
           break;
         }
       case Action.ACTION_REPLY:
         {
           if (target_statuses != null && target_statuses.length > 0) {
             final Status status = target_statuses[0];
             openStatus(
                 getActivity(),
                 new ParcelableStatus(status, mAccountId, false, hires_profile_image));
           }
           break;
         }
       case Action.ACTION_RETWEET:
         {
           if (sources_length == 1) {
             openUserProfile(
                 getActivity(), new ParcelableUser(sources[0], mAccountId, hires_profile_image));
           } else {
             if (target_objects != null && target_objects.length > 0) {
               final Status status = target_objects[0];
               openStatus(
                   getActivity(),
                   new ParcelableStatus(status, mAccountId, false, hires_profile_image));
             }
           }
           break;
         }
     }
   }
 }
示例#29
0
  /** 界面预设 */
  private void prepare() {
    if (listNews.getHeaderViewsCount() > 0) {
      return;
    }
    animRight =
        new RotateAnimation(
            -30, 30f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    animRight.setDuration(1000);
    animRight.setAnimationListener(listener);
    animLeft =
        new RotateAnimation(
            30f, -30f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
    animLeft.setDuration(1000);
    animLeft.setAnimationListener(listener);
    View viewHead = LayoutInflater.from(this.getActivity()).inflate(R.layout.div_home_head, null);
    listNews.addHeaderView(viewHead);
    scrollEntry = (HorizontalScrollViewEx) viewHead.findViewById(R.id.home_scroll_entry);
    scrollEntry.setHorizontalScrollViewListenner(
        new HorizontalScrollViewEx.HorizontalScrollViewListenner() {
          @Override
          public void onScrollChanged(int x, int y, int oldx, int oldy) {
            if (x > oldx && x > 50) {
              imgDot1.setImageResource(R.drawable.icon_dot_unselected);
              imgDot2.setImageResource(R.drawable.icon_dot_selected);
            } else if (x < oldx && x < 50) {
              imgDot1.setImageResource(R.drawable.icon_dot_selected);
              imgDot2.setImageResource(R.drawable.icon_dot_unselected);
            }
          }
        });
    viewEntry1 = (View) viewHead.findViewById(R.id.home_layout_entry1);
    viewEntry2 = (View) viewHead.findViewById(R.id.home_layout_entry2);
    viewEntry3 = (View) viewHead.findViewById(R.id.home_layout_entry3);
    viewEntry4 = (View) viewHead.findViewById(R.id.home_layout_entry4);
    viewEntry5 = (View) viewHead.findViewById(R.id.home_layout_entry5);
    viewEntry6 = (View) viewHead.findViewById(R.id.home_layout_entry6);
    btnRegion.getBackground().setAlpha(200);
    btnSearch.getBackground().setAlpha(200);
    btnBell.setImageAlpha(200);
    imgDot1 = (ImageView) viewHead.findViewById(R.id.home_image_dot1);
    imgDot2 = (ImageView) viewHead.findViewById(R.id.home_image_dot2);
    browser = (ScrollWebView) viewHead.findViewById(R.id.home_browser);

    DisplayMetrics metrics = new DisplayMetrics();
    this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
    LayoutParams lp = (LayoutParams) browser.getLayoutParams();
    lp.height = metrics.widthPixels * 7 / 10;
    browser.setLayoutParams(lp);

    browser.getSettings().setJavaScriptEnabled(true);
    browser.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    browser.setWebViewClient(
        new WebViewClient() {
          @Override
          public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Intent intent = new Intent(HomeActivity.this.getActivity(), BrowserActivity.class);
            intent.putExtra("url", url);
            startActivity(intent);
            browser.pauseTimers();
            browser.resumeTimers();
            return true;
          }

          @Override
          public void onReceivedError(
              WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            browser.loadUrl("about:blank");
          }
        });

    View viewActivity1 = (View) viewHead.findViewById(R.id.home_layout_left);
    viewActivity1.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            String token = "";
            if (null != Me.instance) {
              token = Me.instance.token;
            }
            String regionId = "";
            if (null != Profile.instance().region) {
              regionId = String.valueOf(Profile.instance().region.id);
            }
            Helper.openBrowser(
                HomeActivity.this.getActivity(), Networking.fetchURL("activity1", token, regionId));
          }
        });
    View viewActivity2 = (View) viewHead.findViewById(R.id.home_layout_right);
    viewActivity2.setOnClickListener(
        new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            String token = "";
            if (null != Me.instance) {
              token = Me.instance.token;
            }
            String regionId = "";
            if (null != Profile.instance().region) {
              regionId = String.valueOf(Profile.instance().region.id);
            }
            Helper.openBrowser(
                HomeActivity.this.getActivity(), Networking.fetchURL("activity2", token, regionId));
          }
        });
    this.getActivity().findViewById(R.id.home_layout_header).bringToFront();
  }
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    int act = event.getAction();
    float y = event.getY();
    final int oldChoose = choose;
    // 计算手指位置,找到对应的段,让mList移动段开头的位置上
    int selectIndex = (int) (y / (mHight / letters.length));

    if (selectIndex > -1 && selectIndex < letters.length) { // 防止越界
      String key = letters[selectIndex];
      if (alphaIndexer.containsKey(key)) {
        int pos = alphaIndexer.get(key);
        if (mList.getHeaderViewsCount() > 0) { // 防止ListView有标题栏,本例中没有。
          this.mList.setSelectionFromTop(pos + mList.getHeaderViewsCount(), 0);
        } else {
          this.mList.setSelectionFromTop(pos, 0);
        }
        mDialogText.setText(letters[selectIndex]);
      }
    }

    switch (act) {
      case MotionEvent.ACTION_DOWN:
        showBkg = true;

        if (oldChoose != selectIndex) {
          if (selectIndex > 0 && selectIndex < letters.length) {
            choose = selectIndex;
            invalidate();
          }
        }

        if (mHandler != null) {
          mHandler.post(
              new Runnable() {
                @Override
                public void run() {
                  if (mDialogText != null && mDialogText.getVisibility() == View.INVISIBLE) {
                    mDialogText.setVisibility(VISIBLE);
                  }
                }
              });
        }
        break;
      case MotionEvent.ACTION_MOVE:
        if (oldChoose != selectIndex) {
          if (selectIndex > 0 && selectIndex < letters.length) {
            choose = selectIndex;
            invalidate();
          }
        }
        break;
      case MotionEvent.ACTION_UP:
        showBkg = false;
        choose = -1;
        if (mHandler != null) {
          mHandler.post(
              new Runnable() {
                @Override
                public void run() {
                  if (mDialogText != null && mDialogText.getVisibility() == View.VISIBLE) {
                    mDialogText.setVisibility(INVISIBLE);
                  }
                }
              });
        }
        break;
      default:
        break;
    }

    return super.onTouchEvent(event);
  }