Java Code Examples for android.view.View

The following are top voted examples for showing how to use android.view.View. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: my-ministry-assistant   File: EntryTypeManagerEditorFrag.java View source code 8 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	View root = inflater.inflate(R.layout.entry_type_manager_editor, container, false);
	Bundle args = getArguments();
	if(args != null && args.containsKey(ARG_ENTRY_TYPE_ID))
		setPublication(args.getLong(ARG_ENTRY_TYPE_ID));
	
	setHasOptionsMenu(true);
	
	et_name = (EditText) root.findViewById(R.id.et_name);
	cb_is_active = (CheckBox) root.findViewById(R.id.cb_is_active);
	tv_note = (TextView) root.findViewById(R.id.tv_note);
	
	database = new MinistryService(getActivity().getApplicationContext());
	
   	return root;
}
 
Example 2
Project: platform_tools_adt_idea   File: MyActivity.java View source code 8 votes vote down vote up
@Override
public void test1() {
  ActionBar actionBar = getActionBar();
  GridLayout gridLayout = new GridLayout(null);
  int x = View.DRAWING_CACHE_QUALITY_AUTO;
  int y = View.MEASURED_HEIGHT_STATE_SHIFT;
  int alignmentMode = gridLayout.getAlignmentMode();
  gridLayout.setRowOrderPreserved(true);
  setContentView(R.layout.main);
}
 
Example 3
Project: dlna   File: PullToUpdataListView.java View source code 7 votes vote down vote up
private void measureView(View child) {
	ViewGroup.LayoutParams p = child.getLayoutParams();
	if (p == null) {
		p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
	}
	int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
	int lpHeight = p.height;
	int childHeightSpec;
	if (lpHeight > 0) {
		childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
	} else {
		childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
	}
	child.measure(childWidthSpec, childHeightSpec);
}
 
Example 4
Project: ExcusePro   File: SearchView.java View source code 7 votes vote down vote up
public boolean onKey(View v, int keyCode, KeyEvent event) {
    // guard against possible race conditions
    if (mSearchable == null) {
        return false;
    }

    if (DBG) {
        Log.d(LOG_TAG, "mTextListener.onKey(" + keyCode + "," + event + "), selection: "
                + mQueryTextView.getListSelection());
    }

    // If a suggestion is selected, handle enter, search key, and action keys
    // as presses on the selected suggestion
    if (mQueryTextView.isPopupShowing()
            && mQueryTextView.getListSelection() != ListView.INVALID_POSITION) {
        return onSuggestionsKey(v, keyCode, event);
    }

    // If there is text in the query box, handle enter, and action keys
    // The search key is handled by the dialog's onKeyDown().
    if (!mQueryTextView.isEmpty() && KeyEventCompat.hasNoModifiers(event)) {
        if (event.getAction() == KeyEvent.ACTION_UP) {
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                v.cancelLongPress();

                // Launch as a regular search.
                launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, mQueryTextView.getText()
                        .toString());
                return true;
            }
        }
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            // TODO SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode);
            // TODO if ((actionKey != null) && (actionKey.getQueryActionMsg() != null)) {
            // TODO     launchQuerySearch(keyCode, actionKey.getQueryActionMsg(), mQueryTextView
            // TODO             .getText().toString());
            // TODO     return true;
            // TODO }
        }
    }
    return false;
}
 
Example 5
Project: nptornews   File: DragNDropListView.java View source code 7 votes vote down vote up
private void drag(int x, int y) {
  if (mDragView == null) {
    return;
  }
  WindowManager.LayoutParams layoutParams =
      (WindowManager.LayoutParams) mDragView.getLayoutParams();
  // -- because it's a list; never want it to move left or right
  layoutParams.x = 0;
  layoutParams.y = y - mDragPointOffset;

  WindowManager mWindowManager =
      (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
  mWindowManager.updateViewLayout(mDragView, layoutParams);


  int lineBeforeIndex = calculateDropBeforePosition(x, y);
  if (lineBeforeIndex == INVALID_POSITION) {
    dropPointView.setVisibility(View.GONE);
  } else {
    View v = getChildAt(lineBeforeIndex - getFirstVisiblePosition());
    if (v != null) {
      int[] coordinates = new int[42];
      v.getLocationInWindow(coordinates);
      WindowManager.LayoutParams dropViewParams =
          (WindowManager.LayoutParams)dropPointView.getLayoutParams();
      dropViewParams.x = 0;
      dropViewParams.y = coordinates[1] - (dropPointView.getHeight() / 2);
      dropPointView.setVisibility(View.VISIBLE);
      mWindowManager.updateViewLayout(dropPointView, dropViewParams);
    } else {
      // TODO: capture case where lineBeforeIndex == getLastVisiblePosition
      // + 1 and scroll the list?
      Log.e(LOG_TAG, "Could not find the view for item " + lineBeforeIndex
          + " so not drawing a drop indicator. Should be between " +
          getFirstVisiblePosition() + " and " + getLastVisiblePosition());
      dropPointView.setVisibility(View.GONE);
    }
  }

  if (mDragListener != null) {
    mDragListener.onDrag(x, y, this);
  }
}
 
Example 6
Project: androiddevice.info   File: MainActivity.java View source code 7 votes vote down vote up
private void initNavigationDrawer(){
    mDrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            R.drawable.ic_drawer,  /* nav drawer icon */
            0, /* "open drawer" description */
            0  /* "close drawer" description */
    ) {

        /** Called when a drawer has settled in a completely closed state. */
        public void onDrawerClosed(View view) {
            supportInvalidateOptionsMenu();
        }

        /** Called when a drawer has settled in a completely open state. */
        public void onDrawerOpened(View drawerView) {
            drawerView.bringToFront();
            supportInvalidateOptionsMenu();
        }
    };


    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
            R.layout.list_item, new String[]{getString(R.string.action_about), getString(R.string.action_send)});

    mDrawerOptions.setAdapter(adapter);
    mDrawerOptions.setOnItemClickListener(MainActivity.this);

    mDrawerToggle.setDrawerIndicatorEnabled(true);
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, Gravity.LEFT);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
}
 
Example 7
Project: arduino-android   File: InputController.java View source code 6 votes vote down vote up
@Override
public void onClick(View v) {
	// send the number pressed to the Arduino
	index = (Integer)v.getTag();
//	toast("i="+ index);
	mHostActivity.sendCommand((byte)1,(byte)0, index);
}
 
Example 8
Project: arduino-android   File: DroidTempLogger.java View source code 6 votes vote down vote up
public void onClick(View v) {
	int vId = v.getId();
	switch (vId) {
	case R.id.inputLabel:
		showTabContents(true);
		break;
	}
}
 
Example 9
Project: my-ministry-assistant   File: HouseholderRecentActivityAdapter.java View source code 6 votes vote down vote up
@Override
   public View newView(Context context, Cursor cur, ViewGroup parent) {
	LayoutInflater li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       View view = li.inflate(LAYOUT_ID, parent, false);
	ViewHolder holder = new ViewHolder();
	holder.activity_title = (TextView) view.findViewById(R.id.activity_title);
	holder.activity_publications = (LinearLayout) view.findViewById(R.id.activity_publications);
	holder.activity_notes_layout = (LinearLayout) view.findViewById(R.id.activity_notes_layout);
	holder.activity_notes = (TextView) view.findViewById(R.id.activity_notes);
	holder.activity_date = (TextView) view.findViewById(R.id.activity_date);
	view.setTag(holder);
	return view;
}
 
Example 10
Project: my-ministry-assistant   File: PublisherEditorFragment.java View source code 6 votes vote down vote up
public void fillForm() {
	et_name.setError(null);
	if(publisherId == CREATE_ID) {
		et_name.setText("");
		cb_is_active.setChecked(true);
		
		recent_activity_text.setVisibility(View.GONE);
		getListView().setVisibility(View.GONE);
		getListView().getEmptyView().setVisibility(View.GONE);
	}
	else {
		recent_activity_text.setVisibility(View.VISIBLE);
		getListView().setVisibility(View.VISIBLE);
		getListView().getEmptyView().setVisibility(View.VISIBLE);
		
 	database.openWritable();
 	Cursor publisher = database.fetchPublisher((int)publisherId);
 	if(publisher.moveToFirst()) {
 		et_name.setText(publisher.getString(publisher.getColumnIndex(Publisher.NAME)));
 		cb_is_active.setChecked((publisher.getInt(publisher.getColumnIndex(Publisher.ACTIVE)) == 1) ? true : false);
 	}
 	else {
 		et_name.setText("");
 		cb_is_active.setChecked(true);
 	}
 	publisher.close();
 	activity = database.fetchActivityForPublisher((int) publisherId);
 	adapter.changeCursor(activity);
 	database.close();
 }
}
 
Example 11
Project: dlna   File: YouPlayerFullScreenPlayer.java View source code 6 votes vote down vote up
private void setPlayerMediaLayoutDefault(){
    	LOG.v(TAG, "setPlayerMediaLayoutDefault", "start");
//        mPlayerMediaVideoLayout.setVisibility(View.INVISIBLE);
        mPlayerMediaAudioLayout.setVisibility(View.INVISIBLE);
        mPlayerMediaRadioLayout.setVisibility(View.INVISIBLE);  
        if(mPlayerYouSurfaceView != null)
        	mPlayerYouSurfaceView.setVisibility(View.INVISIBLE);
        if(mPlayerSysSurfaceView != null)
        mPlayerSysSurfaceView.setVisibility(View.INVISIBLE);
//        mPlayerRelativeContainer.setVisibility(View.INVISIBLE);
//        (mView.findViewById(R.id.fullplayer_topbar)).setVisibility(View.INVISIBLE);
        if(mView != null)
        {
        	View view = mView.findViewById(R.id.fullplayer_bottombar);
        	if(view != null)
        	{
        		view.setVisibility(View.INVISIBLE);
        	}
        }
//        (mView.findViewById(R.id.fullplayer_bottombar)).setVisibility(View.INVISIBLE);
      
    }
 
Example 12
Project: my-ministry-assistant   File: SlideOutRightAnimator.java View source code 6 votes vote down vote up
@Override
public void prepare(View target) {
    ViewGroup parent = (ViewGroup)target.getParent();
    int distance = parent.getWidth() - target.getLeft();
    getAnimatorAgent().playTogether(
            ObjectAnimator.ofFloat(target, "alpha", 1, 0),
            ObjectAnimator.ofFloat(target,"translationX",0,distance)
    );
}
 
Example 13
Project: my-ministry-assistant   File: SlideInDownAnimator.java View source code 6 votes vote down vote up
@Override
public void prepare(View target) {
    int distance = target.getTop() + target.getHeight();
    getAnimatorAgent().playTogether(
            ObjectAnimator.ofFloat(target,"alpha",0,1),
            ObjectAnimator.ofFloat(target,"translationY",-distance,0)
    );
}
 
Example 14
Project: androhid   File: ButtonGridLayout.java View source code 6 votes vote down vote up
@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Measure the first child and get it's size
        View child = getChildAt(0);
        child.measure(MeasureSpec.UNSPECIFIED , MeasureSpec.UNSPECIFIED);

        // Make sure the other children are measured as well, to initialize
        for (int i = 1; i < getChildCount(); i++) {
            getChildAt(i).measure(MeasureSpec.UNSPECIFIED , MeasureSpec.UNSPECIFIED);
        }
        
        // Store these to be reused in onLayout.
//        mButtonWidth = child.getMeasuredWidth(); 
        mButtonWidth = (int)(( MeasureSpec.getSize(widthMeasureSpec) * 1.14 ) / ROWS);
        mButtonHeight = child.getMeasuredHeight();
        mWidthInc = mButtonWidth + getPaddingLeft() + getPaddingRight();
        mHeightInc = mButtonHeight + getPaddingTop() + getPaddingBottom();
        mHeight = ROWS * mHeightInc;

        final int width = resolveSize(COLUMNS * mWidthInc, widthMeasureSpec);
        final int height = resolveSize(mHeight, heightMeasureSpec);

        setMeasuredDimension(width, height);
    }
 
Example 15
Project: my-ministry-assistant   File: MainActivity.java View source code 6 votes vote down vote up
private View makeNavDrawerItem(final int itemId, ViewGroup container) {
    boolean selected = getDefaultNavDrawerItem() == itemId;
    int layoutToInflate = 0;
    
    if (itemId == NAVDRAWER_ITEM_SEPARATOR) {
        layoutToInflate = R.layout.navdrawer_separator;
    } else {
        layoutToInflate = R.layout.navdrawer_item;
    }
    
    View view = getLayoutInflater().inflate(layoutToInflate, container, false);

    if (isSeparator(itemId)) {
        // we are done
        UIUtils.setAccessibilityIgnore(view);
        return view;
    }

    ImageView iconView = (ImageView) view.findViewById(R.id.icon);
    TextView titleView = (TextView) view.findViewById(R.id.title);
    int iconId = itemId >= 0 && itemId < NAVDRAWER_ICON_RES_ID.length ? NAVDRAWER_ICON_RES_ID[itemId] : 0;
    int titleId = itemId >= 0 && itemId < NAVDRAWER_TITLE_RES_ID.length ? NAVDRAWER_TITLE_RES_ID[itemId] : 0;
    
    // set icon and text
    iconView.setVisibility(iconId > 0 ? View.VISIBLE : View.GONE);
    if (iconId > 0) {
        iconView.setImageResource(iconId);
    }
    titleView.setText(getString(titleId));

    formatNavDrawerItem(view, itemId, selected);

    view.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNavDrawerItemClicked(itemId);
        }
    });

    return view;
}
 
Example 16
Project: Gui2Go   File: EditorActivity.java View source code 6 votes vote down vote up
private void setWidgetMargins(View v, String top, String left,
                String bottom, String right) {
    ViewGroup.LayoutParams genericParams = v.getLayoutParams();
    RelativeLayout.LayoutParams relativeParams = null;

    if (v.getParent().getClass() == RelativeLayout.class) {
        relativeParams = (RelativeLayout.LayoutParams) genericParams;
    }

    if (!top.isEmpty()) {
        int topPixel = convertDipToPixel(Float.parseFloat(top));
        ((MarginLayoutParams) genericParams).topMargin = topPixel;
    }
    if (!left.isEmpty()) {
        int leftPixel = convertDipToPixel(Float.parseFloat(left));
        ((MarginLayoutParams) genericParams).leftMargin = leftPixel;
    }
    if (!bottom.isEmpty()) {
        int bottomPixel = convertDipToPixel(Float.parseFloat(bottom));
        ((MarginLayoutParams) genericParams).bottomMargin = bottomPixel;
    }
    if (!right.isEmpty()) {
        int rightPixel = convertDipToPixel(Float.parseFloat(right));
        ((MarginLayoutParams) genericParams).rightMargin = rightPixel;
    }

    if (relativeParams != null) {
        v.setLayoutParams(relativeParams);
    } else {
        v.setLayoutParams(genericParams);
    }
}
 
Example 17
Project: dlna   File: YouPlayerFullScreenPlayer.java View source code 6 votes vote down vote up
@Override
public void onDragged(boolean left) {
	LOG.v(TAG, "onDragged","draw x xol : left :"+left);
	View view = mView.findViewById(R.id.full_audio_text_container);
	if( left && view.getVisibility() == View.VISIBLE ){
		view.setVisibility(View.GONE);
	}else if( !left && view.getVisibility() == View.GONE ){
		view.setVisibility(View.VISIBLE);
	}
}
 
Example 18
Project: Gui2Go   File: EditorActivity.java View source code 6 votes vote down vote up
protected void ToggleFillHeight(View v) {
    int oldWidth = v.getWidth();
    LayoutParams params = null;
    if (v.getLayoutParams().height != -1) {
        if (v.getParent().getClass() == LinearLayout.class) {
            params = new LinearLayout.LayoutParams(oldWidth,
                            LayoutParams.MATCH_PARENT);
        } else if (v.getParent().getClass() == FrameLayout.class) {
            params = new FrameLayout.LayoutParams(oldWidth,
                            LayoutParams.MATCH_PARENT);
        } else if (v.getParent().getClass() == RelativeLayout.class) {
            params = new RelativeLayout.LayoutParams(oldWidth,
                            LayoutParams.MATCH_PARENT);
        } else if (v.getParent().getClass() == TableLayout.class) {
            params = new TableLayout.LayoutParams(oldWidth,
                            LayoutParams.MATCH_PARENT);
        } else if (v.getParent().getClass() == RadioGroup.class) {
            params = new RadioGroup.LayoutParams(oldWidth,
                            LayoutParams.MATCH_PARENT);
        }
    } else {
        if (v.getParent().getClass() == LinearLayout.class) {
            params = new LinearLayout.LayoutParams(oldWidth,
                            LayoutParams.WRAP_CONTENT);
        } else if (v.getParent().getClass() == FrameLayout.class) {
            params = new FrameLayout.LayoutParams(oldWidth,
                            LayoutParams.WRAP_CONTENT);
        } else if (v.getParent().getClass() == RelativeLayout.class) {
            params = new RelativeLayout.LayoutParams(oldWidth,
                            LayoutParams.WRAP_CONTENT);
        } else if (v.getParent().getClass() == TableLayout.class) {
            params = new TableLayout.LayoutParams(oldWidth,
                            LayoutParams.WRAP_CONTENT);
        } else if (v.getParent().getClass() == RadioGroup.class) {
            params = new RadioGroup.LayoutParams(oldWidth,
                            LayoutParams.WRAP_CONTENT);
        }
    }
    v.setLayoutParams(params);
    v.invalidate();
}
 
Example 19
Project: my-ministry-assistant   File: SlideInUpAnimator.java View source code 6 votes vote down vote up
@Override
public void prepare(View target) {
    ViewGroup parent = (ViewGroup)target.getParent();
    int distance = parent.getHeight() - target.getTop();
    getAnimatorAgent().playTogether(
            ObjectAnimator.ofFloat(target, "alpha", 0, 1),
            ObjectAnimator.ofFloat(target,"translationY",distance,0)
    );
}
 
Example 20
Project: androhid   File: ButtonGridLayout.java View source code 6 votes vote down vote up
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {    	
    int i = 0;
    
    // The last row is bottom aligned.
    int y = (b - t) - mHeight + getPaddingTop();
    for (int row = 0; row < ROWS; row++) {
        int x = getPaddingLeft();
        for (int col = 0; col < COLUMNS; col++) {
            View child = getChildAt(i);

            child.layout(x, y, x + mButtonWidth, y + mButtonHeight);

            x += mWidthInc;
            i++;
        }
        y += mHeightInc;
    }
  }
 
Example 21
Project: Gui2Go   File: EditorActivity.java View source code 6 votes vote down vote up
private View findView(float x, float y, ArrayList<View> targets) {
    final int count = targets.size();
    for (int i = 0; i < count; i++) {
        final View target = targets.get(i);
        if (target.getRight() > x && target.getTop() < y
                        && target.getBottom() > y && target.getLeft() < x) {
            return target;
        }
    }
    return null;
}
 
Example 22
Project: dlna   File: MoreAdapter.java View source code 6 votes vote down vote up
@Override
public View getView(int i, View subview, ViewGroup arg2) {
	 subview = View.inflate(context, R.layout.more_list_item, null);
	TextView tv =(TextView) subview.findViewById(R.id.tv_content);
	ImageView image = (ImageView)subview.findViewById(R.id.more_image);
	if(i == 0)
	{
		image.setImageResource(R.drawable.wifi_setting);
	}
	else if(i == 1)
	{
		image.setImageResource(R.drawable.route_setting);
	}
	else if(i == 2)
	{
		image.setImageResource(R.drawable.player_setting);
	}
	tv.setText(files.get(i));
	return subview;
}
 
Example 23
Project: my-ministry-assistant   File: PublishersFragment.java View source code 6 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
	View view = inflater.inflate(R.layout.publishers, container, false);
       
       view.findViewById(R.id.btn_add_item).setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			openEditor(PublisherEditorFragment.CREATE_ID);
		}
	});

   	fm = getActivity().getSupportFragmentManager();
   	
   	return view;
}
 
Example 24
Project: Gui2Go   File: EditorActivity.java View source code 6 votes vote down vote up
@Override
public void colorChanged(int color) {
    View view = findViewById(currentHighlightedID);
    if (view != null) {
        view.setBackgroundColor(color);
    }
}
 
Example 25
Project: dlna   File: YouPlayerMoreDialog.java View source code 6 votes vote down vote up
public static PopupWindow show(final View view,int speed,final OnClickListener listener ){	
	final PopupWindow pw = new PopupWindow(view.getContext());
	BitmapDrawable drawable = (BitmapDrawable) view.getResources().getDrawable(R.drawable.youplayer_fullplayer_more_bg);	
	pw.setBackgroundDrawable(drawable);
	int width = 800;
	int height = 400;
       try {
           WindowManager wm = (WindowManager)view.getContext().getSystemService(Context.WINDOW_SERVICE);
           width = wm.getDefaultDisplay().getWidth();
           height = wm.getDefaultDisplay().getHeight();
       } catch (Exception e) {
           e.printStackTrace();
       }
	pw.setWidth(width*3/8);
	pw.setHeight(height*3/8);
	ViewGroup contentView = (ViewGroup) LayoutInflater.from(view.getContext()).inflate(R.layout.youplayer_fullplayer_more_view, null);
	OnClickListener clistener = new OnClickListener() {	
		@Override
		public void onClick(View v) {
			listener.onClick(v);	
			pw.dismiss();	
		}
	};
	
	int[] speeds = new int[]{
		R.drawable.youplayer_fullplayer_bottom_btn_speed08,
		R.drawable.youplayer_fullplayer_bottom_btn_speed10,
		R.drawable.youplayer_fullplayer_bottom_btn_speed15,
		R.drawable.youplayer_fullplayer_bottom_btn_speed20,
	} ;
	
	
	contentView.findViewById(R.id.fullplayer_imgb_download).setOnClickListener(clistener);
	contentView.findViewById(R.id.fullplayer_imgb_share).setOnClickListener(clistener);
	
	ImageButton img_speed = (ImageButton) contentView.findViewById(R.id.fullplayer_imgb_speed);
	img_speed.setOnClickListener(clistener);
	img_speed.setImageResource(speeds[speed]);
	
	contentView.findViewById(R.id.fullplayer_imgb_track).setOnClickListener(clistener);
	
	ImageButton img_3d = (ImageButton) contentView.findViewById(R.id.fullplayer_imgb_3d);
	img_3d.setOnClickListener(clistener);
	
	contentView.findViewById(R.id.fullplayer_btm_imgb_lock).setOnClickListener(clistener);
	
	
	pw.setContentView(contentView);

	pw.setOutsideTouchable(false);
	pw.setTouchable(true);
	pw.setFocusable(true);
	pw.showAsDropDown(view,30,0);
	
	return pw;	
}
 
Example 26
Project: dlna   File: YouPlayerFullScreenPlayer.java View source code 6 votes vote down vote up
private void toHidePanel() throws YouPlayerException{
        if(!getObjectIsNull(mView) && isAllControllPanelIsVisible()){
//            (mView.findViewById(R.id.fullplayer_topbar)).setVisibility(View.INVISIBLE);
            (mView.findViewById(R.id.fullplayer_bottombar)).setVisibility(View.INVISIBLE);
            setPlayerSeekBarVolumeOrBrightVisibleChanged(PLAYER_UI_SHOW_TYPE_ALL_INVISIBLE);
            setRelativeListVisible(false);
            toExecuteNews();
        }
    }
 
Example 27
Project: ExcusePro   File: MenuItemImpl.java View source code 6 votes vote down vote up
public MenuItem setActionView(View view) {
    mActionView = view;
    mActionProvider = null;
    if (view != null && view.getId() == View.NO_ID && mId > 0) {
        view.setId(mId);
    }
    mMenu.onItemActionRequestChanged(this);
    return this;
}
 
Example 28
Project: ExcusePro   File: ScrollingTabContainerView.java View source code 6 votes vote down vote up
public void setTabSelected(int position) {
    mSelectedTabIndex = position;
    final int tabCount = mTabLayout.getChildCount();
    for (int i = 0; i < tabCount; i++) {
        final View child = mTabLayout.getChildAt(i);
        final boolean isSelected = i == position;
        child.setSelected(isSelected);
        if (isSelected) {
            animateToTab(position);
        }
    }
}
 
Example 29
Project: ExcusePro   File: IcsListPopupWindow.java View source code 6 votes vote down vote up
private int getMaxAvailableHeight(View anchor, int yOffset, boolean ignoreBottomDecorations) {
    final Rect displayFrame = new Rect();
    anchor.getWindowVisibleDisplayFrame(displayFrame);

    final int[] anchorPos = new int[2];
    anchor.getLocationOnScreen(anchorPos);

    int bottomEdge = displayFrame.bottom;
    if (ignoreBottomDecorations) {
        Resources res = anchor.getContext().getResources();
        bottomEdge = res.getDisplayMetrics().heightPixels;
    }
    final int distanceToBottom = bottomEdge - (anchorPos[1] + anchor.getHeight()) - yOffset;
    final int distanceToTop = anchorPos[1] - displayFrame.top + yOffset;

    // anchorPos[1] is distance from anchor to top of screen
    int returnedHeight = Math.max(distanceToBottom, distanceToTop);
    if (mPopup.getBackground() != null) {
        mPopup.getBackground().getPadding(mTempRect);
        returnedHeight -= mTempRect.top + mTempRect.bottom;
    }

    return returnedHeight;
}
 
Example 30
Project: BioWiki   File: AniUtils.java View source code 6 votes vote down vote up
public static void flyIn(View target, AnimationListener listener) {
    Context context = target.getContext();
    Animation animation = AnimationUtils.loadAnimation(context, R.anim.reader_flyin);
    if (animation == null)
        return;

    // add small overshoot for bounce effect
    animation.setInterpolator(new OvershootInterpolator(0.9f));
    long duration = context.getResources().getInteger(android.R.integer.config_mediumAnimTime);
    animation.setDuration((long) (duration * 1.5f));

    if (listener != null)
        animation.setAnimationListener(listener);

    target.startAnimation(animation);
    target.setVisibility(View.VISIBLE);
}
 
Example 31
Project: Gui2Go   File: SimpleStandardAdapter.java View source code 6 votes vote down vote up
private void removeHighlight(View v)
{
	if (((EditorActivity) activity).isLayout(v)) {
		v.setBackgroundDrawable(null);
	} else if (v.getClass() == ImageView.class) {
		((ImageView) v).setColorFilter(null);
	} else {
		v.getBackground().setColorFilter(null);
	}
	v.invalidate();
}
 
Example 32
Project: Gui2Go   File: SimpleStandardAdapter.java View source code 6 votes vote down vote up
private void hightlightTargetView(View v, String rgbValue, int borderId,
		boolean highlightInTree)
{
	if (tempHighlightedId != v.getId() && tempHighlightedId != 0) {
		removeHighlight(v);
	}
	if (((EditorActivity) activity).isLayout(v)) {
		v.setBackgroundResource(borderId);
	} else if (v.getClass() == ImageView.class) {
		((ImageView) v).setColorFilter(Color.parseColor(rgbValue),
				Mode.DARKEN);
	} else {
		v.getBackground().setColorFilter(Color.parseColor(rgbValue),
				Mode.DARKEN);
	}
}
 
Example 33
Project: googleio   File: Workspace.java View source code 6 votes vote down vote up
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
    int focusableScreen;
    if (mNextScreen != INVALID_SCREEN) {
        focusableScreen = mNextScreen;
    } else {
        focusableScreen = mCurrentScreen;
    }
    View v = getScreenAt(focusableScreen);
    if (v != null) {
        return v.requestFocus(direction, previouslyFocusedRect);
    }
    return false;
}
 
Example 34
Project: ExcusePro   File: BaseMenuPresenter.java View source code 6 votes vote down vote up
/**
 * Reuses item views when it can
 */
public void updateMenuView(boolean cleared) {
    final ViewGroup parent = (ViewGroup) mMenuView;
    if (parent == null) return;

    int childIndex = 0;
    if (mMenu != null) {
        mMenu.flagActionItems();
        ArrayList<MenuItemImpl> visibleItems = mMenu.getVisibleItems();
        final int itemCount = visibleItems.size();
        for (int i = 0; i < itemCount; i++) {
            MenuItemImpl item = visibleItems.get(i);
            if (shouldIncludeItem(childIndex, item)) {
                final View convertView = parent.getChildAt(childIndex);
                final MenuItemImpl oldItem = convertView instanceof MenuView.ItemView ?
                        ((MenuView.ItemView) convertView).getItemData() : null;
                final View itemView = getItemView(item, convertView, parent);
                if (item != oldItem) {
                    // Don't let old states linger with new data.
                    itemView.setPressed(false);
                    if (IS_HONEYCOMB) itemView.jumpDrawablesToCurrentState();
                }
                if (itemView != convertView) {
                    addItemView(itemView, childIndex);
                }
                childIndex++;
            }
        }
    }

    // Remove leftover views.
    while (childIndex < parent.getChildCount()) {
        if (!filterLeftoverView(parent, childIndex)) {
            childIndex++;
        }
    }
}
 
Example 35
Project: ExcusePro   File: AnimatorProxy.java View source code 6 votes vote down vote up
public int getScrollY() {
    View view = mView.get();
    if (view == null) {
        return 0;
    }
    return view.getScrollY();
}
 
Example 36
Project: ExcusePro   File: AnimatorProxy.java View source code 6 votes vote down vote up
public int getScrollX() {
    View view = mView.get();
    if (view == null) {
        return 0;
    }
    return view.getScrollX();
}
 
Example 37
Project: my-ministry-assistant   File: MainActivity.java View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR1)
@Override
   protected void onPostCreate(Bundle savedInstanceState) {
   	super.onPostCreate(savedInstanceState);
   	
   	setupNavDrawer();
   	
   	onNavDrawerItemClicked(getDefaultNavDrawerItem());
   	
   	if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {
    	View mainContent = findViewById(R.id.primary_fragment_container);
        if (mainContent != null) {
            mainContent.setAlpha(0);
            mainContent.animate().alpha(1).setDuration(MAIN_CONTENT_FADEIN_DURATION);
        } else {
            LOGE(TAG, "No view with ID primary_fragment_container to fade in.");
        }
   	}
   }
 
Example 38
Project: ExcusePro   File: IcsAdapterView.java View source code 6 votes vote down vote up
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
    View selectedView = getSelectedView();
    if (selectedView != null && selectedView.getVisibility() == VISIBLE
            && selectedView.dispatchPopulateAccessibilityEvent(event)) {
        return true;
    }
    return false;
}
 
Example 39
Project: swipelistview-android   File: SwipeListView.java View source code 6 votes vote down vote up
@Override
public void handleMessage(Message msg) {
	super.handleMessage(msg);
	if (mStepX == 0) {
		if (mIsInAnimation) {
			return;
		}
		mIsInAnimation = true;

		mView = (View) msg.obj;
		fromX = msg.arg1;
		toX = msg.arg2;

		mStepX = (int) ((toX - fromX) / STEP_X_GAP);
		if (Math.abs(toX - fromX) < STEP_X_GAP) {
			mView.scrollTo(toX, 0);
			swipeAnimationOver();
			return;
		}
	}

	fromX += mStepX;
	boolean isLastStep = (mStepX > 0 && fromX > toX) || (mStepX < 0 && fromX < toX);
	if (isLastStep) {
		fromX = toX;
	}

	mView.scrollTo(fromX, 0);
	ref.get().invalidate();

	if (!isLastStep) {
		this.sendEmptyMessageDelayed(0, SWIPE_ANIMATION_DELAY);
	} else {
		swipeAnimationOver();
	}
}
 
Example 40
Project: Blurry   File: BlurTask.java View source code 6 votes vote down vote up
public BlurTask(View target, BlurFactor factor, Callback callback) {
  target.setDrawingCacheEnabled(true);
  this.res = target.getResources();
  this.factor = factor;
  this.callback = callback;

  target.destroyDrawingCache();
  target.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
  capture = target.getDrawingCache();
  contextWeakRef = new WeakReference<>(target.getContext());
}
 
Example 41
Project: ExcusePro   File: MenuPopupHelper.java View source code 6 votes vote down vote up
public boolean tryShow() {
    mPopup = new IcsListPopupWindow(mContext, null, R.attr.popupMenuStyle);
    mPopup.setOnDismissListener(this);
    mPopup.setOnItemClickListener(this);

    mAdapter = new MenuAdapter(mMenu);
    mPopup.setAdapter(mAdapter);
    mPopup.setModal(true);

    View anchor = mAnchorView;
    if (anchor != null) {
        // Don't attach to the VTO unless the anchor itself is attached to avoid VTO-related leaks.
        if (anchor.getWindowToken() != null) {
            ViewTreeObserver vto = anchor.getViewTreeObserver();
            if (vto != mTreeObserver) {
                if (mTreeObserver != null && mTreeObserver.isAlive()) {
                    mTreeObserver.removeGlobalOnLayoutListener(this);
                }
                if ((mTreeObserver = vto) != null) {
                    vto.addOnGlobalLayoutListener(this);
                }
            }
        } else if (anchor instanceof View_HasStateListenerSupport) {
            ((View_HasStateListenerSupport) anchor).addOnAttachStateChangeListener(this);
        }
        mPopup.setAnchorView(anchor);
    } else {
        return false;
    }

    mPopup.setContentWidth(Math.min(measureContentWidth(mAdapter), mPopupMaxWidth));
    mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
    mPopup.show();
    mPopup.getListView().setOnKeyListener(this);
    return true;
}
 
Example 42
Project: ExcusePro   File: UserSettingsFragment.java View source code 6 votes vote down vote up
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.com_facebook_usersettingsfragment, container, false);
    loginButton = (LoginButton) view.findViewById(R.id.com_facebook_usersettingsfragment_login_button);
    loginButton.setProperties(loginButtonProperties);
    loginButton.setFragment(this);
    Session session = getSession();
    if (session != null && !session.equals(Session.getActiveSession())) {
        loginButton.setSession(session);
    }
    connectedStateLabel = (TextView) view.findViewById(R.id.com_facebook_usersettingsfragment_profile_name);
    
    // if no background is set for some reason, then default to Facebook blue
    if (view.getBackground() == null) {
        view.setBackgroundColor(getResources().getColor(R.color.com_facebook_blue));
    } else {
        view.getBackground().setDither(true);
    }
    return view;
}
 
Example 43
Project: ExcusePro   File: ActionMenuPresenter.java View source code 6 votes vote down vote up
public void run() {
    mMenu.changeMenuMode();
    final View menuView = (View) mMenuView;
    if (menuView != null && menuView.getWindowToken() != null && mPopup.tryShow()) {
        mOverflowPopup = mPopup;
    }
    mPostedOpenRunnable = null;
}
 
Example 44
Project: BioWiki   File: BWActionBarActivity.java View source code 6 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View view = super.getView(position, convertView, parent);
    MenuDrawerItem item = getItem(position);

    TextView titleTextView = (TextView) view.findViewById(R.id.menu_row_title);
    titleTextView.setText(item.getTitleRes());

    ImageView iconImageView = (ImageView) view.findViewById(R.id.menu_row_icon);
    iconImageView.setImageResource(item.getIconRes());
    // Hide the badge always
    view.findViewById(R.id.menu_row_badge).setVisibility(View.GONE);

    if (item.isSelected()) {
        // http://stackoverflow.com/questions/5890379/setbackgroundresource-discards-my-xml-layout-attributes
        int bottom = view.getPaddingBottom();
        int top = view.getPaddingTop();
        int right = view.getPaddingRight();
        int left = view.getPaddingLeft();
        view.setBackgroundResource(R.color.blue_dark);
        view.setPadding(left, top, right, bottom);
    } else {
        view.setBackgroundResource(R.drawable.md_list_selector);
    }
    // allow the menudrawer item to configure the view
    item.configureView(view);

    return view;
}
 
Example 45
Project: mclub-tracker-app   File: LocationActivity.java View source code 6 votes vote down vote up
private void setViewEnabled(int id, boolean enabled) {
    View view = findViewById(id);
    if(view == null) {
        return;
    }
    view.setEnabled(enabled);
}
 
Example 46
Project: googleio   File: Workspace.java View source code 6 votes vote down vote up
@Override
public boolean dispatchUnhandledMove(View focused, int direction) {
    if (direction == View.FOCUS_LEFT) {
        if (getCurrentScreen() > 0) {
            snapToScreen(getCurrentScreen() - 1);
            return true;
        }
    } else if (direction == View.FOCUS_RIGHT) {
        if (getCurrentScreen() < getScreenCount() - 1) {
            snapToScreen(getCurrentScreen() + 1);
            return true;
        }
    }
    return super.dispatchUnhandledMove(focused, direction);
}
 
Example 47
Project: AppCompat-Extension-Library   File: FloatingActionMenuAnimatorHoneycomb.java View source code 6 votes vote down vote up
@Override
public void prepareView(View view, float expandedTranslation, float collapsedTranslation, boolean expanded, boolean expandsHorizontally) {
    if (expandsHorizontally) {
        view.setTranslationX(expanded ? expandedTranslation : collapsedTranslation);
        view.setAlpha(expanded ? 1f : 0f);
    } else {
        view.setTranslationY(expanded ? expandedTranslation : collapsedTranslation);
        view.setAlpha(expanded ? 1f : 0f);
    }
}
 
Example 48
Project: NookPDFViewer   File: CustomGallery.java View source code 6 votes vote down vote up
@Override
    public boolean getChildStaticTransformation(View child, Transformation t) {
        View view = getSelectedView();
        if (view != null && !view.equals(child)) {
            t.clear();
            t.setAlpha(m_Alpha);
            t.setTransformationType(Transformation.TYPE_BOTH);
//            int idx = this.getSelectedItemPosition();
//            int idxc = this.getPositionForView(child);
//            Matrix mat = t.getMatrix();
//            if( idxc < idx)
//                mat.postTranslate(-29,0);
        } else {
            t.clear();
            t.setAlpha(m_Alpha);
            t.setTransformationType(Transformation.TYPE_BOTH);
            Matrix mat = t.getMatrix();
            Matrix mat1 = new Matrix();
            int centerx, centery;
            centery = child.getTop() + child.getMeasuredHeight() / 2;
            centerx = child.getLeft() + child.getMeasuredWidth() / 2;
            mat.postTranslate(-centerx, -centery);
            mat1.postScale(m_Size, m_Size);
            mat.postConcat(mat1);
            mat1 = new Matrix();
            mat1.postTranslate(centerx, centery);
            mat.postConcat(mat1);
            mat.postTranslate(50, 5);
      
        }
        return true;
        // return false;
    }
 
Example 49
Project: my-ministry-assistant   File: UIUtils.java View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static void setAccessibilityIgnore(View view) {
       view.setClickable(false);
       view.setFocusable(false);
       view.setContentDescription("");
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
       	view.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
       }
   }
 
Example 50
Project: cardslib   File: MultiChoiceAdapterHelperBase.java View source code 6 votes vote down vote up
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {

    //Check if the card is checkable
    if (!isCardCheckable(position)) {
        return false;
    }


    //Check the item
    int correctedPosition = correctPositionAccountingForHeader(adapterView, position);
    long handle = positionToSelectionHandle(correctedPosition);
    boolean wasChecked =  mAdapterView.isItemChecked((int)handle);

    // invoke the contextual action mode by setting the respective list item to the checked
    setItemChecked(handle, !wasChecked);
    view.setActivated(!wasChecked);

    if (actionMode!=null){
        //You need it to enable the CAB
        //((CardView)view).setLongClickable(false);
    }

    return true;

}
 
Example 51
Project: ExcusePro   File: IcsAdapterView.java View source code 6 votes vote down vote up
/**
 * Call the OnItemClickListener, if it is defined.
 *
 * @param view The view within the AdapterView that was clicked.
 * @param position The position of the view in the adapter.
 * @param id The row id of the item that was clicked.
 * @return True if there was an assigned OnItemClickListener that was
 *         called, false otherwise is returned.
 */
public boolean performItemClick(View view, int position, long id) {
    if (mOnItemClickListener != null) {
        playSoundEffect(SoundEffectConstants.CLICK);
        if (view != null) {
            view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
        }
        mOnItemClickListener.onItemClick(/*this*/null, view, position, id);
        return true;
    }

    return false;
}
 
Example 52
Project: BioWiki   File: Compat.java View source code 6 votes vote down vote up
public static void postOnAnimation(View view, Runnable runnable) {
    if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
        SDK16.postOnAnimation(view, runnable);
    } else {
        view.postDelayed(runnable, SIXTY_FPS_INTERVAL);
    }
}
 
Example 53
Project: ExcusePro   File: IcsSpinner.java View source code 6 votes vote down vote up
@Override
public int getBaseline() {
    View child = null;

    if (getChildCount() > 0) {
        child = getChildAt(0);
    } else if (mAdapter != null && mAdapter.getCount() > 0) {
        child = makeAndAddView(0);
        mRecycler.put(0, child);
        removeAllViewsInLayout();
    }

    if (child != null) {
        final int childBaseline = child.getBaseline();
        return childBaseline >= 0 ? child.getTop() + childBaseline : -1;
    } else {
        return -1;
    }
}
 
Example 54
Project: Blurry   File: Helper.java View source code 6 votes vote down vote up
public static void setBackground(View v, Drawable drawable) {
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    v.setBackground(drawable);
  } else {
    v.setBackgroundDrawable(drawable);
  }
}
 
Example 55
Project: ExcusePro   File: MenuPopupHelper.java View source code 6 votes vote down vote up
@Override
public void onGlobalLayout() {
    if (isShowing()) {
        final View anchor = mAnchorView;
        if (anchor == null || !anchor.isShown()) {
            dismiss();
        } else if (isShowing()) {
            // Recompute window size and position
            mPopup.show();
        }
    }
}
 
Example 56
Project: CeaselessAndroid   File: ZoomOutPageTransformer.java View source code 6 votes vote down vote up
public void transformPage(View view, float position) {
    int pageWidth = view.getWidth();
    int pageHeight = view.getHeight();

    if (position < -1) { // [-Infinity,-1)
        // This page is way off-screen to the left.
        view.setAlpha(0);

    } else if (position <= 1) { // [-1,1]
        // Modify the default slide transition to shrink the page as well
        float scaleFactor = Math.max(MIN_SCALE, 1 - Math.abs(position));
        float vertMargin = pageHeight * (1 - scaleFactor) / 2;
        float horzMargin = pageWidth * (1 - scaleFactor) / 2;
        if (position < 0) {
            view.setTranslationX(horzMargin - vertMargin / 2);
        } else {
            view.setTranslationX(-horzMargin + vertMargin / 2);
        }

        // Scale the page down (between MIN_SCALE and 1)
        view.setScaleX(scaleFactor);
        view.setScaleY(scaleFactor);

        // Fade the page relative to its size.
        view.setAlpha(MIN_ALPHA +
                (scaleFactor - MIN_SCALE) /
                        (1 - MIN_SCALE) * (1 - MIN_ALPHA));

    } else { // (1,+Infinity]
        // This page is way off-screen to the right.
        view.setAlpha(0);
    }
}
 
Example 57
Project: BioWiki   File: PhotoViewAttacher.java View source code 6 votes vote down vote up
@Override
public final boolean onTouch(View v, MotionEvent ev) {
    boolean handled = false;

    if (mZoomEnabled) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // First, disable the Parent from intercepting the touch
                // event
                v.getParent().requestDisallowInterceptTouchEvent(true);

                // If we're flinging, and the user presses down, cancel
                // fling
                cancelFling();
                break;

            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_UP:
                // If the user has zoomed less than min scale, zoom back
                // to min scale
                if (getScale() < mMinScale) {
                    RectF rect = getDisplayRect();
                    if (null != rect) {
                        v.post(new AnimatedZoomRunnable(getScale(), mMinScale, rect.centerX(), rect.centerY()));
                        handled = true;
                    }
                }
                break;
        }

        // Check to see if the user double tapped
        if (null != mGestureDetector && mGestureDetector.onTouchEvent(ev)) {
            handled = true;
        }

        // Finally, try the Scale/Drag detector
        if (null != mScaleDragDetector && mScaleDragDetector.onTouchEvent(ev)) {
            handled = true;
        }
    }

    return handled;
}
 
Example 58
Project: notes   File: HeaderGridView.java View source code 6 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
	// Header (negative positions will throw an
	// ArrayIndexOutOfBoundsException)
	int numHeadersAndPlaceholders = getHeadersCount() * mNumColumns;
	if (position < numHeadersAndPlaceholders) {
		View headerViewContainer = mHeaderViewInfos.get(position
				/ mNumColumns).viewContainer;
		if (position % mNumColumns == 0) {
			return headerViewContainer;
		} else {
			if (convertView == null) {
				convertView = new View(parent.getContext());
			}
			// We need to do this because GridView uses the height of
			// the last item
			// in a row to determine the height for the entire row.
			convertView.setVisibility(View.INVISIBLE);
			convertView.setMinimumHeight(headerViewContainer
					.getHeight());
			return convertView;
		}
	}

	// Adapter
	final int adjPosition = position - numHeadersAndPlaceholders;
	int adapterCount = 0;
	if (mAdapter != null) {
		adapterCount = mAdapter.getCount();
		if (adjPosition < adapterCount) {
			return mAdapter.getView(adjPosition, convertView, parent);
		}
	}

	throw new ArrayIndexOutOfBoundsException(position);
}
 
Example 59
Project: dove   File: SwipeHelper.java View source code 6 votes vote down vote up
/**
 * Sets the layer type of a view to hardware if the view is attached and
 * hardware acceleration is enabled. Does nothing otherwise.
 * 
 * @param v The view to use hardware accelerate.
 */
private static void enableHardwareLayer(View v) {
    if (v != null && v.isHardwareAccelerated()) {
        v.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        v.buildLayer();
    }
}
 
Example 60
Project: packages_apps_Launcher2   File: CellLayout.java View source code 6 votes vote down vote up
@Override
public void requestChildFocus(View child, View focused) {
    super.requestChildFocus(child, focused);
    if (child != null) {
        Rect r = new Rect();
        child.getDrawingRect(r);
        requestRectangleOnScreen(r);
    }
}
 
Example 61
Project: ExcusePro   File: PullToRefreshAttacher.java View source code 6 votes vote down vote up
/**
 * Add a view which will be used to initiate refresh requests, along with a
 * delegate which knows how to handle the given view, and a listener to be
 * invoked when a refresh is started.
 * 
 * @param view
 *            View which will be used to initiate refresh requests.
 * @param viewDelegate
 *            delegate which knows how to handle <code>view</code>.
 * @param refreshListener
 *            Listener to be invoked when a refresh is started.
 * @param setTouchListener
 *            Whether to set this as the
 *            [email protected] android.view.View.OnTouchListener}.
 */
void addRefreshableView(View view, ViewDelegate viewDelegate,
		OnRefreshListener refreshListener, final boolean setTouchListener) {
	// Check to see if view is null
	if (view == null) {
		Log.i(LOG_TAG, "Refreshable View is null.");
		return;
	}

	if (refreshListener == null) {
		throw new IllegalArgumentException(
				"OnRefreshListener not given. Please provide one.");
	}

	// ViewDelegate
	if (viewDelegate == null) {
		viewDelegate = InstanceCreationUtils.getBuiltInViewDelegate(view);
		if (viewDelegate == null) {
			throw new IllegalArgumentException(
					"No view handler found. Please provide one.");
		}
	}

	// View to detect refreshes for
	mRefreshableViews.put(view, new ViewParams(viewDelegate,
			refreshListener));
	if (setTouchListener) {
		view.setOnTouchListener(this);
	}
}
 
Example 62
Project: ExcusePro   File: MenuBuilder.java View source code 6 votes vote down vote up
public void restoreActionViewStates(Bundle states) {
    if (states == null) {
        return;
    }

    SparseArray<Parcelable> viewStates = states.getSparseParcelableArray(
            getActionViewStatesKey());

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB && viewStates == null) {
        //Fixes Issue #652 with sdk <= 2.3.6
        return;
    }

    final int itemCount = size();
    for (int i = 0; i < itemCount; i++) {
        final MenuItem item = getItem(i);
        final View v = item.getActionView();
        if (v != null && v.getId() != View.NO_ID) {
            v.restoreHierarchyState(viewStates);
        }
        if (item.hasSubMenu()) {
            final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
            subMenu.restoreActionViewStates(states);
        }
    }

    final int expandedId = states.getInt(EXPANDED_ACTION_VIEW_ID);
    if (expandedId > 0) {
        MenuItem itemToExpand = findItem(expandedId);
        if (itemToExpand != null) {
            itemToExpand.expandActionView();
        }
    }
}
 
Example 63
Project: ExcusePro   File: MenuBuilder.java View source code 6 votes vote down vote up
public void saveActionViewStates(Bundle outStates) {
    SparseArray<Parcelable> viewStates = null;

    final int itemCount = size();
    for (int i = 0; i < itemCount; i++) {
        final MenuItem item = getItem(i);
        final View v = item.getActionView();
        if (v != null && v.getId() != View.NO_ID) {
            if (viewStates == null) {
                viewStates = new SparseArray<Parcelable>();
            }
            v.saveHierarchyState(viewStates);
            if (item.isActionViewExpanded()) {
                outStates.putInt(EXPANDED_ACTION_VIEW_ID, item.getItemId());
            }
        }
        if (item.hasSubMenu()) {
            final SubMenuBuilder subMenu = (SubMenuBuilder) item.getSubMenu();
            subMenu.saveActionViewStates(outStates);
        }
    }

    if (viewStates != null) {
        outStates.putSparseParcelableArray(getActionViewStatesKey(), viewStates);
    }
}
 
Example 64
Project: ExcusePro   File: IcsView.java View source code 6 votes vote down vote up
/**
 * Return only the state bits of [email protected] #getMeasuredWidthAndState()}
 * and [email protected] #getMeasuredHeightAndState()}, combined into one integer.
 * The width component is in the regular bits [email protected] #MEASURED_STATE_MASK}
 * and the height component is at the shifted bits
 * [email protected] #MEASURED_HEIGHT_STATE_SHIFT}>>[email protected] #MEASURED_STATE_MASK}.
 */
public static int getMeasuredStateInt(View child) {
    return (child.getMeasuredWidth()&View.MEASURED_STATE_MASK)
            | ((child.getMeasuredHeight()>>View.MEASURED_HEIGHT_STATE_SHIFT)
                    & (View.MEASURED_STATE_MASK>>View.MEASURED_HEIGHT_STATE_SHIFT));
}
 
Example 65
Project: AmazeFileManager   File: HeaderRenderer.java View source code 6 votes vote down vote up
/**
 * Draws a header to a canvas, offsetting by some x and y amount
 *
 * @param recyclerView the parent recycler view for drawing the header into
 * @param canvas       the canvas on which to draw the header
 * @param header       the view to draw as the header
 * @param offset       a Rect used to define the x/y offset of the header. Specify x/y offset by setting
 *                     the [email protected] Rect#left} and [email protected] Rect#top} properties, respectively.
 */
public void drawHeader(RecyclerView recyclerView, Canvas canvas, View header, Rect offset) {
  canvas.save();

  if (recyclerView.getLayoutManager().getClipToPadding()) {
    // Clip drawing of headers to the padding of the RecyclerView. Avoids drawing in the padding
    Rect clipRect = getClipRectForHeader(recyclerView, header);
    canvas.clipRect(clipRect);
  }

  canvas.translate(offset.left, offset.top);

  header.draw(canvas);
  canvas.restore();
}
 
Example 66
Project: android-sdk-sources-for-api-level-23   File: BasicBindingTest.java View source code 6 votes vote down vote up
public void testStopBinding() throws Throwable {
    final NoRebind noRebind = new NoRebind();
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            assertAB("X", "Y");
            mBinder.addOnRebindCallback(noRebind);
        }
    });
    mBinder.setA("Q");
    WaitForRun waitForRun = new WaitForRun();
    View root = mBinder.getRoot();
    root.postOnAnimation(waitForRun);
    waitForRun.waitForRun();
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            assertEquals(1, noRebind.rebindAttempts);
            assertEquals(1, noRebind.rebindHalted);
            assertEquals(0, noRebind.rebindWillEvaluate);
            assertEquals("XY", mBinder.textView.getText().toString());
        }
    });
    mBinder.removeOnRebindCallback(noRebind);
    final AllowRebind allowRebind = new AllowRebind();
    mBinder.addOnRebindCallback(allowRebind);
    mBinder.setB("R");
    root.postOnAnimation(waitForRun);
    waitForRun.waitForRun();
    runTestOnUiThread(new Runnable() {
        @Override
        public void run() {
            assertEquals(1, noRebind.rebindAttempts);
            assertEquals(1, noRebind.rebindHalted);
            assertEquals(0, noRebind.rebindWillEvaluate);
            assertEquals(1, allowRebind.rebindAttempts);
            assertEquals(0, allowRebind.rebindHalted);
            assertEquals(1, allowRebind.rebindWillEvaluate);
            assertEquals("QR", mBinder.textView.getText().toString());
        }
    });
}
 
Example 67
Project: tuberun_android   File: TabsAdapter.java View source code 6 votes vote down vote up
@Override
public View createTabContent(String tag) {
	View v = new TextView(mContext);
	v.setMinimumWidth(0);
	v.setMinimumHeight(0);
	return v;
}
 
Example 68
Project: Roid-Library   File: DraggableDrawer.java View source code 6 votes vote down vote up
private int supportGetTranslationX(View v) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        return (int) v.getTranslationX();
    }

    return 0;
}
 
Example 69
Project: TwoDAdapter   File: TwoDScrollView.java View source code 6 votes vote down vote up
/**
 * You can call this function yourself to have the scroll view perform
 * scrolling from a key event, just as if the event had been dispatched to
 * it by the view hierarchy.
 *
 * @param event The key event to execute.
 * @return Return true if the event was handled, else false.
 */
public boolean executeKeyEvent(KeyEvent event) {
	mTempRect.setEmpty();
	if (!canScroll()) {
		if (isFocused()) {
			View currentFocused = findFocus();
			if (currentFocused == this) currentFocused = null;
			View nextFocused = FocusFinder.getInstance().findNextFocus(this, currentFocused, View.FOCUS_DOWN);
			return nextFocused != null && nextFocused != this && nextFocused.requestFocus(View.FOCUS_DOWN);
		}
		return false;
	}
	boolean handled = false;
	if (event.getAction() == KeyEvent.ACTION_DOWN) {
		switch (event.getKeyCode()) {
		case KeyEvent.KEYCODE_DPAD_UP:
			if (!event.isAltPressed()) {
				handled = arrowScroll(View.FOCUS_UP, false);
			} else {
				handled = fullScroll(View.FOCUS_UP, false);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			if (!event.isAltPressed()) {
				handled = arrowScroll(View.FOCUS_DOWN, false);
			} else {
				handled = fullScroll(View.FOCUS_DOWN, false);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			if (!event.isAltPressed()) {
				handled = arrowScroll(View.FOCUS_LEFT, true);
			} else {
				handled = fullScroll(View.FOCUS_LEFT, true);
			}
			break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			if (!event.isAltPressed()) {
				handled = arrowScroll(View.FOCUS_RIGHT, true);
			} else {
				handled = fullScroll(View.FOCUS_RIGHT, true);
			}
			break;
		}
	}
	return handled;
}
 
Example 70
Project: AmazeFileManager   File: Main.java View source code 6 votes vote down vote up
public void stopAnimation() {
    if ((!adapter.stoppedAnimation)) {
        for (int j = 0; j < listView.getChildCount(); j++) {
            View v = listView.getChildAt(j);
            if (v != null) v.clearAnimation();
        }
    }
    adapter.stoppedAnimation = true;
}
 
Example 71
Project: TextSecureSMP   File: RepeatableImageKey.java View source code 6 votes vote down vote up
@TargetApi(VERSION_CODES.HONEYCOMB_MR1)
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
  switch (motionEvent.getAction()) {
  case MotionEvent.ACTION_DOWN:
    view.postDelayed(repeater, VERSION.SDK_INT >= VERSION_CODES.HONEYCOMB_MR1
                               ? ViewConfiguration.getKeyRepeatTimeout()
                               : ViewConfiguration.getLongPressTimeout());
    performHapticFeedback(HapticFeedbackConstants.KEYBOARD_TAP);
    return false;
  case MotionEvent.ACTION_CANCEL:
  case MotionEvent.ACTION_UP:
    view.removeCallbacks(repeater);
    return false;
  default:
    return false;
  }
}
 
Example 72
Project: recyclerview-animators   File: ViewHelper.java View source code 6 votes vote down vote up
public static void clear(View v) {
  ViewCompat.setAlpha(v, 1);
  ViewCompat.setScaleY(v, 1);
  ViewCompat.setScaleX(v, 1);
  ViewCompat.setTranslationY(v, 0);
  ViewCompat.setTranslationX(v, 0);
  ViewCompat.setRotation(v, 0);
  ViewCompat.setRotationY(v, 0);
  ViewCompat.setRotationX(v, 0);
  // @TODO https://code.google.com/p/android/issues/detail?id=80863
  //        ViewCompat.setPivotY(v, v.getMeasuredHeight() / 2);
  v.setPivotY(v.getMeasuredHeight() / 2);
  ViewCompat.setPivotX(v, v.getMeasuredWidth() / 2);
  ViewCompat.animate(v).setInterpolator(null);
}
 
Example 73
Project: Roid-Library   File: DraggableDrawer.java View source code 6 votes vote down vote up
private int supportGetTranslationY(View v) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        return (int) v.getTranslationY();
    }

    return 0;
}
 
Example 74
Project: Jide-Note   File: ScreenUtils.java View source code 6 votes vote down vote up
/**
 * ??????????????
 *
 * @param activity
 * @return
 */
public static Bitmap snapShotWithStatusBar(Activity activity)
{
    View view = activity.getWindow().getDecorView();
    view.setDrawingCacheEnabled(true);
    view.buildDrawingCache();
    Bitmap bmp = view.getDrawingCache();
    int width = getScreenWidth(activity);
    int height = getScreenHeight(activity);
    Bitmap bp = null;
    bp = Bitmap.createBitmap(bmp, 0, 0, width, height);
    view.destroyDrawingCache();
    return bp;

}
 
Example 75
Project: AndroidIndicators   File: Title3DTransformer.java View source code 6 votes vote down vote up
@Override
public void transform(View view1, View view2, float positionOffset, int direction) {
    view1.setPivotX(0);
    view1.setPivotY(view1.getHeight() / 2);

    view2.setPivotX(0);
    view2.setPivotY(view2.getHeight() / 2);

    if (direction == ViewPagerObserver.DIRECTION_LEFT) {
        view1.setAlpha(1f);//Hiding
        view1.setRotationY(90 * ((1f - positionOffset)));

        view2.setAlpha(1f);//Showing
        view2.setRotationY(-90 + 90 * (1f - positionOffset));
    } else {
        view1.setAlpha(1f );//Hiding
        view1.setRotationY(-90 * positionOffset);

        view2.setAlpha(1f);//Showing
        view2.setRotationY(90 * (1f - positionOffset));
    }
}
 
Example 76
Project: hacktoolkit-android_lib   File: SystemUiHiderHoneycomb.java View source code 6 votes vote down vote up
/**
 * Constructor not intended to be called by clients. Use
 * [email protected] SystemUiHider#getInstance} to obtain an instance.
 */
protected SystemUiHiderHoneycomb(Activity activity, View anchorView,
		int flags) {
	super(activity, anchorView, flags);

	mShowFlags = View.SYSTEM_UI_FLAG_VISIBLE;
	mHideFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE;
	mTestFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE;

	if ((mFlags & FLAG_FULLSCREEN) != 0) {
		// If the client requested fullscreen, add flags relevant to hiding
		// the status bar. Note that some of these constants are new as of
		// API 16 (Jelly Bean). It is safe to use them, as they are inlined
		// at compile-time and do nothing on pre-Jelly Bean devices.
		mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
		mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
				| View.SYSTEM_UI_FLAG_FULLSCREEN;
	}

	if ((mFlags & FLAG_HIDE_NAVIGATION) != 0) {
		// If the client requested hiding navigation, add relevant flags.
		mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION;
		mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
				| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
		mTestFlags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
	}
}
 
Example 77
Project: SwipeDismissListView   File: ViewPropertyAnimatorHC.java View source code 6 votes vote down vote up
/**
 * This method gets the value of the named property from the View object.
 *
 * @param propertyConstant The property whose value should be returned
 * @return float The value of the named property
 */
private float getValue(int propertyConstant) {
    //final View.TransformationInfo info = mView.mTransformationInfo;
    View v = mView.get();
    if (v != null) {
        switch (propertyConstant) {
            case TRANSLATION_X:
                //return info.mTranslationX;
                return v.getTranslationX();
            case TRANSLATION_Y:
                //return info.mTranslationY;
                return v.getTranslationY();
            case ROTATION:
                //return info.mRotation;
                return v.getRotation();
            case ROTATION_X:
                //return info.mRotationX;
                return v.getRotationX();
            case ROTATION_Y:
                //return info.mRotationY;
                return v.getRotationY();
            case SCALE_X:
                //return info.mScaleX;
                return v.getScaleX();
            case SCALE_Y:
                //return info.mScaleY;
                return v.getScaleY();
            case X:
                //return v.mLeft + info.mTranslationX;
                return v.getX();
            case Y:
                //return v.mTop + info.mTranslationY;
                return v.getY();
            case ALPHA:
                //return info.mAlpha;
                return v.getAlpha();
        }
    }
    return 0;
}
 
Example 78
Project: xface-android   File: XAppWebView.java View source code 6 votes vote down vote up
@Override
public void loadUrl(String url) {
    super.loadUrl(url);
    this.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // ??onLongClick???Android 4.0???????text selection??.
            // ????????touchstart, touchmove, touchend?events
            return true;
        }
    });
}
 
Example 79
Project: Todayinformation   File: PullToRefreshBase.java View source code 6 votes vote down vote up
/**
 * Helper method which just calls scrollTo() in the correct scrolling
 * direction.
 * 
 * @param value - New Scroll value
 */
protected final void setHeaderScroll(int value) {
	if (DEBUG) {
		Log.d(LOG_TAG, "setHeaderScroll: " + value);
	}

	// Clamp value to with pull scroll range
	final int maximumPullScroll = getMaximumPullScroll();
	value = Math.min(maximumPullScroll, Math.max(-maximumPullScroll, value));

	if (mLayoutVisibilityChangesEnabled) {
		if (value < 0) {
			mHeaderLayout.setVisibility(View.VISIBLE);
		} else if (value > 0) {
			mFooterLayout.setVisibility(View.VISIBLE);
		} else {
			mHeaderLayout.setVisibility(View.INVISIBLE);
			mFooterLayout.setVisibility(View.INVISIBLE);
		}
	}

	if (USE_HW_LAYERS) {
		/**
		 * Use a Hardware Layer on the Refreshable View if we've scrolled at
		 * all. We don't use them on the Header/Footer Views as they change
		 * often, which would negate any HW layer performance boost.
		 */
		ViewCompat.setLayerType(mRefreshableViewWrapper, value != 0 ? View.LAYER_TYPE_HARDWARE
				: View.LAYER_TYPE_NONE);
	}

	switch (getPullToRefreshScrollDirection()) {
		case VERTICAL:
			scrollTo(0, value);
			break;
		case HORIZONTAL:
			scrollTo(value, 0);
			break;
	}
}
 
Example 80
Project: TwoDAdapter   File: TwoDAdapter.java View source code 6 votes vote down vote up
/**
 * Get view position on X axis
 * @param view : View to get position
 * @return Position on X axis
 */
@SuppressLint("NewApi")
protected float getViewPositionX(View view) {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
		return view.getX();
	} else {
		LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
		return layoutParams.leftMargin;
	}
}
 
Example 81
Project: Lyric-Music-Player   File: EdgeEffectCompat.java View source code 6 votes vote down vote up
/**
 * Call [email protected] View#getOverScrollMode()}.
 *
 * (This is unrelated to EdgeEffect; it's thrown in here since ViewPager
 * also uses it.)
 */
public static int getOverScrollMode(View view)
{
	return view.getOverScrollMode();
}
 
Example 82
Project: TwoDAdapter   File: TwoDAdapter.java View source code 6 votes vote down vote up
/**
 * Get view position on Y axis
 * @param view : View to get position
 * @return Position on Y axis
 */
@SuppressLint("NewApi")
protected float getViewPositionY(View view) {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
		return view.getY();
	} else {
		LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
		return layoutParams.topMargin;
	}
}
 
Example 83
Project: TextSecureSMP   File: RegistrationActivity.java View source code 6 votes vote down vote up
private void initializeSpinner() {
  this.countrySpinnerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item);
  this.countrySpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

  setCountryDisplay(getString(R.string.RegistrationActivity_select_your_country));

  this.countrySpinner.setAdapter(this.countrySpinnerAdapter);
  this.countrySpinner.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
      if (event.getAction() == MotionEvent.ACTION_UP) {
        Intent intent = new Intent(RegistrationActivity.this, CountrySelectionActivity.class);
        startActivityForResult(intent, PICK_COUNTRY);
      }
      return true;
    }
  });
}
 
Example 84
Project: TwoDAdapter   File: TwoDScrollView.java View source code 6 votes vote down vote up
/**
 * When looking for focus in children of a scroll view, need to be a little
 * more careful not to give focus to something that is scrolled off screen.
 *
 * This is more expensive than the default [email protected] android.view.ViewGroup}
 * implementation, otherwise this behavior might have been made the default.
 */
@Override
protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
	// convert from forward / backward notation to up / down / left / right
	// (ugh).
	if (direction == View.FOCUS_FORWARD) {
		direction = View.FOCUS_DOWN;
	} else if (direction == View.FOCUS_BACKWARD) {
		direction = View.FOCUS_UP;
	}

	final View nextFocus = previouslyFocusedRect == null ?
			FocusFinder.getInstance().findNextFocus(this, null, direction) :
				FocusFinder.getInstance().findNextFocusFromRect(this,
						previouslyFocusedRect, direction);

			if (nextFocus == null) {
				return false;
			}

			return nextFocus.requestFocus(direction, previouslyFocusedRect);
}
 
Example 85
Project: TasksProject   File: CardsListFragment.java View source code 6 votes vote down vote up
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    this.getListView().setHeaderDividersEnabled(true);
    this.getListView().setVerticalScrollBarEnabled(false);
    this.getListView().setVerticalFadingEdgeEnabled(false);
    this.getListView().setClipToPadding(false);
    this.getListView().setOverScrollMode(View.OVER_SCROLL_NEVER);
    this.getListView().setOverscrollHeader(this.getResources().getDrawable(R.drawable.ic_action_new_labels));
    this.getListView().setTextFilterEnabled(true);

    initHeaderView();

}
 
Example 86
Project: packages_apps_Launcher2   File: DragController.java View source code 6 votes vote down vote up
/**
 * Draw the view into a bitmap.
 */
private Bitmap getViewBitmap(View v) {
    v.clearFocus();
    v.setPressed(false);

    boolean willNotCache = v.willNotCacheDrawing();
    v.setWillNotCacheDrawing(false);

    // Reset the drawing cache background color to fully transparent
    // for the duration of this operation
    int color = v.getDrawingCacheBackgroundColor();
    v.setDrawingCacheBackgroundColor(0);

    if (color != 0) {
        v.destroyDrawingCache();
    }
    v.buildDrawingCache();
    Bitmap cacheBitmap = v.getDrawingCache();
    if (cacheBitmap == null) {
        Log.e(TAG, "failed getViewBitmap(" + v + ")", new RuntimeException());
        return null;
    }

    Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

    // Restore the view
    v.destroyDrawingCache();
    v.setWillNotCacheDrawing(willNotCache);
    v.setDrawingCacheBackgroundColor(color);

    return bitmap;
}
 
Example 87
Project: TwoDAdapter   File: TwoDAdapter.java View source code 6 votes vote down vote up
/**
 * Set view position
 * @param view : View to set
 * @param x : Position on X axis
 * @param y : Position on Y axis
 */
@SuppressLint("NewApi")
protected void setViewPosition(View view, float x, float y) {
	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
		view.setX(x);
		view.setY(y);
	} else {
		LayoutParams layoutParams = (LayoutParams) view.getLayoutParams();
		layoutParams.leftMargin = (int) x;
		layoutParams.topMargin = (int) y;
	}
}
 
Example 88
Project: hci-2011-2   File: Fragment.java View source code 6 votes vote down vote up
/**
 * Registers a context menu to be shown for the given view (multiple views
 * can show the context menu). This method will set the
 * [email protected] OnCreateContextMenuListener} on the view to this fragment, so
 * [email protected] #onCreateContextMenu(ContextMenu, View, ContextMenuInfo)} will be
 * called when it is time to show the context menu.
 *
 * @see #unregisterForContextMenu(View)
 * @param view The view that should show a context menu.
 */
public void registerForContextMenu(View view) {
    view.setOnCreateContextMenuListener(this);
}
 
Example 89
Project: mythmote   File: KeyBindingManager.java View source code 6 votes vote down vote up
public void onClick(View v) {

		KeyBindingEntry entry = viewToEntryMap.get(v);

		if (null != entry && null != communicator) {
			Log.d(MythMote.LOG_TAG, "onClick " + entry.getFriendlyName()
					+ " command " + entry.getCommand());
			
			//send command
			communicator.SendCommand(entry.getCommand());
			
			//perform haptic feedback if enabled
			if(mHapticFeedbackEnabled){
			v.performHapticFeedback(
					HapticFeedbackConstants.FLAG_IGNORE_VIEW_SETTING,
					HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
			}
		}

	}
 
Example 90
Project: OrderNowAndroid   File: StaggeredGridView.java View source code 6 votes vote down vote up
void positionSelector(int position, View sel) {
    if (position != INVALID_POSITION) {
        mSelectorPosition = position;
    }

    final Rect selectorRect = mSelectorRect;
    selectorRect.set(sel.getLeft(), sel.getTop(), sel.getRight(), sel.getBottom());
    if (sel instanceof SelectionBoundsAdjuster) {
        ((SelectionBoundsAdjuster)sel).adjustListItemSelectionBounds(selectorRect);
    }

    positionSelector(selectorRect.left, selectorRect.top, selectorRect.right,
            selectorRect.bottom);

    final boolean isChildViewEnabled = mIsChildViewEnabled;
    if (sel.isEnabled() != isChildViewEnabled) {
        mIsChildViewEnabled = !isChildViewEnabled;
        if (getSelectedItemPosition() != INVALID_POSITION) {
            refreshDrawableState();
        }
    }
}
 
Example 91
Project: sawan-bar   File: DTMFTwelveKeyDialer.java View source code 6 votes vote down vote up
/**
 * setup the keys on the dialer activity, using the keymaps.
 */
private void setupKeypad(DTMFTwelveKeyDialerView dialerView) {
    // for each view id listed in the displaymap
    View button;
    for (int viewId : mDisplayMap.keySet()) {
        // locate the view
        button = dialerView.findViewById(viewId);
        // Setup the listeners for the buttons
        button.setOnTouchListener(this);
        button.setClickable(true);
        button.setOnKeyListener(this);
    }
}
 
Example 92
Project: packages_apps_Launcher2   File: Folder.java View source code 6 votes vote down vote up
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
    if (!view.isInTouchMode()) {
        return false;
    }

    ShortcutInfo app = (ShortcutInfo) parent.getItemAtPosition(position);

    mDragController.startDrag(view, this, app, DragController.DRAG_ACTION_COPY);
    mLauncher.closeFolder(this);
    mDragItem = app;

    return true;
}
 
Example 93
Project: Android-Json-Parsing-Code-Sample   File: LineMorphingDrawable.java View source code 6 votes vote down vote up
public Builder(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
	TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LineMorphingDrawable, defStyleAttr, defStyleRes);
	int resId;
	
	if((resId = a.getResourceId(R.styleable.LineMorphingDrawable_lmd_state, 0)) != 0)
		states(readStates(context, resId));			
	curState(a.getInteger(R.styleable.LineMorphingDrawable_lmd_curState, 0));			
	padding(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_padding, 0));
	paddingLeft(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_paddingLeft, mPaddingLeft));
	paddingTop(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_paddingTop, mPaddingTop));
	paddingRight(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_paddingRight, mPaddingRight));
	paddingBottom(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_paddingBottom, mPaddingBottom));
	animDuration(a.getInteger(R.styleable.LineMorphingDrawable_lmd_animDuration, context.getResources().getInteger(android.R.integer.config_mediumAnimTime)));
	if((resId = a.getResourceId(R.styleable.LineMorphingDrawable_lmd_interpolator, 0)) != 0)
		interpolator(AnimationUtils.loadInterpolator(context, resId));
	strokeSize(a.getDimensionPixelSize(R.styleable.LineMorphingDrawable_lmd_strokeSize, ThemeUtil.dpToPx(context, 3)));
	strokeColor(a.getColor(R.styleable.LineMorphingDrawable_lmd_strokeColor, 0xFFFFFFFF));
	int cap = a.getInteger(R.styleable.LineMorphingDrawable_lmd_strokeCap, 0);
	if(cap == 0)
		strokeCap(Paint.Cap.BUTT);
	else if(cap == 1)
		strokeCap(Paint.Cap.ROUND);
	else
		strokeCap(Paint.Cap.SQUARE);
	int join = a.getInteger(R.styleable.LineMorphingDrawable_lmd_strokeJoin, 0);
	if(join == 0)
		strokeJoin(Paint.Join.MITER);
	else if(join == 1)
		strokeJoin(Paint.Join.ROUND);
	else
		strokeJoin(Paint.Join.BEVEL);
	clockwise(a.getBoolean(R.styleable.LineMorphingDrawable_lmd_clockwise, true));

          int direction = a.getInteger(R.styleable.LineMorphingDrawable_lmd_layoutDirection, View.LAYOUT_DIRECTION_LTR);
          if(direction == View.LAYOUT_DIRECTION_LOCALE)
              rtl(TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL);
          else
              rtl(direction == View.LAYOUT_DIRECTION_RTL);
	
	a.recycle();
}
 
Example 94
Project: MHacksAndroid-Public   File: AbsListViewDelegate.java View source code 6 votes vote down vote up
@Override
public boolean isReadyForPull(View view, final float x, final float y) {
    boolean ready = false;

    // First we check whether we're scrolled to the top
    AbsListView absListView = (AbsListView) view;
    if (absListView.getCount() == 0) {
        ready = true;
    } else if (absListView.getFirstVisiblePosition() == 0) {
        final View firstVisibleChild = absListView.getChildAt(0);
        ready = firstVisibleChild != null && firstVisibleChild.getTop() >= 0;
    }

    // Then we have to check whether the fas scroller is enabled, and check we're not starting
    // the gesture from the scroller
    if (ready && absListView.isFastScrollEnabled() && isFastScrollAlwaysVisible(absListView)) {
        switch (getVerticalScrollbarPosition(absListView)) {
            case View.SCROLLBAR_POSITION_RIGHT:
                ready = x < absListView.getRight() - absListView.getVerticalScrollbarWidth();
                break;
            case View.SCROLLBAR_POSITION_LEFT:
                ready = x > absListView.getVerticalScrollbarWidth();
                break;
        }
    }

    return ready;
}
 
Example 95
Project: android-FlipView   File: Recycler.java View source code 6 votes vote down vote up
/**
 * Put a view into the ScrapViews list. These views are unordered.
 * 
 * @param scrap
 *            The view to add
 */
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
void addScrapView(View scrap, int position, int viewType) {
	// create a new Scrap
	Scrap item = new Scrap(scrap, true);
	
	if (viewTypeCount == 1) {
		currentScraps.put(position, item);
	} else {
		scraps[viewType].put(position, item);
	}
	if (Build.VERSION.SDK_INT >= 14) {
		scrap.setAccessibilityDelegate(null);
	}
}
 
Example 96
Project: Android_Blog_Demos   File: ViewServer.java View source code 6 votes vote down vote up
/**
 * Invoke this method to unregister a view hierarchy.
 * 
 * @param view A view that belongs to the view hierarchy/window to unregister
 * 
 * @see #addWindow(View, String)
 */
public void removeWindow(View view) {
    View rootView;
    mWindowsLock.writeLock().lock();
    try {
        rootView = view.getRootView();
        mWindows.remove(rootView);
    } finally {
        mWindowsLock.writeLock().unlock();
    }
    mFocusLock.writeLock().lock();
    try {
        if (mFocusedWindow == rootView) {
            mFocusedWindow = null;
        }
    } finally {
        mFocusLock.writeLock().unlock();
    }
    fireWindowsChangedEvent();
}
 
Example 97
Project: beepme   File: BeepActivity.java View source code 6 votes vote down vote up
private void updateLayout() {
    final LayoutInflater inflater = LayoutInflater.from(this);
    final View view = inflater.inflate(R.layout.beep, null);
    view.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
    setContentView(view);

    acceptDeclineHandle = (GlowPadView)findViewById(R.id.beep_glowpad);
    acceptDeclineHandle.setOnTriggerListener(glowPadCtrl);
    glowPadCtrl.startPinger();
    //acceptDeclineHandle.setShowTargetsOnIdle(true);
}
 
Example 98
Project: OrderNowAndroid   File: StaggeredGridView.java View source code 6 votes vote down vote up
public void run() {
    if (mTouchMode == TOUCH_MODE_DOWN) {

        mTouchMode = TOUCH_MODE_TAP;
        final View child = getChildAt(mMotionPosition - mFirstPosition);
        if (child != null && !child.hasFocusable()) {

            if (!mDataChanged) {
            	child.setSelected(true);
            	child.setPressed(true);

                setPressed(true);
                positionSelector(mMotionPosition, child);
                refreshDrawableState();

                final int longPressTimeout = ViewConfiguration.getLongPressTimeout();
                final boolean longClickable = isLongClickable();

                if (mSelector != null) {
                    Drawable d = mSelector.getCurrent();
                    if (d instanceof TransitionDrawable) {
                        if (longClickable) {
                            ((TransitionDrawable) d).startTransition(longPressTimeout);
                        } else {
                            ((TransitionDrawable) d).resetTransition();
                        }
                    }
                }

                if (longClickable) {
                    if (mPendingCheckForLongPress == null) {
                        mPendingCheckForLongPress = new CheckForLongPress();
                    }
                    mPendingCheckForLongPress.rememberWindowAttachCount();
                    postDelayed(mPendingCheckForLongPress, longPressTimeout);
                } else {
                    mTouchMode = TOUCH_MODE_DONE_WAITING;
                }

                postInvalidate();
            } else {
                mTouchMode = TOUCH_MODE_DONE_WAITING;
            }
        }
    }
}
 
Example 99
Project: Todayinformation   File: ResideMenu.java View source code 6 votes vote down vote up
/**
 * If the motion event was relative to the view
 * which in ignored view list,return true;
 *
 * @param ev
 * @return
 */
private boolean isInIgnoredView(MotionEvent ev) {
    Rect rect = new Rect();
    for (View v : ignoredViews) {
        v.getGlobalVisibleRect(rect);
        if (rect.contains((int) ev.getX(), (int) ev.getY()))
            return true;
    }
    return false;
}
 
Example 100
Project: PhotoPhase   File: ViewPager.java View source code 6 votes vote down vote up
/**
 * We only want the current page that is being shown to be touchable.
 */
@Override
public void addTouchables(ArrayList<View> views) {
    // Note that we don't call super.addTouchables(), which means that
    // we don't call View.addTouchables().  This is okay because a ViewPager
    // is itself not touchable.
    for (int i = 0; i < getChildCount(); i++) {
        final View child = getChildAt(i);
        if (child.getVisibility() == VISIBLE) {
            ItemInfo ii = infoForChild(child);
            if (ii != null && ii.position == mCurItem) {
                child.addTouchables(views);
            }
        }
    }
}
 
Example 101
Project: android-FlipView   File: FlipView.java View source code 6 votes vote down vote up
/**
 * Enable a hardware layer for the view.
 * 
 * @param v
 * @param drawWithLayer
 */
private void setDrawWithLayer(View v, boolean drawWithLayer) {
	if (isHardwareAccelerated()) {
		if (v.getLayerType() != LAYER_TYPE_HARDWARE && drawWithLayer) {
			v.setLayerType(LAYER_TYPE_HARDWARE, null);
		} else if (v.getLayerType() != LAYER_TYPE_NONE && !drawWithLayer) {
			v.setLayerType(LAYER_TYPE_NONE, null);
		}
	}
}
 
Example 102
Project: Gui2Go   File: SimpleStandardAdapter.java View source code 6 votes vote down vote up
private void changeSelected(final boolean isChecked, final Long id)
{
	if (isChecked) {
		// selected.clear();
		selected.add(id);
	} else {
		selected.remove(id);
	}
	// AMI ADDED
	View myView = activity.findViewById(id.intValue());
	if (myView.getClass() == ListView.class
			|| myView.getClass() == Spinner.class
			|| myView.getClass() == GridView.class) {
		// special treatement for spinners and listviews
		// they can only be selected in the tree
		((EditorActivity) activity).performHightlight(myView);
	} else {
		myView.performClick();
	}

}
 
Example 103
Project: comfort-zone   File: CordovaActivity.java View source code 6 votes vote down vote up
/**
 * Called when view focus is changed
 */
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus && immersiveMode) {
        final int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;

        getWindow().getDecorView().setSystemUiVisibility(uiOptions);
    }
}
 
Example 104
Project: googleio   File: Workspace.java View source code 6 votes vote down vote up
@Override
public void addFocusables(ArrayList<View> views, int direction, int focusableMode) {
    View focusableSourceScreen = null;
    if (mCurrentScreen >= 0 && mCurrentScreen < getScreenCount()) {
        focusableSourceScreen = getScreenAt(mCurrentScreen);
    }
    if (direction == View.FOCUS_LEFT) {
        if (mCurrentScreen > 0) {
            focusableSourceScreen = getScreenAt(mCurrentScreen - 1);
        }
    } else if (direction == View.FOCUS_RIGHT) {
        if (mCurrentScreen < getScreenCount() - 1) {
            focusableSourceScreen = getScreenAt(mCurrentScreen + 1);
        }
    }

    if (focusableSourceScreen != null) {
        focusableSourceScreen.addFocusables(views, direction, focusableMode);
    }
}
 
Example 105
Project: Gui2Go   File: LongClickListener.java View source code 6 votes vote down vote up
@Override
public boolean onLongClick(View v)
{
	v.performClick();
	v.showContextMenu();
	return true;
}
 
Example 106
Project: property-db   File: AdapterView.java View source code 6 votes vote down vote up
/**
 * Sets the view to show if the adapter is empty
 */
@android.view.RemotableViewMethod
public void setEmptyView(View emptyView) {
    mEmptyView = emptyView;

    // If not explicitly specified this view is important for accessibility.
    if (emptyView != null
            && emptyView.getImportantForAccessibility() == IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
        emptyView.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_YES);
    }

    final T adapter = getAdapter();
    final boolean empty = ((adapter == null) || adapter.isEmpty());
    updateEmptyStatus(empty);
}
 
Example 107
Project: DemoProject   File: AnimatedRecyclerView.java View source code 6 votes vote down vote up
public void recycleViewsOutOfBounds(RecyclerView.Recycler recycler) {
    final int childCount = getChildCount();
    final int parentWidth = getWidth();
    final int parentHeight = getHeight();
    boolean foundFirst = false;
    int first = 0;
    int last = 0;
    for (int i = 0; i < childCount; i++) {
        final View v = getChildAt(i);
        if (v.hasFocus() || (v.getRight() >= 0 && v.getLeft() <= parentWidth &&
                v.getBottom() >= 0 && v.getTop() <= parentHeight)) {
            if (!foundFirst) {
                first = i;
                foundFirst = true;
            }
            last = i;
        }
    }
    for (int i = childCount - 1; i > last; i--) {
        removeAndRecycleViewAt(i, recycler);
    }
    for (int i = first - 1; i >= 0; i--) {
        removeAndRecycleViewAt(i, recycler);
    }
    if (getChildCount() == 0) {
        mFirstPosition = 0;
    } else {
        mFirstPosition += first;
    }
}
 
Example 108
Project: PradaCollage   File: MultiTouchListener.java View source code 6 votes vote down vote up
private static void computeRenderOffset(View view, float pivotX, float pivotY) {
    if (view.getPivotX() == pivotX && view.getPivotY() == pivotY) {
        return;
    }

    float[] prevPoint = { 0.0f, 0.0f };
    view.getMatrix().mapPoints(prevPoint);

    view.setPivotX(pivotX);
    view.setPivotY(pivotY);

    float[] currPoint = { 0.0f, 0.0f };
    view.getMatrix().mapPoints(currPoint);

    float offsetX = currPoint[0] - prevPoint[0];
    float offsetY = currPoint[1] - prevPoint[1];

    view.setTranslationX(view.getTranslationX() - offsetX);
    view.setTranslationY(view.getTranslationY() - offsetY);
}
 
Example 109
Project: androidquery   File: AbstractAQuery.java View source code 6 votes vote down vote up
private View findView(String tag){
	
	//((ViewGroup)findViewById(android.R.id.content)).getChildAt(0)
	View result = null;
	if(root != null){
		result = root.findViewWithTag(tag);
	}else if(act != null){
		//result = act.findViewById(id);
		View top = ((ViewGroup) act.findViewById(android.R.id.content)).getChildAt(0);
		if(top != null){
			result = top.findViewWithTag(tag);
		}
	}
	return result;
	
}
 
Example 110
Project: SealBrowser   File: ApiCompatibilityUtils.java View source code 6 votes vote down vote up
/**
 * @see android.view.View#postInvalidateOnAnimation()
 */
public static void postInvalidateOnAnimation(View view) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        view.postInvalidateOnAnimation();
    } else {
        view.postInvalidate();
    }
}
 
Example 111
Project: XposedGELSettings   File: GestureHelper.java View source code 6 votes vote down vote up
static void showAppdock(int duration) {
    mHotseat = (View) getObjectField(Common.LAUNCHER_INSTANCE, Fields.lHotseat);

    if (Common.LAUNCHER_INSTANCE == null || mHotseat == null || mHotseat.getAlpha() != 0.0f) {
        if (DEBUG) log("Don't show App Dock");
        return;
    }

    if (DEBUG) log("Show App Dock");

    final LayoutParams lp = (LayoutParams) mHotseat.getLayoutParams();

    if (isLandscape) {
        lp.width = Common.HOTSEAT_BAR_HEIGHT;
        lp.height = LayoutParams.MATCH_PARENT;
    }
    else {
        lp.width = LayoutParams.MATCH_PARENT;
        lp.height = Common.HOTSEAT_BAR_HEIGHT;
    }

    mHotseat.setLayoutParams(lp);

    showAnimation = mHotseat.animate();
    showAnimation.setListener(showListener);
    showAnimation
            .alpha(1f)
            .setDuration(duration)
            .start();
}
 
Example 112
Project: BioWiki   File: AnimationAdapter.java View source code 6 votes vote down vote up
private void cancelExistingAnimation(final View convertView) {
    int hashCode = convertView.hashCode();
    Animator animator = mAnimators.get(hashCode);
    if (animator != null) {
        animator.end();
        mAnimators.remove(hashCode);
    }
}
 
Example 113
Project: Transitions-Everywhere   File: ChangeScroll.java View source code 6 votes vote down vote up
@Override
public Animator createAnimator(ViewGroup sceneRoot, TransitionValues startValues,
                               TransitionValues endValues) {
    if (startValues == null || endValues == null ||
            Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        return null;
    }
    final View view = endValues.view;
    int startX = (Integer) startValues.values.get(PROPNAME_SCROLL_X);
    int endX = (Integer) endValues.values.get(PROPNAME_SCROLL_X);
    int startY = (Integer) startValues.values.get(PROPNAME_SCROLL_Y);
    int endY = (Integer) endValues.values.get(PROPNAME_SCROLL_Y);
    Animator scrollXAnimator = null;
    Animator scrollYAnimator = null;
    if (startX != endX) {
        view.setScrollX(startX);
        scrollXAnimator = ObjectAnimator.ofInt(view, "scrollX", startX, endX);
    }
    if (startY != endY) {
        view.setScrollY(startY);
        scrollYAnimator = ObjectAnimator.ofInt(view, "scrollY", startY, endY);
    }
    return TransitionUtils.mergeAnimators(scrollXAnimator, scrollYAnimator);
}
 
Example 114
Project: gb   File: GpsStatusWidgetTest.java View source code 6 votes vote down vote up
@Test
public void testFadeMeter() {
    View parent = PowerMock.createMock(View.class);
    Time time = PowerMock.createMock(Time.class);
    MeterBars meterBars = PowerMock.createMock(MeterBars.class);

    expect(time.getCurrentTime()).andReturn(1000L);
    meterBars.setLag(0);
    parent.postInvalidateDelayed(100);

    PowerMock.replayAll();
    new MeterFader(parent, meterBars, time).paint();
    // Log.d("GeoBeagle", "painting " + lastUpdateLag);
    PowerMock.verifyAll();
}
 
Example 115
Project: cardslib   File: NativeDashFragment.java View source code 6 votes vote down vote up
private void displayDescription(View view, String desc) {
    hideDescriptionToast();
    mCurrentToast = Toast.makeText(mContext.getApplicationContext(), desc, Toast.LENGTH_LONG);
    mCurrentToast.show();
    if (Build.VERSION.SDK_INT >= 16) {
        view.announceForAccessibility(desc);
    }
}
 
Example 116
Project: material-ripple   File: MaterialRippleLayout.java View source code 6 votes vote down vote up
private boolean findClickableViewInChild(View view, int x, int y) {
    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            View child = viewGroup.getChildAt(i);
            final Rect rect = new Rect();
            child.getHitRect(rect);

            final boolean contains = rect.contains(x, y);
            if (contains) {
                return findClickableViewInChild(child, x - rect.left, y - rect.top);
            }
        }
    } else if (view != childView) {
        return (view.isEnabled() && (view.isClickable() || view.isLongClickable() || view.isFocusableInTouchMode()));
    }

    return view.isFocusableInTouchMode();
}
 
Example 117
Project: property-db   File: FastScroller.java View source code 6 votes vote down vote up
public void setScrollbarPosition(int position) {
    if (position == View.SCROLLBAR_POSITION_DEFAULT) {
        position = mList.isLayoutRtl() ?
                View.SCROLLBAR_POSITION_LEFT : View.SCROLLBAR_POSITION_RIGHT;
    }
    mPosition = position;
    switch (position) {
        default:
        case View.SCROLLBAR_POSITION_RIGHT:
            mOverlayDrawable = mOverlayDrawableRight;
            break;
        case View.SCROLLBAR_POSITION_LEFT:
            mOverlayDrawable = mOverlayDrawableLeft;
            break;
    }
}
 
Example 118
Project: property-db   File: KeyguardWidgetPager.java View source code 6 votes vote down vote up
public KeyguardWidgetPager(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    if (getImportantForAccessibility() == View.IMPORTANT_FOR_ACCESSIBILITY_AUTO) {
        setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
    }

    setPageSwitchListener(this);

    mBackgroundWorkerThread = new HandlerThread("KeyguardWidgetPager Worker");
    mBackgroundWorkerThread.start();
    mBackgroundWorkerHandler = new Handler(mBackgroundWorkerThread.getLooper());
}
 
Example 119
Project: gag   File: AndroidInput.java View source code 6 votes vote down vote up
public AndroidInput (Application activity, Context context, Object view, AndroidApplicationConfiguration config) {
	// we hook into View, for LWPs we call onTouch below directly from
	// within the AndroidLivewallpaperEngine#onTouchEvent() method.
	if (view instanceof View) {
		View v = (View)view;
		v.setOnKeyListener(this);
		v.setOnTouchListener(this);			
		v.setFocusable(true);
		v.setFocusableInTouchMode(true);
		v.requestFocus();
		v.requestFocusFromTouch();
	}
	this.config = config;
	this.onscreenKeyboard = new AndroidOnscreenKeyboard(context, new Handler(), this);

	for (int i = 0; i < realId.length; i++)
		realId[i] = -1;
	handle = new Handler();
	this.app = activity;
	this.context = context;
	this.sleepTime = config.touchSleepTime;
	int sdkVersion = Integer.parseInt(android.os.Build.VERSION.SDK);
	if (sdkVersion >= 5)
		touchHandler = new AndroidMultiTouchHandler();
	else
		touchHandler = new AndroidSingleTouchHandler();
	hasMultitouch = touchHandler.supportsMultitouch(context);

	vibrator = (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);

	int rotation = getRotation();
	DisplayMode mode = app.getGraphics().getDesktopDisplayMode();
	if (((rotation == 0 || rotation == 180) && (mode.width >= mode.height))
		|| ((rotation == 90 || rotation == 270) && (mode.width <= mode.height))) {
		nativeOrientation = Orientation.Landscape;
	} else {
		nativeOrientation = Orientation.Portrait;
	}
}
 
Example 120
Project: ABPlayer   File: PLA_AbsListView.java View source code 6 votes vote down vote up
@Override
public void getFocusedRect(Rect r) {
	View view = getSelectedView();
	if (view != null && view.getParent() == this) {
		// the focused rectangle of the selected view offset into the
		// coordinate space of this view.
		view.getFocusedRect(r);
		offsetDescendantRectToMyCoords(view, r);
	} else {
		// otherwise, just the norm
		super.getFocusedRect(r);
	}
}
 
Example 121
Project: property-db   File: TwoStatePreference.java View source code 6 votes vote down vote up
void sendAccessibilityEvent(View view) {
    // Since the view is still not attached we create, populate,
    // and send the event directly since we do not know when it
    // will be attached and posting commands is not as clean.
    AccessibilityManager accessibilityManager = AccessibilityManager.getInstance(getContext());
    if (mSendClickAccessibilityEvent && accessibilityManager.isEnabled()) {
        AccessibilityEvent event = AccessibilityEvent.obtain();
        event.setEventType(AccessibilityEvent.TYPE_VIEW_CLICKED);
        view.onInitializeAccessibilityEvent(event);
        view.dispatchPopulateAccessibilityEvent(event);
        accessibilityManager.sendAccessibilityEvent(event);
    }
    mSendClickAccessibilityEvent = false;
}
 
Example 122
Project: property-db   File: AbsListView.java View source code 6 votes vote down vote up
/**
 * Put a view into the ScrapViews list. These views are unordered.
 *
 * @param scrap The view to add
 */
void addScrapView(View scrap, int position) {
    AbsListView.LayoutParams lp = (AbsListView.LayoutParams) scrap.getLayoutParams();
    if (lp == null) {
        return;
    }

    lp.scrappedFromPosition = position;

    // Don't put header or footer views or views that should be ignored
    // into the scrap heap
    int viewType = lp.viewType;
    final boolean scrapHasTransientState = scrap.hasTransientState();
    if (!shouldRecycleViewType(viewType) || scrapHasTransientState) {
        if (viewType != ITEM_VIEW_TYPE_HEADER_OR_FOOTER || scrapHasTransientState) {
            if (mSkippedScrap == null) {
                mSkippedScrap = new ArrayList<View>();
            }
            mSkippedScrap.add(scrap);
        }
        if (scrapHasTransientState) {
            if (mTransientStateViews == null) {
                mTransientStateViews = new SparseArray<View>();
            }
            scrap.dispatchStartTemporaryDetach();
            mTransientStateViews.put(position, scrap);
        }
        return;
    }

    scrap.dispatchStartTemporaryDetach();
    if (mViewTypeCount == 1) {
        mCurrentScrap.add(scrap);
    } else {
        mScrapViews[viewType].add(scrap);
    }

    scrap.setAccessibilityDelegate(null);
    if (mRecyclerListener != null) {
        mRecyclerListener.onMovedToScrapHeap(scrap);
    }
}
 
Example 123
Project: DemoProject   File: Animation.java View source code 6 votes vote down vote up
public void onClick(View v) {
    Log.i(TAG, "Starting thumbnail-zoom animation...");
    // Create a thumbnail animation.  We are going to build our thumbnail
    // just from the view that was pressed.  We make sure the view is
    // not selected, because by the time the animation starts we will
    // have finished with the selection of the tap.
    v.setDrawingCacheEnabled(true);
    v.setPressed(false);
    v.refreshDrawableState();
    Bitmap bm = v.getDrawingCache();
    Canvas c = new Canvas(bm);
    //c.drawARGB(255, 255, 0, 0);
    ActivityOptions opts = ActivityOptions.makeThumbnailScaleUpAnimation(
            v, bm, 0, 0);
    // Request the activity be started, using the custom animation options.
    startActivity(new Intent(Animation.this, AlertDialogSamples.class), opts.toBundle());
    v.setDrawingCacheEnabled(false);
}
 
Example 124
Project: BioWiki   File: SwipeDismissListViewTouchListener.java View source code 6 votes vote down vote up
@Override
public boolean onTouch(final View view, final MotionEvent motionEvent) {
    if (mVirtualListCount == -1) {
        mVirtualListCount = mListView.getAdapter().getCount();
    }

    if (mViewWidth < 2) {
        mViewWidth = mListView.getWidth();
    }

    switch (motionEvent.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            mDisallowSwipe = false;
            view.onTouchEvent(motionEvent);
            return handleDownEvent(motionEvent);
        case MotionEvent.ACTION_MOVE:
            return handleMoveEvent(motionEvent);
        case MotionEvent.ACTION_CANCEL:
            return handleCancelEvent(motionEvent);
        case MotionEvent.ACTION_UP:

            mDisallowSwipe = false;
            mTouchChildTouched = false;
            return handleUpEvent(motionEvent);

    }
    return false;
}
 
Example 125
Project: BCP-Mobile   File: AssignmentAdapter.java View source code 6 votes vote down vote up
@Override
  public View getView(int position, View convertView, ViewGroup parent) {
  	View v = convertView;

final Item i = data[position];
if (i != null) {
	if(i.isSection()) {
		SectionItem si = (SectionItem)i;
		v = inflater.inflate(R.layout.list_item_section, null);

		v.setOnClickListener(null);
		v.setOnLongClickListener(null);
		v.setLongClickable(false);
		
		final TextView sectionView = (TextView) v.findViewById(R.id.list_item_section_text);
		sectionView.setText(si.getTitle());
		
	} else {
		Assignment asg = (Assignment) i;
		v = inflater.inflate(R.layout.course_item_row, null);
		final TextView name = (TextView) v.findViewById(R.id.asg_name);
		final TextView percent = (TextView) v.findViewById(R.id.asg_percent);
		final ImageView letter = (ImageView) v.findViewById(R.id.asg_letter);
		
		if (name != null) 
			name.setText(asg.name);
		if(percent != null)
			percent.setText(decimalFormat.format(asg.score) + " / " + decimalFormat.format(asg.total));
		if(letter != null)
			letter.setImageResource(getIdFromGrade(asg.letter));
	}
}
return v;
  }
 
Example 126
Project: packages_apps_Launcher2   File: Workspace.java View source code 6 votes vote down vote up
/**
 * Adds the specified child in the specified screen. The position and dimension of
 * the child are defined by x, y, spanX and spanY.
 *
 * @param child The child to add in one of the workspace's screens.
 * @param screen The screen in which to add the child.
 * @param x The X position of the child in the screen's grid.
 * @param y The Y position of the child in the screen's grid.
 * @param spanX The number of cells spanned horizontally by the child.
 * @param spanY The number of cells spanned vertically by the child.
 * @param insert When true, the child is inserted at the beginning of the children list.
 */
void addInScreen(View child, int screen, int x, int y, int spanX, int spanY, boolean insert) {
    if (screen < 0 || screen >= getChildCount()) {
        Log.e(TAG, "The screen must be >= 0 and < " + getChildCount()
            + " (was " + screen + "); skipping child");
        return;
    }

    clearVacantCache();

    final CellLayout group = (CellLayout) getChildAt(screen);
    CellLayout.LayoutParams lp = (CellLayout.LayoutParams) child.getLayoutParams();
    if (lp == null) {
        lp = new CellLayout.LayoutParams(x, y, spanX, spanY);
    } else {
        lp.cellX = x;
        lp.cellY = y;
        lp.cellHSpan = spanX;
        lp.cellVSpan = spanY;
    }
    group.addView(child, insert ? 0 : -1, lp);
    if (!(child instanceof Folder)) {
        child.setHapticFeedbackEnabled(false);
        child.setOnLongClickListener(mLongClickListener);
    }
    if (child instanceof DropTarget) {
        mDragController.addDropTarget((DropTarget)child);
    }
}
 
Example 127
Project: GWSHolmesWatson   File: LayoutInflater.java View source code 6 votes vote down vote up
@SuppressLint("NewApi")
private View prepareView(View view) {
    if (HoloEverywhere.DISABLE_OVERSCROLL_EFFECT && VERSION.SDK_INT >= 9) {
        view.setOverScrollMode(View.OVER_SCROLL_NEVER);
    }
    return view;
}
 
Example 128
Project: SealBrowser   File: ApiCompatibilityUtils.java View source code 6 votes vote down vote up
/**
 * Returns true if view's layout direction is right-to-left.
 *
 * @param view the View whose layout is being considered
 */
public static boolean isLayoutRtl(View view) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return view.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
    } else {
        // All layouts are LTR before JB MR1.
        return false;
    }
}
 
Example 129
Project: Gui2Go   File: GridViewItemClickListener.java View source code 6 votes vote down vote up
@Override
public boolean onItemLongClick(AdapterView<?> parent, View v,
		int position, long id)
{
	LinearLayout lay = (LinearLayout) v;
	String tag = (String) ((TextView) lay.getChildAt(0)).getText();
	String[] mimeTypes = { ClipDescription.MIMETYPE_TEXT_PLAIN };

	ClipData.Item item = new ClipData.Item(tag);
	ClipData dragData = new ClipData("GridViewItem", mimeTypes, item);

	View.DragShadowBuilder myShadow = new DragShadowBuilder(v);

	v.startDrag(dragData, myShadow, null, 0);
	return true;
}
 
Example 130
Project: danbooru-gallery-android   File: GalleryViewPager.java View source code 6 votes vote down vote up
@SuppressLint("NewApi")
@Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
    if (v instanceof TouchImageView) {
        return v.canScrollHorizontally(dx);
    } else {
        return super.canScroll(v, checkV, dx, x, y);
    }
}
 
Example 131
Project: drinkly   File: FButton.java View source code 6 votes vote down vote up
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    switch (motionEvent.getAction()) {
        case MotionEvent.ACTION_DOWN:
            updateBackground(pressedDrawable);
            this.setPadding(mPaddingLeft, mPaddingTop + mShadowHeight, mPaddingRight, mPaddingBottom);
            break;
        case MotionEvent.ACTION_MOVE:
            Rect r = new Rect();
            view.getLocalVisibleRect(r);
            if (!r.contains((int) motionEvent.getX(), (int) motionEvent.getY() + 3 * mShadowHeight) &&
                    !r.contains((int) motionEvent.getX(), (int) motionEvent.getY() - 3 * mShadowHeight)) {
                updateBackground(unpressedDrawable);
                this.setPadding(mPaddingLeft, mPaddingTop + mShadowHeight, mPaddingRight, mPaddingBottom + mShadowHeight);
            }
            break;
        case MotionEvent.ACTION_OUTSIDE:
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_UP:
            updateBackground(unpressedDrawable);
            this.setPadding(mPaddingLeft, mPaddingTop + mShadowHeight, mPaddingRight, mPaddingBottom + mShadowHeight);
            break;
    }
    return false;
}
 
Example 132
Project: framework-master   File: PtrDefaultHandler.java View source code 6 votes vote down vote up
/**
 * Default implement for check can perform pull to refresh
 *
 * @param frame
 * @param content
 * @param header
 * @return
 */
public static boolean checkContentCanBePulledDown(PtrFrameLayout frame, View content, View header) {
    if (!(content instanceof ViewGroup)) {
        return true;
    }

    ViewGroup viewGroup = (ViewGroup) content;
    if (viewGroup.getChildCount() == 0) {
        return true;
    }

    if (viewGroup instanceof AbsListView) {
        AbsListView listView = (AbsListView) viewGroup;
        if (listView.getFirstVisiblePosition() > 0) {
            return false;
        }
    }

    if (Build.VERSION.SDK_INT >= 14) {
        return !content.canScrollVertically(-1);
    } else {
        if (viewGroup instanceof ScrollView || viewGroup instanceof AbsListView) {
            return viewGroup.getScrollY() == 0;
        }
    }

    View child = viewGroup.getChildAt(0);
    ViewGroup.LayoutParams glp = child.getLayoutParams();
    int top = child.getTop();
    if (glp instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) glp;
        return top == mlp.topMargin + viewGroup.getPaddingTop();
    } else {
        return top == viewGroup.getPaddingTop();
    }
}
 
Example 133
Project: SealBrowser   File: ApiCompatibilityUtils.java View source code 6 votes vote down vote up
/**
 * @see android.view.View#setLayoutDirection(int)
 */
public static void setLayoutDirection(View view, int layoutDirection) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        view.setLayoutDirection(layoutDirection);
    } else {
        // Do nothing. RTL layouts aren't supported before JB MR1.
    }
}
 
Example 134
Project: Android-automation   File: ViewUtils.java View source code 6 votes vote down vote up
/**
 * Returns the most recent view container
 * 
 * @param views
 *            the views to check
 * @return the most recent view container
 * 
 */

private final View getRecentContainer(View[] views) {
	View container = null;
	long drawingTime = 0;
	View view;

	for (int i = 0; i < views.length; i++) {
		view = views[i];
		if (view != null && view.isShown() && view.hasWindowFocus()
				&& view.getDrawingTime() > drawingTime) {
			container = view;
			drawingTime = view.getDrawingTime();
		}
	}
	return container;
}
 
Example 135
Project: property-db   File: AlertController.java View source code 6 votes vote down vote up
static boolean canTextInput(View v) {
    if (v.onCheckIsTextEditor()) {
        return true;
    }
    
    if (!(v instanceof ViewGroup)) {
        return false;
    }
    
    ViewGroup vg = (ViewGroup)v;
    int i = vg.getChildCount();
    while (i > 0) {
        i--;
        v = vg.getChildAt(i);
        if (canTextInput(v)) {
            return true;
        }
    }
    
    return false;
}
 
Example 136
Project: property-db   File: AccessibilityNodeInfo.java View source code 6 votes vote down vote up
/**
 * Sets the source to be a virtual descendant of the given <code>root</code>.
 * If <code>virtualDescendantId</code> is [email protected] View#NO_ID} the root
 * is set as the source.
 * <p>
 * A virtual descendant is an imaginary View that is reported as a part of the view
 * hierarchy for accessibility purposes. This enables custom views that draw complex
 * content to report themselves as a tree of virtual views, thus conveying their
 * logical structure.
 * </p>
 * <p>
 *   <strong>Note:</strong> Cannot be called from an
 *   [email protected] android.accessibilityservice.AccessibilityService}.
 *   This class is made immutable before being delivered to an AccessibilityService.
 * </p>
 *
 * @param root The root of the virtual subtree.
 * @param virtualDescendantId The id of the virtual descendant.
 */
public void setSource(View root, int virtualDescendantId) {
    enforceNotSealed();
    mWindowId = (root != null) ? root.getAccessibilityWindowId() : UNDEFINED;
    final int rootAccessibilityViewId =
        (root != null) ? root.getAccessibilityViewId() : UNDEFINED;
    mSourceNodeId = makeNodeId(rootAccessibilityViewId, virtualDescendantId);
}
 
Example 137
Project: ExcusePro   File: IcsProgressBar.java View source code 6 votes vote down vote up
@Override
protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    Drawable d = mCurrentDrawable;

    int dw = 0;
    int dh = 0;
    if (d != null) {
        dw = Math.max(mMinWidth, Math.min(mMaxWidth, d.getIntrinsicWidth()));
        dh = Math.max(mMinHeight, Math.min(mMaxHeight, d.getIntrinsicHeight()));
    }
    updateDrawableState();
    dw += getPaddingLeft() + getPaddingRight();
    dh += getPaddingTop() + getPaddingBottom();

    if (IS_HONEYCOMB) {
        setMeasuredDimension(View.resolveSizeAndState(dw, widthMeasureSpec, 0),
                View.resolveSizeAndState(dh, heightMeasureSpec, 0));
    } else {
        setMeasuredDimension(View.resolveSize(dw, widthMeasureSpec),
                View.resolveSize(dh, heightMeasureSpec));
    }
}
 
Example 138
Project: property-db   File: ListView.java View source code 6 votes vote down vote up
/**
 * To avoid horizontal focus searches changing the selected item, we
 * manually focus search within the selected item (as applicable), and
 * prevent focus from jumping to something within another item.
 * @param direction one of {View.FOCUS_LEFT, View.FOCUS_RIGHT}
 * @return Whether this consumes the key event.
 */
private boolean handleHorizontalFocusWithinListItem(int direction) {
    if (direction != View.FOCUS_LEFT && direction != View.FOCUS_RIGHT)  {
        throw new IllegalArgumentException("direction must be one of"
                + " {View.FOCUS_LEFT, View.FOCUS_RIGHT}");
    }

    final int numChildren = getChildCount();
    if (mItemsCanFocus && numChildren > 0 && mSelectedPosition != INVALID_POSITION) {
        final View selectedView = getSelectedView();
        if (selectedView != null && selectedView.hasFocus() &&
                selectedView instanceof ViewGroup) {

            final View currentFocus = selectedView.findFocus();
            final View nextFocus = FocusFinder.getInstance().findNextFocus(
                    (ViewGroup) selectedView, currentFocus, direction);
            if (nextFocus != null) {
                // do the math to get interesting rect in next focus' coordinates
                currentFocus.getFocusedRect(mTempRect);
                offsetDescendantRectToMyCoords(currentFocus, mTempRect);
                offsetRectIntoDescendantCoords(nextFocus, mTempRect);
                if (nextFocus.requestFocus(direction, mTempRect)) {
                    return true;
                }
            }
            // we are blocking the key from being handled (by returning true)
            // if the global result is going to be some other view within this
            // list.  this is to acheive the overall goal of having
            // horizontal d-pad navigation remain in the current item.
            final View globalNextFocus = FocusFinder.getInstance().findNextFocus(
                    (ViewGroup) getRootView(), currentFocus, direction);
            if (globalNextFocus != null) {
                return isViewAncestorOf(globalNextFocus, this);
            }
        }
    }
    return false;
}
 
Example 139
Project: ABPlayer   File: PLA_AbsListView.java View source code 6 votes vote down vote up
private void dispatchFinishTemporaryDetach(View v) {
	if( v == null )
		return;

	v.onFinishTemporaryDetach();
	if( v instanceof ViewGroup){
		ViewGroup group = (ViewGroup) v;
		final int count = group.getChildCount();
		for (int i = 0; i < count; i++) {
			dispatchFinishTemporaryDetach(group.getChildAt(i));
		}			
	}
}
 
Example 140
Project: googleio   File: FractionalTouchDelegate.java View source code 6 votes vote down vote up
/**
 * Helper to create and setup a [email protected] FractionalTouchDelegate} between the
 * given [email protected] View}.
 *
 * @param source Larger source [email protected] View}, usually a parent, that will be
 *            assigned [email protected] View#setTouchDelegate(TouchDelegate)}.
 * @param target Smaller target [email protected] View} which will receive
 *            [email protected] MotionEvent} that land in requested fractional area.
 * @param sourceFraction Fractional area projected onto source [email protected] View}
 *            which determines when [email protected] MotionEvent} will be passed to
 *            target [email protected] View}.
 */
public static void setupDelegate(View source, View target, RectF sourceFraction) {
    source.setTouchDelegate(new FractionalTouchDelegate(source, target, sourceFraction));
}
 
Example 141
Project: SealBrowser   File: OverScrollGlow.java View source code 6 votes vote down vote up
/**
 * Pull leftover touch scroll distance into one of the edge glows as appropriate.
 *
 * @param x Current X scroll offset
 * @param y Current Y scroll offset
 * @param oldX Old X scroll offset
 * @param oldY Old Y scroll offset
 * @param maxX Maximum range for horizontal scrolling
 * @param maxY Maximum range for vertical scrolling
 */
public void pullGlow(int x, int y, int oldX, int oldY, int maxX, int maxY) {
    // Only show overscroll bars if there was no movement in any direction
    // as a result of scrolling.
    if (oldX == mHostView.getScrollX() && oldY == mHostView.getScrollY()) {
        // Don't show left/right glows if we fit the whole content.
        // Also don't show if there was vertical movement.
        if (maxX > 0) {
            final int pulledToX = oldX + mOverScrollDeltaX;
            if (pulledToX < 0) {
                mEdgeGlowLeft.onPull((float) mOverScrollDeltaX / mHostView.getWidth());
                if (!mEdgeGlowRight.isFinished()) {
                    mEdgeGlowRight.onRelease();
                }
            } else if (pulledToX > maxX) {
                mEdgeGlowRight.onPull((float) mOverScrollDeltaX / mHostView.getWidth());
                if (!mEdgeGlowLeft.isFinished()) {
                    mEdgeGlowLeft.onRelease();
                }
            }
            mOverScrollDeltaX = 0;
        }

        if (maxY > 0 || mHostView.getOverScrollMode() == View.OVER_SCROLL_ALWAYS) {
            final int pulledToY = oldY + mOverScrollDeltaY;
            if (pulledToY < 0) {
                mEdgeGlowTop.onPull((float) mOverScrollDeltaY / mHostView.getHeight());
                if (!mEdgeGlowBottom.isFinished()) {
                    mEdgeGlowBottom.onRelease();
                }
            } else if (pulledToY > maxY) {
                mEdgeGlowBottom.onPull((float) mOverScrollDeltaY / mHostView.getHeight());
                if (!mEdgeGlowTop.isFinished()) {
                    mEdgeGlowTop.onRelease();
                }
            }
            mOverScrollDeltaY = 0;
        }
    }
}
 
Example 142
Project: property-db   File: ListView.java View source code 6 votes vote down vote up
View findViewInHeadersOrFooters(ArrayList<FixedViewInfo> where, int id) {
    if (where != null) {
        int len = where.size();
        View v;

        for (int i = 0; i < len; i++) {
            v = where.get(i).view;

            if (!v.isRootNamespace()) {
                v = v.findViewById(id);

                if (v != null) {
                    return v;
                }
            }
        }
    }
    return null;
}
 
Example 143
Project: openxface-android   File: XInAppBrowser.java View source code 6 votes vote down vote up
/**
 * ?????
 */
protected void buildEditText() {
    RelativeLayout.LayoutParams textLayoutParams = new RelativeLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    textLayoutParams.addRule(RelativeLayout.RIGHT_OF, 1);
    textLayoutParams.addRule(RelativeLayout.LEFT_OF, 5);
    OnKeyListener keyListener = new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if ((event.getAction() == KeyEvent.ACTION_DOWN)
                    && (keyCode == KeyEvent.KEYCODE_ENTER)) {
                navigate(mEditText.getText().toString());
                return true;
            }
            return false;
        }
    };
    mEditText =  createEditText(EDITTEXT_ID, textLayoutParams, true, mUrl,
            InputType.TYPE_TEXT_VARIATION_URI, EditorInfo.IME_ACTION_GO,
            keyListener);
}
 
Example 144
Project: Android-Json-Parsing-Code-Sample   File: RippleManager.java View source code 6 votes vote down vote up
/**
    * Should be called in the construction method of view to create a RippleDrawable.
    * @param v
    * @param context
    * @param attrs
    * @param defStyleAttr
    * @param defStyleRes
    */
public void onCreate(View v, Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes){
	if(v.isInEditMode())
		return;

	mView = v;
	
	TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RippleView, defStyleAttr, defStyleRes);
       int rippleStyle = a.getResourceId(R.styleable.RippleView_rd_style, 0);
	RippleDrawable drawable = null;

	if(rippleStyle != 0)
		drawable = new RippleDrawable.Builder(context, rippleStyle).backgroundDrawable(mView.getBackground()).build();
	else{
		boolean rippleEnable = a.getBoolean(R.styleable.RippleView_rd_enable, false);
		if(rippleEnable)
			drawable = new RippleDrawable.Builder(context, attrs, defStyleAttr, defStyleRes).backgroundDrawable(mView.getBackground()).build();
	}

	a.recycle();

	if(drawable != null)
           ViewUtil.setBackground(mView, drawable);
}
 
Example 145
Project: SealBrowser   File: ContentViewCore.java View source code 6 votes vote down vote up
/**
 * @see View#awakenScrollBars(int, boolean)
 */
@SuppressWarnings("javadoc")
public boolean awakenScrollBars(int startDelay, boolean invalidate) {
    // For the default implementation of ContentView which draws the scrollBars on the native
    // side, calling this function may get us into a bad state where we keep drawing the
    // scrollBars, so disable it by always returning false.
    if (mContainerView.getScrollBarStyle() == View.SCROLLBARS_INSIDE_OVERLAY) {
        return false;
    } else {
        return mContainerViewInternals.super_awakenScrollBars(startDelay, invalidate);
    }
}
 
Example 146
Project: adapterviewanimator   File: AdapterViewAnimator.java View source code 6 votes vote down vote up
private void beforeDataSetChanged() {
  Adapter adapter = adapterView.getAdapter();
  final int firstVisiblePosition = adapterView.getFirstVisiblePosition();
  for (int i = 0, childCount = adapterView.getChildCount(); i < childCount; i++) {
    final int position = firstVisiblePosition + i;
    final long id = adapter.getItemId(position);
    final View child = adapterView.getChildAt(i);
    Rect r = new Rect(child.getLeft(), child.getTop(), child.getRight(), child.getBottom());
    child.setHasTransientState(true);
    viewBounds.put(id, r);
    idToViewMap.put(id, child);
  }
}
 
Example 147
Project: extension-android-immersive   File: AndroidImmersive.java View source code 6 votes vote down vote up
/**
	 * Called when the activity is starting.
	 */
	@Override public void onCreate (Bundle savedInstanceState) {
		Log.i("IMM", "create");
		View decorView = mainActivity.getWindow().getDecorView();
		decorView.setOnSystemUiVisibilityChangeListener (new View.OnSystemUiVisibilityChangeListener() {
    	@Override
   		public void onSystemUiVisibilityChange(int visibility) {
   			if(Build.VERSION.SDK_INT < 16 || Build.VERSION.SDK_INT >= 19){
   				//super.onSystemUiVisibilityChange(visibility);
   				return;
   			}
        	// Note that system bars will only be "visible" if none of the
        	// LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
        	if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
            handleSystemUIHide();
        	} else {
            handleSystemUIHide();
        }
    }
});
	}
 
Example 148
Project: TintLayout   File: TintLayout.java View source code 6 votes vote down vote up
public TintLayout(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TintLayout);

    try {
        final double tempAngle = typedArray.getFloat(R.styleable.TintLayout_angle, 45f);
        if (tempAngle >= 0 && tempAngle <= 360) {
            this.angle = tempAngle;
        } else {
            throw new IllegalArgumentException(getResources().getString(R.string.angle_exception));
        }

        final int colorsId = typedArray.getResourceId(R.styleable.TintLayout_colors, 0);
        if (colorsId != 0) {
            setColors(getResources().getIntArray(colorsId));
        } else {
            setColors(getResources().getIntArray(R.array.default_colors));
        }
    } finally {
        typedArray.recycle();
    }


    setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    setWillNotDraw(false);
}
 
Example 149
Project: sdk-support   File: FragmentTransitionCompat21.java View source code 6 votes vote down vote up
public static void findNamedViews(Map<String, View> namedViews, View view) {
    if (view.getVisibility() == View.VISIBLE) {
        String transitionName = view.getTransitionName();
        if (transitionName != null) {
            namedViews.put(transitionName, view);
        }
        if (view instanceof ViewGroup) {
            ViewGroup viewGroup = (ViewGroup) view;
            int count = viewGroup.getChildCount();
            for (int i = 0; i < count; i++) {
                View child = viewGroup.getChildAt(i);
                findNamedViews(namedViews, child);
            }
        }
    }
}
 
Example 150
Project: WallpaperPicker   File: Utilities.java View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean isViewAttachedToWindow(View v) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        return v.isAttachedToWindow();
    } else {
        // A proxy call which returns null, if the view is not attached to the window.
        return v.getKeyDispatcherState() != null;
    }
}
 
Example 151
Project: SystemUiHelper   File: SystemUiHelperImplKK.java View source code 6 votes vote down vote up
@Override
protected int createHideFlags() {
    int flag = super.createHideFlags();

    if (mLevel == SystemUiHelper.LEVEL_IMMERSIVE) {
        // If the client requested immersive mode, and we're on Android 4.4
        // or later, add relevant flags. Applying HIDE_NAVIGATION without
        // IMMERSIVE prevents the activity from accepting all touch events,
        // so we only do this on Android 4.4 and later (where IMMERSIVE is
        // present).
        flag |= ((mFlags & SystemUiHelper.FLAG_IMMERSIVE_STICKY) != 0)
                        ? View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                        : View.SYSTEM_UI_FLAG_IMMERSIVE;
    }

    return flag;
}
 
Example 152
Project: Accessibility-Test-Framework-for-Android   File: ViewAccessibilityUtils.java View source code 6 votes vote down vote up
/**
 * @see View#isImportantForAccessibility()
 */
public static boolean isImportantForAccessibility(View view) {
  if (view == null) {
    return false;
  }

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return view.isImportantForAccessibility();
  } else {
    // On earlier APIs, we must piece together accessibility importance from the available
    // properties. We return false incorrectly for some cases where unretrievable listeners
    // prevent us from determining importance.

    // If the developer marked the view as explicitly not important, it isn't.
    int mode = view.getImportantForAccessibility();
    if ((mode == View.IMPORTANT_FOR_ACCESSIBILITY_NO)
        || (mode == View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS)) {
      return false;
    }

    // No parent view can be hiding us. (APIs 19 to 21)
    ViewParent parent = view.getParent();
    while (parent instanceof View) {
      if (((View) parent).getImportantForAccessibility()
          == View.IMPORTANT_FOR_ACCESSIBILITY_NO_HIDE_DESCENDANTS) {
        return false;
      }
      parent = parent.getParent();
    }

    // Interrogate the view's other properties to determine importance.
    return (mode == View.IMPORTANT_FOR_ACCESSIBILITY_YES)
        || isActionableForAccessibility(view)
        || hasListenersForAccessibility(view)
        || (view.getAccessibilityNodeProvider() != null)
        || (ViewCompat.getAccessibilityLiveRegion(view)
            != ViewCompat.ACCESSIBILITY_LIVE_REGION_NONE);
  }
}
 
Example 153
Project: Accessibility-Test-Framework-for-Android   File: ViewAccessibilityUtils.java View source code 6 votes vote down vote up
private static View lookForLabelForViewInViewAndChildren(View view, View childToSkip,
    int idToFind) {
  if (view.getLabelFor() == idToFind) {
    return view;
  }
  if (!(view instanceof ViewGroup)) {
    return null;
  }
  ViewGroup viewGroup = (ViewGroup) view;
  for (int i = 0; i < viewGroup.getChildCount(); ++i) {
    View child = viewGroup.getChildAt(i);
    if (!child.equals(childToSkip)) {
      View labelingView = lookForLabelForViewInViewAndChildren(child, null, idToFind);
      if (labelingView != null) {
        return labelingView;
      }
    }
  }
  return null;
}
 
Example 154
Project: slkr   File: CourseAdapter.java View source code 6 votes vote down vote up
@Override
public CourseAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
  context = parent.getContext();
    // create a new view
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.course_card, parent, false);
    // set the view's size, margins, paddings and layout parameters
    v.setPadding(10,10,10,0);
    v.setElevation(10);
    v.animate();
    ViewHolder vh = new ViewHolder(v);
    return vh;
}
 
Example 155
Project: platform-friends-android   File: CreateNewUserActivity.java View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.create_new_user);

    getActionBar().hide();

    this.maleButton = (ToggleButton) findViewById(R.id.cnu_maleButton);
    this.femaleButton = (ToggleButton) findViewById(R.id.cnu_femaleButton);
    this.maleButton.setOnClickListener(this);
    this.femaleButton.setOnClickListener(this);
    this.birthDay = (EditText) findViewById(R.id.cnu_birthday);
    this.birthDay.setOnClickListener(this);
    this.birthDay.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                displayDatePicker();
            }
        }
    });

    this.name = (EditText) findViewById(R.id.cnu_name);
    MyTextWatcher textWatcher = new MyTextWatcher();
    this.name.addTextChangedListener(textWatcher);

    this.email = (EditText) findViewById(R.id.cnu_email);
    this.username = (EditText) findViewById(R.id.cnu_username);
    this.username.addTextChangedListener(textWatcher);

    this.password = (EditText) findViewById(R.id.cnu_password);
    this.password.addTextChangedListener(textWatcher);

    this.about = (EditText) findViewById(R.id.cnu_about);
    this.registerButton = (Button) findViewById(R.id.cnu_register);
    this.registerButton.setOnClickListener(this);
}
 
Example 156
Project: Accessibility-Test-Framework-for-Android   File: ViewAccessibilityUtils.java View source code 6 votes vote down vote up
/**
 * Determines if the supplied [email protected] View} has an ancestor which meets the criteria for gaining
 * accessibility focus.
 * <p>
 * NOTE: This method only evaluates ancestors which may be considered important for accessibility
 * and explicitly does not evaluate the supplied [email protected] view}.
 *
 * @param view The [email protected] View} to evaluate
 * @return [email protected] true} if an ancestor of [email protected] view} may gain accessibility focus, [email protected] false}
 *         otherwise
 */
private static boolean hasFocusableAncestor(View view) {
  if (view == null) {
    return false;
  }

  ViewParent parent = view.getParentForAccessibility();
  if (!(parent instanceof View)) {
    return false;
  }

  if (isAccessibilityFocusable((View) parent)) {
    return true;
  }

  return hasFocusableAncestor((View) parent);
}
 
Example 157
Project: Context-Menu.Android   File: ContextMenuDialogFragment.java View source code 6 votes vote down vote up
@SuppressLint("NewApi")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
    rootView.setFitsSystemWindows(mMenuParams.isFitsSystemWindow());
    ((ViewGroup) rootView).setClipToPadding(mMenuParams.isClipToPadding());

    initViews(rootView);
    getDialog().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    initDropDownMenuAdapter();
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            mDropDownMenuAdapter.menuToggle();
        }
    }, mMenuParams.getAnimationDelay());

    if (mMenuParams.isClosableOutside()) {
        rootView.findViewById(R.id.root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().onBackPressed();
            }
        });
    }
    return rootView;
}
 
Example 158
Project: FoldingLayout   File: FoldingLayoutActivity.java View source code 6 votes vote down vote up
private void setSepiaLayer (View view, boolean isSepiaLayerOn) {
    if (!IS_JBMR2) {
        if (isSepiaLayerOn) {
            view.setLayerType(View.LAYER_TYPE_HARDWARE, null);
            view.setLayerPaint(mSepiaPaint);
        } else {
            view.setLayerPaint(mDefaultPaint);
        }
    }
}
 
Example 159
Project: AndroidListViewBackport   File: Compat.java View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static int getMeasuredState(View view) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        return view.getMeasuredState();
    } else {
        return 0;
    }
}
 
Example 160
Project: property-db   File: PopupWindow.java View source code 6 votes vote down vote up
@Override
protected int[] onCreateDrawableState(int extraSpace) {
    if (mAboveAnchor) {
        // 1 more needed for the above anchor state
        final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
        View.mergeDrawableStates(drawableState, ABOVE_ANCHOR_STATE_SET);
        return drawableState;
    } else {
        return super.onCreateDrawableState(extraSpace);
    }
}
 
Example 161
Project: property-db   File: MenuPopupHelper.java View source code 6 votes vote down vote up
public boolean tryShow() {
    mPopup = new ListPopupWindow(mContext, null, com.android.internal.R.attr.popupMenuStyle);
    mPopup.setOnDismissListener(this);
    mPopup.setOnItemClickListener(this);

    mAdapter = new MenuAdapter(mMenu);
    mPopup.setAdapter(mAdapter);
    mPopup.setModal(true);

    View anchor = mAnchorView;
    if (anchor != null) {
        final boolean addGlobalListener = mTreeObserver == null;
        mTreeObserver = anchor.getViewTreeObserver(); // Refresh to latest
        if (addGlobalListener) mTreeObserver.addOnGlobalLayoutListener(this);
        anchor.addOnAttachStateChangeListener(this);
        mPopup.setAnchorView(anchor);
    } else {
        return false;
    }

    mPopup.setContentWidth(Math.min(measureContentWidth(mAdapter), mPopupMaxWidth));
    mPopup.setInputMethodMode(PopupWindow.INPUT_METHOD_NOT_NEEDED);
    mPopup.show();
    mPopup.getListView().setOnKeyListener(this);
    return true;
}
 
Example 162
Project: dlna   File: YouPlayerAppFrame.java View source code 6 votes vote down vote up
public void setPortraitScreen(Activity context) {
        if(context != null){
            try {
            	if(fullPlayerControler != null)
            	{
//            		fullPlayerControler.getView().setKeepScreenOn(false);
            		View view = fullPlayerControler.getView();
            		if(view != null)
            		view.setKeepScreenOn(false);
            	}
                final WindowManager.LayoutParams attrs = context.getWindow().getAttributes();
                attrs.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
                context.getWindow().setAttributes(attrs);
                context.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
                context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
 
Example 163
Project: otp-authenticator-android   File: TestUtilities.java View source code 6 votes vote down vote up
/**
 * Opens the context menu for the provided [email protected] View} and invokes the menu item with the
 * provided ID.
 *
 * Note: This method cannot be invoked on the main thread.
 */
public static void openContextMenuAndInvokeItem(
    Instrumentation instrumentation, final Activity activity, final View view, final int itemId) {
  // IMPLEMENTATION NOTE: Instrumentation.invokeContextMenuAction would've been much simpler, but
  // it doesn't work on ICS because its KEY_UP event times out.
  FutureTask<Boolean> task = new FutureTask<Boolean>(new Callable<Boolean>() {
    @Override
    public Boolean call() {
      // Use performLongClick instead of showContextMenu to exercise more of the code path that
      // is invoked when the user normally opens a context menu.
      view.performLongClick();
      return activity.getWindow().performContextMenuIdentifierAction(itemId, 0);
    }
  });
  instrumentation.runOnMainSync(task);
  try {
    if (!task.get()) {
      throw new RuntimeException("Failed to invoke context menu item with ID " + itemId);
    }
  } catch (Exception e) {
    throw new RuntimeException("Failed to open context menu and select a menu item", e);
  }
  instrumentation.waitForIdleSync();
}
 
Example 164
Project: HoverAniamtion   File: FlipPageViewTransformer.java View source code 6 votes vote down vote up
@Override
protected void onTransform(View view, float position) {
    float percentage = 1 - Math.abs(position);
    if(Build.VERSION.SDK_INT >= 13){
        view.setCameraDistance(12000);
    }
    setVisibility(view, position);
    setTranslation(view);
    setSize(view, position, percentage);
    setRotation(view, position, percentage);
}
 
Example 165
Project: property-db   File: GridLayout.java View source code 6 votes vote down vote up
/**
 * @hide
 */
@Override
protected void onDebugDrawMargins(Canvas canvas) {
    // Apply defaults, so as to remove UNDEFINED values
    LayoutParams lp = new LayoutParams();
    for (int i = 0; i < getChildCount(); i++) {
        View c = getChildAt(i);
        Insets insets = getLayoutMode() == OPTICAL_BOUNDS ? c.getOpticalInsets() : Insets.NONE;
        lp.setMargins(
                getMargin1(c, true, true) - insets.left,
                getMargin1(c, false, true) - insets.top,
                getMargin1(c, true, false) - insets.right,
                getMargin1(c, false, false) - insets.bottom);
        lp.onDebugDraw(c, canvas);
    }
}
 
Example 166
Project: andevcon-2014-jl   File: ManyListFragment.java View source code 6 votes vote down vote up
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
public static int generateViewId() {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
        for (;;) {
            final int result = sNextGeneratedId.get();
            // aapt-generated IDs have the high byte nonzero; clamp to the range under that.
            int newValue = result + 1;
            if (newValue > 0x00FFFFFF) newValue = 1; // Roll over to 1, not 0.
            if (sNextGeneratedId.compareAndSet(result, newValue)) {
                return result;
            }
        }
    } else {
        return View.generateViewId();
    }
}
 
Example 167
Project: PortalWaitingList   File: MainActivity.java View source code 6 votes vote down vote up
@Override
public void portalItemClicked(PortalDetail clickedPortal, View clickedView) {
    this.clickedPortal = clickedPortal;
    Intent detail = new Intent(this, DetailActivity.class);
    detail.putExtra(DetailActivity.ARG_CLICKED_PORTAL, clickedPortal);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
        clickedView.setTransitionName("title");
        ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this, clickedView, "title");
        startActivity(detail, options.toBundle());
        return;
    }
    startActivity(detail);
}
 
Example 168
Project: AudioBook   File: BrowserActivityTest.java View source code 6 votes vote down vote up
/**
 * Tests that a folder is clickable. This requires the device to have at
 * least one audio file within a folder (not directly on sdcard).
 */
public void testClickFolder() {
	View child = browserListView.getChildAt(0);
	String preString = child.toString();
	TouchUtils.clickView(this, child);
	View clicked = browserListView.getChildAt(0);
	assertNotNull("Clicked null", clicked);
	// assert the file was clicked. Variable clicked will be a view with the
	// title ".." and the description "Parent Folder"
	assertFalse(
			"Clicked did not change (this test requires there to be at least one audio file within a directory).",
			preString.equals(clicked.toString()));
}
 
Example 169
Project: SealBrowser   File: AwContents.java View source code 6 votes vote down vote up
/**
 * @see View#setScrollBarStyle(int)
 */
public void setScrollBarStyle(int style) {
    if (style == View.SCROLLBARS_INSIDE_OVERLAY
            || style == View.SCROLLBARS_OUTSIDE_OVERLAY) {
        mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
    } else {
        mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
    }
}
 
Example 170
Project: GWSHolmesWatson   File: FragmentBreadCrumbs.java View source code 6 votes vote down vote up
@SuppressLint("NewApi")
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int count = getChildCount();
    int maxHeight = 0;
    int maxWidth = 0;
    int measuredChildState = 0;
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (child.getVisibility() != View.GONE) {
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            maxWidth = Math.max(maxWidth, child.getMeasuredWidth());
            maxHeight = Math.max(maxHeight, child.getMeasuredHeight());
            if (VERSION.SDK_INT >= 11) {
                measuredChildState = View.combineMeasuredStates(
                        measuredChildState, child.getMeasuredState());
            } else {
                measuredChildState = View.combineMeasuredStates(
                        measuredChildState, 0);
            }
        }
    }
    maxWidth += getPaddingLeft() + getPaddingRight();
    maxHeight += getPaddingTop() + getPaddingBottom();
    maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
    maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
    setMeasuredDimension(View.resolveSizeAndState(maxWidth,
            widthMeasureSpec, measuredChildState),
            View.resolveSizeAndState(maxHeight, heightMeasureSpec,
                    measuredChildState << View.MEASURED_HEIGHT_STATE_SHIFT));
}
 
Example 171
Project: SealBrowser   File: UiUtils.java View source code 6 votes vote down vote up
private static void prepareViewHierarchyForScreenshot(View view, boolean takingScreenshot) {
    if (view instanceof ViewGroup) {
        ViewGroup viewGroup = (ViewGroup) view;
        for (int i = 0; i < viewGroup.getChildCount(); i++) {
            prepareViewHierarchyForScreenshot(viewGroup.getChildAt(i), takingScreenshot);
        }
    } else if (view instanceof SurfaceView) {
        view.setWillNotDraw(!takingScreenshot);
    }
}
 
Example 172
Project: SealBrowser   File: ApiCompatibilityUtils.java View source code 6 votes vote down vote up
/**
 * @see android.view.View#getPaddingStart()
 */
public static int getPaddingStart(View view) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return view.getPaddingStart();
    } else {
        // Before JB MR1, all layouts are left-to-right, so start == left.
        return view.getPaddingLeft();
    }
}
 
Example 173
Project: SealBrowser   File: ApiCompatibilityUtils.java View source code 6 votes vote down vote up
/**
 * @see android.view.View#getPaddingEnd()
 */
public static int getPaddingEnd(View view) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        return view.getPaddingEnd();
    } else {
        // Before JB MR1, all layouts are left-to-right, so end == right.
        return view.getPaddingRight();
    }
}
 
Example 174
Project: android-sdk-sources-for-api-level-23   File: ViewState.java View source code 6 votes vote down vote up
public void initFrom(View view) {
    alpha = view.getVisibility() == View.INVISIBLE ? 0.0f : view.getAlpha();
    yTranslation = view.getTranslationY();
    zTranslation = view.getTranslationZ();
    gone = view.getVisibility() == View.GONE;
    scale = view.getScaleX();
}
 
Example 175
Project: sdk-support   File: ViewCompatLollipop.java View source code 6 votes vote down vote up
public static WindowInsetsCompat dispatchApplyWindowInsets(View v, WindowInsetsCompat insets) {
    if (insets instanceof WindowInsetsCompatApi21) {
        // First unwrap the compat version so that we have the framework instance
        WindowInsets unwrapped = ((WindowInsetsCompatApi21) insets).unwrap();
        // Now call dispatchApplyWindowInsets
        WindowInsets result = v.dispatchApplyWindowInsets(unwrapped);

        if (result != unwrapped) {
            // ...and return a newly wrapped compat insets instance if different
            insets = new WindowInsetsCompatApi21(result);
        }
    }
    return insets;
}
 
Example 176
Project: notes   File: OCursorListAdapter.java View source code 6 votes vote down vote up
@Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
    View view;
    if (mCacheViews && getCachedView(cursor) != null) {
        view = getCachedView(cursor);
        if (!view.isDirty()) {
            return view;
        }
    }
    if (mOnViewCreateListener != null) {
        view = mOnViewCreateListener.onViewCreated(context, viewGroup,
                cursor, cursor.getPosition());
        if (view == null) {
            view = mInflater.inflate(mLayout, viewGroup, false);
        }
    } else
        view = mInflater.inflate(mLayout, viewGroup, false);
    if (mCacheViews) {
        mViewCache.put("view_" + cursor.getPosition(), view);
    }
    return view;
}
 
Example 177
Project: FasterGallery   File: MoviePlayer.java View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
private void showSystemUi(boolean visible) {
	if (!ApiHelper.HAS_VIEW_SYSTEM_UI_FLAG_LAYOUT_STABLE)
		return;

	int flag = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
			| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
			| View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
	if (!visible) {
		// We used the deprecated "STATUS_BAR_HIDDEN" for unbundling
		flag |= View.STATUS_BAR_HIDDEN | View.SYSTEM_UI_FLAG_FULLSCREEN
				| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
	}
	mVideoView.setSystemUiVisibility(flag);
}
 
Example 178
Project: SulfurKeyboard   File: ConverterActivity.java View source code 6 votes vote down vote up
@Override
public boolean onLongClick(View v) {
	if (!v.isEnabled()) return false;
	final CharSequence description = v.getContentDescription();
	if (TextUtils.isEmpty(description)) return false;
	
	final int[] screenPos = new int[2];
       final Rect displayFrame = new Rect();
       v.getLocationOnScreen(screenPos);
       v.getWindowVisibleDisplayFrame(displayFrame);

	final Context context = getContext();
       final int width = v.getWidth();
       final int height = v.getHeight();
       final int midy = screenPos[1] + height / 2;
       final int screenWidth = context.getResources().getDisplayMetrics().widthPixels;

       Toast cheatSheet = Toast.makeText(context, description, Toast.LENGTH_SHORT);
       if (midy < displayFrame.height()) {
           // Show along the top; follow action buttons
           cheatSheet.setGravity(Gravity.TOP | Gravity.RIGHT, screenWidth - screenPos[0] - width / 2, height);
       } else {
           // Show along the bottom center
           cheatSheet.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, height);
       }
       cheatSheet.show();
	return true;
}
 
Example 179
Project: DemoProject   File: Hover.java View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.hover);

    mMessageTextView = (TextView) findViewById(R.id.message);
    mInterceptCheckBox = (CheckBox) findViewById(R.id.intercept_checkbox);
    mInterceptor = (HoverInterceptorView) findViewById(R.id.interceptor);

    View container = findViewById(R.id.container);
    container.setOnHoverListener(new View.OnHoverListener() {
        @Override
        public boolean onHover(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_HOVER_ENTER:
                    mMessageTextView.setText(Hover.this.getResources().getString(
                            R.string.hover_message_entered_at,
                            event.getX(), event.getY()));
                    break;
                case MotionEvent.ACTION_HOVER_MOVE:
                    mMessageTextView.setText(Hover.this.getResources().getString(
                            R.string.hover_message_moved_at,
                            event.getX(), event.getY()));
                    break;
                case MotionEvent.ACTION_HOVER_EXIT:
                    mMessageTextView.setText(Hover.this.getResources().getString(
                            R.string.hover_message_exited_at,
                            event.getX(), event.getY()));
                    break;
            }
            return false;
        }
    });

    mInterceptCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mInterceptor.setInterceptHover(isChecked);
        }
    });
}
 
Example 180
Project: SealBrowser   File: AwLayoutSizer.java View source code 6 votes vote down vote up
/**
 * Calculate the size of the view.
 * This is designed to be used to implement the android.view.View#onMeasure() method.
 */
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);

    int contentHeightPix = (int) (mContentHeightCss * mPageScaleFactor * mDIPScale);
    int contentWidthPix = (int) (mContentWidthCss * mPageScaleFactor * mDIPScale);

    int measuredHeight = contentHeightPix;
    int measuredWidth = contentWidthPix;

    mLastMeasuredPageScaleFactor = mPageScaleFactor;

    // Always use the given size unless unspecified. This matches WebViewClassic behavior.
    mWidthMeasurementIsFixed = (widthMode != MeasureSpec.UNSPECIFIED);
    mHeightMeasurementIsFixed = (heightMode == MeasureSpec.EXACTLY);
    mHeightMeasurementLimited =
        (heightMode == MeasureSpec.AT_MOST) && (contentHeightPix > heightSize);
    mHeightMeasurementLimit = heightSize;

    if (mHeightMeasurementIsFixed || mHeightMeasurementLimited) {
        measuredHeight = heightSize;
    }

    if (mWidthMeasurementIsFixed) {
        measuredWidth = widthSize;
    }

    if (measuredHeight < contentHeightPix) {
        measuredHeight |= View.MEASURED_STATE_TOO_SMALL;
    }

    if (measuredWidth < contentWidthPix) {
        measuredWidth |= View.MEASURED_STATE_TOO_SMALL;
    }

    mDelegate.setMeasuredDimension(measuredWidth, measuredHeight);
}
 
Example 181
Project: SealBrowser   File: ApiCompatibilityUtils.java View source code 6 votes vote down vote up
/**
 * @see android.view.View#setPaddingRelative(int, int, int, int)
 */
public static void setPaddingRelative(View view, int start, int top, int end, int bottom) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        view.setPaddingRelative(start, top, end, bottom);
    } else {
        // Before JB MR1, all layouts are left-to-right, so start == left, etc.
        view.setPadding(start, top, end, bottom);
    }
}
 
Example 182
Project: AcDisplay   File: ViewUtils.java View source code 6 votes vote down vote up
/**
 * Recursive helper method that applies transformations in post-order.
 *
 * @param ev the on-screen motion event
 */
private static void transformMotionEventToLocal(@NonNull View view, @NonNull MotionEvent ev) {
    final ViewParent parent = view.getParent();
    if (parent instanceof View) {
        final View vp = (View) parent;
        transformMotionEventToLocal(vp, ev);
        ev.offsetLocation(vp.getScrollX(), vp.getScrollY());
    }
    // TODO: Use reflections to access ViewRootImpl
    // else if (parent instanceof ViewRootImpl) {
    //    final ViewRootImpl vr = (ViewRootImpl) parent;
    //    ev.offsetLocation(0, vr.mCurScrollY);
    // }

    ev.offsetLocation(-view.getLeft(), -view.getTop());

    Matrix matrix = view.getMatrix();
    if (matrix != null) {
        ev.transform(matrix);
    }
}
 
Example 183
Project: vlc-android-macbuild   File: SystemUIHelper.java View source code 6 votes vote down vote up
@TargetApi(16)
public static void requestFitSysWindow(View view) {
    if (view == null)
        return;

    if (BuildHelper.isApi16_JellyBeanOrLater()) {
        view.requestFitSystemWindows();
    }
}
 
Example 184
Project: property-db   File: ContextMenuBuilder.java View source code 6 votes vote down vote up
/**
 * Shows this context menu, allowing the optional original view (and its
 * ancestors) to add items.
 * 
 * @param originalView Optional, the original view that triggered the
 *        context menu.
 * @param token Optional, the window token that should be set on the context
 *        menu's window.
 * @return If the context menu was shown, the [email protected] MenuDialogHelper} for
 *         dismissing it. Otherwise, null.
 */
public MenuDialogHelper show(View originalView, IBinder token) {
    if (originalView != null) {
        // Let relevant views and their populate context listeners populate
        // the context menu
        originalView.createContextMenu(this);
    }

    if (getVisibleItems().size() > 0) {
        EventLog.writeEvent(50001, 1);
        
        MenuDialogHelper helper = new MenuDialogHelper(this); 
        helper.show(token);
        
        return helper;
    }
    
    return null;
}
 
Example 185
Project: property-db   File: WindowManagerService.java View source code 6 votes vote down vote up
void updateStatusBarVisibilityLocked(int visibility) {
    mInputManager.setSystemUiVisibility(visibility);
    final WindowList windows = getDefaultWindowListLocked();
    final int N = windows.size();
    for (int i = 0; i < N; i++) {
        WindowState ws = windows.get(i);
        try {
            int curValue = ws.mSystemUiVisibility;
            int diff = curValue ^ visibility;
            // We are only interested in differences of one of the
            // clearable flags...
            diff &= View.SYSTEM_UI_CLEARABLE_FLAGS;
            // ...if it has actually been cleared.
            diff &= ~visibility;
            int newValue = (curValue&~diff) | (visibility&diff);
            if (newValue != curValue) {
                ws.mSeq++;
                ws.mSystemUiVisibility = newValue;
            }
            if (newValue != curValue || ws.mAttrs.hasSystemUiListeners) {
                ws.mClient.dispatchSystemUiVisibilityChanged(ws.mSeq,
                        visibility, newValue, diff);
            }
        } catch (RemoteException e) {
            // so sorry
        }
    }
}
 
Example 186
Project: property-db   File: WebViewClassic.java View source code 6 votes vote down vote up
@Override
public void setScrollBarStyle(int style) {
    if (style == View.SCROLLBARS_INSIDE_INSET
            || style == View.SCROLLBARS_OUTSIDE_INSET) {
        mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = false;
    } else {
        mOverlayHorizontalScrollbar = mOverlayVerticalScrollbar = true;
    }
}
 
Example 187
Project: property-db   File: AccessibilityRecord.java View source code 6 votes vote down vote up
/**
 * Sets the source to be a virtual descendant of the given <code>root</code>.
 * If <code>virtualDescendantId</code> equals to [email protected] View#NO_ID} the root
 * is set as the source.
 * <p>
 * A virtual descendant is an imaginary View that is reported as a part of the view
 * hierarchy for accessibility purposes. This enables custom views that draw complex
 * content to report them selves as a tree of virtual views, thus conveying their
 * logical structure.
 * </p>
 *
 * @param root The root of the virtual subtree.
 * @param virtualDescendantId The id of the virtual descendant.
 */
public void setSource(View root, int virtualDescendantId) {
    enforceNotSealed();
    final boolean important;
    if (virtualDescendantId == UNDEFINED) {
        important = (root != null) ? root.isImportantForAccessibility() : true;
    } else {
        important = true;
    }
    setBooleanProperty(PROPERTY_IMPORTANT_FOR_ACCESSIBILITY, important);
    mSourceWindowId = (root != null) ? root.getAccessibilityWindowId() : UNDEFINED;
    final int rootViewId = (root != null) ? root.getAccessibilityViewId() : UNDEFINED;
    mSourceNodeId = AccessibilityNodeInfo.makeNodeId(rootViewId, virtualDescendantId);
}
 
Example 188
Project: RoughCut   File: MediaItemView.java View source code 6 votes vote down vote up
public MediaItemView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    // Initialize static data
    if (sAddTransitionDrawable == null) {
        sAddTransitionDrawable = getResources().getDrawable(
                R.drawable.add_transition_selector);
        sEmptyFrameDrawable = getResources().getDrawable(
                R.drawable.timeline_loading);

        // Initialize the thumbnail cache, limit the memory usage to 3MB
        sThumbnailCache = new ThumbnailCache(3*1024*1024);
    }

    // Get the screen width
    final Display display = ((WindowManager)context.getSystemService(
            Context.WINDOW_SERVICE)).getDefaultDisplay();
    final DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    mScreenWidth = metrics.widthPixels;

    // Setup our gesture detector and scroll listener
    mGestureDetector = new GestureDetector(context, new MyGestureListener());
    mScrollListener = new MyScrollViewListener();

    // Prepare the progress bar rectangles
    final ProgressBar progressBar = ProgressBar.getProgressBar(context);
    final int layoutHeight = (int)(
            getResources().getDimension(R.dimen.media_layout_height) -
            getResources().getDimension(R.dimen.media_layout_padding));
    mGeneratingEffectProgressDestRect = new Rect(getPaddingLeft(),
            layoutHeight - progressBar.getHeight() - getPaddingBottom(), 0,
            layoutHeight - getPaddingBottom());

    // Initialize the progress value
    mGeneratingEffectProgress = -1;

    // Initialize the "Add transition" indicators state
    mLeftState = View.EMPTY_STATE_SET;
    mRightState = View.EMPTY_STATE_SET;

    // Initialize the thumbnail indices we want to request
    mWantThumbnails = new ArrayList<Integer>();

    // Initialize the set of indices we are waiting
    mPending = new HashSet<Integer>();

    // Initialize the generation number
    mGeneration = sGenerationCounter++;
}
 
Example 189
Project: Light-Controller   File: ShapeWear.java View source code 6 votes vote down vote up
/**
 * Initialized to determine screen shape
 * @param view
 */
private static void initShapeDetection(View view){
    view.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
        @Override
        public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
            if (insets.isRound()) {
                shape = ScreenShape.ROUND;
                if(screenWidthPX == 320 && screenHeightPX == 290) {
                    shape = ScreenShape.MOTO_ROUND;
                }
            } else {
                shape = ScreenShape.RECTANGLE;
            }
            if(onShapeChangeListener != null){
                onShapeChangeListener.shapeDetected(getShape());
            }
            return insets;
        }
    });
}
 
Example 190
Project: property-db   File: KeyguardViewManager.java View source code 6 votes vote down vote up
/**
 * Show the keyguard.  Will handle creating and attaching to the view manager
 * lazily.
 */
public synchronized void show(Bundle options) {
    if (DEBUG) Log.d(TAG, "show(); mKeyguardView==" + mKeyguardView);

    boolean enableScreenRotation = shouldEnableScreenRotation();

    maybeCreateKeyguardLocked(enableScreenRotation, false, options);
    maybeEnableScreenRotation(enableScreenRotation);

    // Disable common aspects of the system/status/navigation bars that are not appropriate or
    // useful on any keyguard screen but can be re-shown by dialogs or SHOW_WHEN_LOCKED
    // activities. Other disabled bits are handled by the KeyguardViewMediator talking
    // directly to the status bar service.
    final int visFlags = View.STATUS_BAR_DISABLE_HOME;
    if (DEBUG) Log.v(TAG, "show:setSystemUiVisibility(" + Integer.toHexString(visFlags)+")");
    mKeyguardHost.setSystemUiVisibility(visFlags);

    mViewManager.updateViewLayout(mKeyguardHost, mWindowLayoutParams);
    mKeyguardHost.setVisibility(View.VISIBLE);
    mKeyguardView.show();
    mKeyguardView.requestFocus();
}
 
Example 191
Project: framework-master   File: ScaleController.java View source code 6 votes vote down vote up
@SuppressLint("NewApi")
private final int getMinimumWidth(View view) {
    if (Build.VERSION.SDK_INT < 16) {
        return this.reflectMinWH(view, "mMinWidth");
    } else {
        return view.getMinimumWidth();
    }
}
 
Example 192
Project: WearViewStub   File: ShapeWear.java View source code 6 votes vote down vote up
/**
 * Initialized to determine screen shape
 * @param view
 */
private static void initShapeDetection(View view){
    if(!setOnApplyWindowInsetsListenerCalled) {
        setOnApplyWindowInsetsListenerCalled = true;
        view.setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
            @Override
                public WindowInsets onApplyWindowInsets(View v, WindowInsets insets) {
                if (insets.isRound()) {
                    shape = ScreenShape.ROUND;
                    if (screenWidthPX == 320 && screenHeightPX == 290) {
                        shape = ScreenShape.MOTO_ROUND;
                    }
                } else {
                    shape = ScreenShape.RECTANGLE;
                }
                if (onShapeChangeListeners != null && !onShapeChangeListeners.isEmpty()) {
                    synchronized (onShapeChangeListeners) {
                        for (OnShapeChangeListener listener : onShapeChangeListeners)
                            listener.shapeDetected(getShape());
                    }
                }
                return insets;
            }
        });
        view.requestApplyInsets();
    }
}
 
Example 193
Project: XieDaDeng   File: PhoneStatusBar.java View source code 6 votes vote down vote up
@Override
protected void showRecents(boolean triggeredFromAltTab) {
    // Set the recents visibility flag
    mSystemUiVisibility |= View.RECENT_APPS_VISIBLE;
    notifyUiVisibilityChanged(mSystemUiVisibility);
    super.showRecents(triggeredFromAltTab);
}
 
Example 194
Project: js-android-app   File: ScrollToItemAction.java View source code 6 votes vote down vote up
@Override
public void perform(UiController uiController, View view) {
    if (isDisplayingAtLeast(90).matches(view)) {
        Log.i(TAG, "View is already displayed. Returning.");
        return;
    }
    Rect rect = new Rect();
    view.getDrawingRect(rect);
    if (!view.requestRectangleOnScreen(rect, true /* immediate */)) {
        Log.w(TAG, "Scrolling to view was requested, but none of the parents scrolled.");
    }
    uiController.loopMainThreadUntilIdle();
    if (!isDisplayingAtLeast(90).matches(view)) {
        throw new PerformException.Builder()
                .withActionDescription(this.getDescription())
                .withViewDescription(HumanReadables.describe(view))
                .withCause(new RuntimeException(
                        "Scrolling to view was attempted, but the view is not displayed"))
                .build();
    }
}
 
Example 195
Project: DemoProject   File: ScrollBar3.java View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.scrollbar3);
    
    findViewById(R.id.view3).setScrollBarStyle(View.SCROLLBARS_INSIDE_INSET);
}
 
Example 196
Project: framework-master   File: ScaleController.java View source code 6 votes vote down vote up
@SuppressLint("NewApi")
private final int getMinimumHeight(View view) {
    if (Build.VERSION.SDK_INT < 16) {
        return this.reflectMinWH(view, "mMinHeight");
    } else {
        return view.getMinimumHeight();
    }
}
 
Example 197
Project: android-sdk-sources-for-api-level-23   File: ActivityTransitionCoordinator.java View source code 6 votes vote down vote up
private static SharedElementOriginalState getOldSharedElementState(View view, String name,
        Bundle transitionArgs) {

    SharedElementOriginalState state = new SharedElementOriginalState();
    state.mLeft = view.getLeft();
    state.mTop = view.getTop();
    state.mRight = view.getRight();
    state.mBottom = view.getBottom();
    state.mMeasuredWidth = view.getMeasuredWidth();
    state.mMeasuredHeight = view.getMeasuredHeight();
    state.mTranslationZ = view.getTranslationZ();
    state.mElevation = view.getElevation();
    if (!(view instanceof ImageView)) {
        return state;
    }
    Bundle bundle = transitionArgs.getBundle(name);
    if (bundle == null) {
        return state;
    }
    int scaleTypeInt = bundle.getInt(KEY_SCALE_TYPE, -1);
    if (scaleTypeInt < 0) {
        return state;
    }

    ImageView imageView = (ImageView) view;
    state.mScaleType = imageView.getScaleType();
    if (state.mScaleType == ImageView.ScaleType.MATRIX) {
        state.mMatrix = new Matrix(imageView.getImageMatrix());
    }
    return state;
}
 
Example 198
Project: BioWiki   File: MediaItemFragment.java View source code 5 votes vote down vote up
private void refreshViews(Cursor cursor) {
    if (!cursor.moveToFirst())
        return;

    // check whether or not to show the edit button
    String state = cursor.getString(cursor.getColumnIndex("uploadState"));
    mIsLocal = MediaUtils.isLocalFile(state);
    if (mIsLocal)
        getSherlockActivity().invalidateOptionsMenu();

    // title
    mTitleView.setText(cursor.getString(cursor.getColumnIndex("title")));

    // caption
    String caption = cursor.getString(cursor.getColumnIndex("caption"));
    if (caption == null || caption.length() == 0) {
        mCaptionView.setVisibility(View.GONE);
    } else {
        mCaptionView.setText(caption);
        mCaptionView.setVisibility(View.VISIBLE);
    }

    // description
    String desc = cursor.getString(cursor.getColumnIndex("description"));
    if (desc == null || desc.length() == 0) {
        mDescriptionView.setVisibility(View.GONE);
    } else {
        mDescriptionView.setText(desc);
        mDescriptionView.setVisibility(View.VISIBLE);
    }

    // added / upload date
    String date = MediaUtils.getDate(cursor.getLong(cursor.getColumnIndex("date_created_gmt")));
    if (mIsLocal) {
        mDateView.setText("Added on: " + date);
    } else {
        mDateView.setText("Uploaded on: " + date);
    }

    // file name
    String fileName = cursor.getString(cursor.getColumnIndex("fileName"));
    mFileNameView.setText("File name: " + fileName);

    // get the file extension from the fileURL
    String fileURL = cursor.getString(cursor.getColumnIndex("fileURL"));
    if (fileURL != null) {
        String fileType = fileURL.replaceAll(".*\\.(\\w+)$", "$1").toUpperCase();
        mFileTypeView.setText("File type: " + fileType);
        mFileTypeView.setVisibility(View.VISIBLE);
    } else {
        mFileTypeView.setVisibility(View.GONE);
    }

    String imageUri = cursor.getString(cursor.getColumnIndex("fileURL"));
    if (imageUri == null)
        imageUri = cursor.getString(cursor.getColumnIndex("filePath"));

    inflateImageView();

    // image and dimensions
    if (MediaUtils.isValidImage(imageUri)) {

        int width = cursor.getInt(cursor.getColumnIndex("width"));
        int height = cursor.getInt(cursor.getColumnIndex("height"));

        float screenWidth;

        View parentView = (View) mImageView.getParent();

        //differentiating between tablet and phone
        if (this.isInLayout()) {
            screenWidth = parentView.getMeasuredWidth();
        } else {
            screenWidth = getActivity().getResources().getDisplayMetrics().widthPixels;
        }
        float screenHeight = getActivity().getResources().getDisplayMetrics().heightPixels;

        if (width > 0 && height > 0) {
            String dimensions = width + "x" + height;
            mDimensionsView.setText("Dimensions: " + dimensions);
            mDimensionsView.setVisibility(View.VISIBLE);
        } else {
            mDimensionsView.setVisibility(View.GONE);
        }

        if (width > screenWidth) {
            height = (int) (height / (width / screenWidth));
            width = (int) screenWidth;
        } else if (height > screenHeight) {
            width = (int) (width / (height / screenHeight));
            height = (int) screenHeight;
        }

        if (mIsLocal) {
            final String filePath = cursor.getString(cursor.getColumnIndex("filePath"));
            loadLocalImage(mImageView, filePath, width, height);
        } else {
            // Allow non-private wp.com and Jetpack blogs to use photon to get a higher res thumbnail
            if (BioWiki.getCurrentBlog() != null && BioWiki.getCurrentBlog().isPhotonCapable()) {
                String thumbnailURL = StringUtils.getPhotonUrl(imageUri, (int) screenWidth);
                ((NetworkImageView) mImageView).setImageUrl(thumbnailURL, mImageLoader);
            } else {
                ((NetworkImageView) mImageView).setImageUrl(imageUri + "?w=" + screenWidth, mImageLoader);
            }
        }
        mImageView.setVisibility(View.VISIBLE);

        mImageView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, height));

    } else {
        mImageView.setVisibility(View.GONE);
        mDimensionsView.setVisibility(View.GONE);
    }
}
 
Example 199
Project: BioWiki   File: SwipeDismissListViewTouchListener.java View source code 5 votes vote down vote up
private boolean handleDownEvent(final MotionEvent motionEvent) {
    // Find the child view that was touched (perform a hit test)
    Rect rect = new Rect();
    int childCount = mListView.getChildCount();
    int[] listViewCoords = new int[2];
    mListView.getLocationOnScreen(listViewCoords);
    int x = (int) motionEvent.getRawX() - listViewCoords[0];
    int y = (int) motionEvent.getRawY() - listViewCoords[1];
    View downView = null;
    for (int i = 0; i < childCount && downView == null; i++) {
        View child = mListView.getChildAt(i);
        child.getHitRect(rect);
        if (rect.contains(x, y)) {
            downView = child;
        }
    }

    if (downView != null) {
        mDownX = motionEvent.getRawX();
        mDownY = motionEvent.getRawY();
        int downPosition = AdapterViewUtil.getPositionForView(mListView, downView);

        if (mDismissableManager != null) {
            long downId = mListView.getAdapter().getItemId(downPosition);
            if (!mDismissableManager.isDismissable(downId, downPosition)) {
                /* Cancel, not dismissable */
                return false;
            }
        }

        mCurrentDismissData = createPendingDismissData(downPosition, downView);

        if (mPendingDismisses.contains(mCurrentDismissData) || downPosition >= mVirtualListCount) {
            // Cancel, we're already processing this position
            mCurrentDismissData = null;
            return false;
        } else {
            mTouchChildTouched = !mIsParentHorizontalScrollContainer && mResIdOfTouchChild == 0;

            if (mResIdOfTouchChild != 0) {
                mIsParentHorizontalScrollContainer = false;

                final View childView = downView.findViewById(mResIdOfTouchChild);
                if (childView != null) {
                    final Rect childRect = getChildViewRect(mListView, childView);
                    if (childRect.contains((int) motionEvent.getX(), (int) motionEvent.getY())) {
                        mTouchChildTouched = true;
                        mListView.requestDisallowInterceptTouchEvent(true);
                    }
                }
            }

            if (mIsParentHorizontalScrollContainer) {
                // Do it now and don't wait until the user moves more than
                // the slop factor.
                mTouchChildTouched = true;
                mListView.requestDisallowInterceptTouchEvent(true);
            }

            mVelocityTracker = VelocityTracker.obtain();
            mVelocityTracker.addMovement(motionEvent);
        }
    }
    return true;
}
 
Example 200
Project: android_packages_apps_AeroControl   File: StatisticAdapter.java View source code 5 votes vote down vote up
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    Holder holder;

    if (mIndex == color_code.length)
        mIndex = 0;

    if (row == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(mLayoutResourceId, parent, false);

        holder = new Holder();
        holder.frequency = (TextView) row.findViewById(R.id.frequency);
        holder.timeInState = (TextView) row.findViewById(R.id.timeInState);
        holder.percentage = (TextView) row.findViewById((R.id.percentage));

        holder.frequency.setTypeface(mFont);
        holder.timeInState.setTypeface(mFont);
        holder.percentage.setTypeface(mFont);

        holder.frequency.setTextColor(Color.parseColor(color_code[mIndex]));
        holder.timeInState.setTextColor(Color.parseColor(color_code[mIndex]));
        holder.percentage.setTextColor(Color.parseColor(color_code[mIndex]));

        mIndex++;

        row.setTag(holder);
    } else {
        holder = (Holder) row.getTag();
    }

    final statisticInit overview = mData.get(position);
    if(overview == null)
        return row;

    if (mData != null) {

        if(overview.mFrequency != null)
            holder.frequency.setText(overview.mFrequency);

        if(overview.mTimeInState != null)
            holder.timeInState.setText(overview.mTimeInState);

        if(overview.mPercentage != null)
            holder.percentage.setText(overview.mPercentage);

        if (mTags[position] != null) {
            holder.frequency.setTextColor(Color.parseColor(mTags[position]));
            holder.timeInState.setTextColor(Color.parseColor(mTags[position]));
            holder.percentage.setTextColor(Color.parseColor(mTags[position]));
        }

    } else {
        Log.e("Aero",
                "No Data found for adapter.");
    }

    if (!mIsVisible[position]) {
        /* Small animation effect */
        int delay = (position * 50);
        Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.bottom_up);
        animation.setStartOffset(delay);
        row.setAnimation(animation);
        mIsVisible[position] = true;
    }

    return row;
}
 
Example 201
Project: Gui2Go   File: EditorActivity.java View source code 5 votes vote down vote up
public View createNewWidget(View parent, String viewType,
                boolean isCalledFromXmlLoader, boolean isEditable,
                boolean isNewLayoutRoot, boolean shouldReport) {
    // event listeners
    OnClickListener mClickListener = new HightlightViewClickListener();
    OnDragListener mDragListen = new LayoutDragListener();

    View newWidget = null;
    String tag = "";

    if (viewType.equals(WidgetTypes.BUTTON_TAG)) {
        newWidget = createNewButton();
    } else if (viewType.equals(WidgetTypes.CHECKBOX_TAG)) {
        newWidget = createNewCheckbox();
    } else if (viewType.equals(WidgetTypes.TEXTVIEW_TAG)) {
        newWidget = createNewTextView();
    } else if (viewType.equals(WidgetTypes.IMAGEVIEW_TAG)) {
        newWidget = createNewImageView();
    } else if (viewType.equals(WidgetTypes.EDITTEXT_TAG)) {
        newWidget = createNewEditText();
    } else if (viewType.equals(WidgetTypes.RADIOBUTTON_TAG)) {
        newWidget = createNewRadioButton();
    } else if (viewType.equals(WidgetTypes.SPINNER_TAG)) {
        newWidget = createNewSpinner();
    } else if (viewType.equals(WidgetTypes.TOGGLEBUTTON_TAG)) {
        newWidget = createNewToggleButton();
    } else if (viewType.equals(WidgetTypes.LINEAR_TAG)) {
        newWidget = createNewLinearLayout(isCalledFromXmlLoader);
    } else if (viewType.equals(WidgetTypes.RELATIVE_TAG)) {
        newWidget = createNewRelativeLayout();
    } else if (viewType.equals(WidgetTypes.FRAME_TAG)) {
        newWidget = createNewFrameLayout();
    } else if (viewType.equals(WidgetTypes.TABLE_TAG)) {
        newWidget = createNewTableLayout();
    } else if (viewType.equals(WidgetTypes.LISTVIEW_TAG)) {
        newWidget = createNewListView();
    } else if (viewType.equals(WidgetTypes.RADIOGROUP_TAG)) {
        newWidget = createNewRadioGroup();
    } else if (viewType.equals(WidgetTypes.GRIDVIEW_TAG)) {
        newWidget = createNewGridView();
    } else if (viewType.equals(WidgetTypes.TABLEROW_TAG)) {
        newWidget = createNewTableRow();
    } else {
        Toast.makeText(this, "Unknown Widget Type", Toast.LENGTH_LONG)
                        .show();
    }

    if (newWidget != null) {
        // widget properties

        if (isEditable) {
            if (isListView(newWidget) || isSpinner(newWidget)
                            || newWidget.getClass() == GridView.class) {
                // these will be selectable only from the tree
            } else {
                newWidget.setOnClickListener(mClickListener);
                registerForContextMenu(newWidget);
            }

        }

        // if its a layout, need to make it listen to drag events and be
        // same size as parent
        if (isLayout(newWidget)) {
            // if its a layout we generate a layout name
            newWidget.setOnDragListener(mDragListen);
            LayoutParams params = new LayoutParams(
                            LayoutParams.MATCH_PARENT,
                            LayoutParams.MATCH_PARENT);
            newWidget.setLayoutParams(params);

            if (isNewLayoutRoot) { // if its a new LayoutRoot we have to
                // name it properly
                newWidget.setTag("LayoutRoot");
            } else {
                tag = GenerateLayoutName();
                newWidget.setTag(tag);
            }
        } else {
            tag = GenerateWidgetName();
            newWidget.setTag(tag);
        }

        int id = GenerateWidgetID();
        newWidget.setId(id);
        // add it to the view parent
        ((ViewGroup) parent).addView(newWidget);
        if (shouldReport) {
            // no need to report every widget if we create them from the XML
            // loader
            ReportWidgetAdded(newWidget.getClass().getSimpleName(), false,
                            tag);
        }
        if (parent.getClass() == RelativeLayout.class
                        && !parent.getTag().toString()
                                        .equals("MAIN_CANVAS")
                        && !isCalledFromXmlLoader) {
            // only call the relative layout dialog if its parent is a
            // relative layout
            // and its not called from the XML loader
            ChangeWidgetLayoutParams(newWidget,
                            RetrieveLayoutStates(newWidget));
        }
        // add it to the widget tree and refresh the TreeView
        if (parent.getTag().toString().equals("MAIN_CANVAS")) {
            manager.addAfterChild(null, (long) newWidget.getId(), null);
        } else {
            manager.addAfterChild((long) parent.getId(),
                            (long) newWidget.getId(), null);
        }

        simpleAdapter.refresh();

        return newWidget;
    }
    return null;
}
 
Example 202
Project: ExcusePro   File: IcsSpinner.java View source code 5 votes vote down vote up
/**
 * Creates and positions all views for this Spinner.
 *
 * @param delta Change in the selected position. +1 moves selection is moving to the right,
 * so views are scrolling to the left. -1 means selection is moving to the left.
 */
@Override
void layout(int delta, boolean animate) {
    int childrenLeft = mSpinnerPadding.left;
    int childrenWidth = getRight() - getLeft() - mSpinnerPadding.left - mSpinnerPadding.right;

    if (mDataChanged) {
        handleDataChanged();
    }

    // Handle the empty set by removing all views
    if (mItemCount == 0) {
        resetList();
        return;
    }

    if (mNextSelectedPosition >= 0) {
        setSelectedPositionInt(mNextSelectedPosition);
    }

    recycleAllViews();

    // Clear out old views
    removeAllViewsInLayout();

    // Make selected view and position it
    mFirstPosition = mSelectedPosition;
    View sel = makeAndAddView(mSelectedPosition);
    int width = sel.getMeasuredWidth();
    int selectedOffset = childrenLeft;
    switch (mGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
        case Gravity.CENTER_HORIZONTAL:
            selectedOffset = childrenLeft + (childrenWidth / 2) - (width / 2);
            break;
        case Gravity.RIGHT:
            selectedOffset = childrenLeft + childrenWidth - width;
            break;
    }
    sel.offsetLeftAndRight(selectedOffset);

    // Flush any cached views that did not get reused above
    mRecycler.clear();

    invalidate();

    checkSelectionChanged();

    mDataChanged = false;
    mNeedSync = false;
    setNextSelectedPositionInt(mSelectedPosition);
}
 
Example 203
Project: ExcusePro   File: ActionBarContainer.java View source code 5 votes vote down vote up
@Override
public void onLayout(boolean changed, int l, int t, int r, int b) {
    super.onLayout(changed, l, t, r, b);

    final boolean hasTabs = mTabContainer != null && mTabContainer.getVisibility() != GONE;

    if (mTabContainer != null && mTabContainer.getVisibility() != GONE) {
        final int containerHeight = getMeasuredHeight();
        final int tabHeight = mTabContainer.getMeasuredHeight();

        if ((mActionBarView.getDisplayOptions() & ActionBar.DISPLAY_SHOW_HOME) == 0) {
            // Not showing home, put tabs on top.
            final int count = getChildCount();
            for (int i = 0; i < count; i++) {
                final View child = getChildAt(i);

                if (child == mTabContainer) continue;

                if (!mActionBarView.isCollapsed()) {
                    child.offsetTopAndBottom(tabHeight);
                }
            }
            mTabContainer.layout(l, 0, r, tabHeight);
        } else {
            mTabContainer.layout(l, containerHeight - tabHeight, r, containerHeight);
        }
    }

    boolean needsInvalidate = false;
    if (mIsSplit) {
        if (mSplitBackground != null) {
            mSplitBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
            needsInvalidate = true;
        }
    } else {
        if (mBackground != null) {
            mBackground.setBounds(mActionBarView.getLeft(), mActionBarView.getTop(),
                    mActionBarView.getRight(), mActionBarView.getBottom());
            needsInvalidate = true;
        }
        if ((mIsStacked = hasTabs && mStackedBackground != null)) {
            mStackedBackground.setBounds(mTabContainer.getLeft(), mTabContainer.getTop(),
                    mTabContainer.getRight(), mTabContainer.getBottom());
            needsInvalidate = true;
        }
    }

    if (needsInvalidate) {
        invalidate();
    }
}
 
Example 204
Project: ExcusePro   File: IcsListPopupWindow.java View source code 5 votes vote down vote up
private int measureHeightOfChildren(int widthMeasureSpec, int startPosition, int endPosition,
        final int maxHeight, int disallowPartialChildPosition) {

    final ListAdapter adapter = mAdapter;
    if (adapter == null) {
        return mDropDownList.getListPaddingTop() + mDropDownList.getListPaddingBottom();
    }

    // Include the padding of the list
    int returnedHeight = mDropDownList.getListPaddingTop() + mDropDownList.getListPaddingBottom();
    final int dividerHeight = ((mDropDownList.getDividerHeight() > 0) && mDropDownList.getDivider() != null) ? mDropDownList.getDividerHeight() : 0;
    // The previous height value that was less than maxHeight and contained
    // no partial children
    int prevHeightWithoutPartialChild = 0;
    int i;
    View child;

    // mItemCount - 1 since endPosition parameter is inclusive
    endPosition = (endPosition == -1/*NO_POSITION*/) ? adapter.getCount() - 1 : endPosition;

    for (i = startPosition; i <= endPosition; ++i) {
        child = mAdapter.getView(i, null, mDropDownList);
        if (mDropDownList.getCacheColorHint() != 0) {
            child.setDrawingCacheBackgroundColor(mDropDownList.getCacheColorHint());
        }

        measureScrapChild(child, i, widthMeasureSpec);

        if (i > 0) {
            // Count the divider for all but one child
            returnedHeight += dividerHeight;
        }

        returnedHeight += child.getMeasuredHeight();

        if (returnedHeight >= maxHeight) {
            // We went over, figure out which height to return.  If returnedHeight > maxHeight,
            // then the i'th position did not fit completely.
            return (disallowPartialChildPosition >= 0) // Disallowing is enabled (> -1)
                        && (i > disallowPartialChildPosition) // We've past the min pos
                        && (prevHeightWithoutPartialChild > 0) // We have a prev height
                        && (returnedHeight != maxHeight) // i'th child did not fit completely
                    ? prevHeightWithoutPartialChild
                    : maxHeight;
        }

        if ((disallowPartialChildPosition >= 0) && (i >= disallowPartialChildPosition)) {
            prevHeightWithoutPartialChild = returnedHeight;
        }
    }

    // At this point, we went through the range of children, and they each
    // completely fit, so return the returnedHeight
    return returnedHeight;
}
 
Example 205
Project: cardslib   File: CardView.java View source code 5 votes vote down vote up
/**
 * Add ClickListener to expand and collapse hidden view
 */
protected void setupExpandCollapseActionListener() {
    if (mInternalExpandLayout != null) {
        mInternalExpandLayout.setVisibility(View.GONE);

        boolean internal_blockForLongClickOnImageButtonExpand = false;
        ViewToClickToExpand viewToClickToExpand = null;

        //ButtonExpandVisible has a priority to viewClickToExpand
        if (mCardHeader != null && mCardHeader.isButtonExpandVisible()) {

            viewToClickToExpand = ViewToClickToExpand.builder()
                    .setupView(mInternalHeaderLayout.getImageButtonExpand())
                    .highlightView(true);
            internal_blockForLongClickOnImageButtonExpand = true;

        } else if (mCard.getViewToClickToExpand() != null) {

            viewToClickToExpand = mCard.getViewToClickToExpand();
        }

        if (viewToClickToExpand != null) {

            TitleViewOnClickListener titleViewOnClickListener = new TitleViewOnClickListener(mInternalExpandLayout, mCard, viewToClickToExpand.isViewToSelect());

            /*if (mCardHeader!=null && mCardHeader.isButtonExpandVisible() && mInternalHeaderLayout != null) {
                mInternalHeaderLayout.setOnClickExpandCollapseActionListener(titleViewOnClickListener);
            }*/

            View viewToClick = viewToClickToExpand.getViewToClick();
            if (viewToClick != null) {

                if (internal_blockForLongClickOnImageButtonExpand) {
                    //The long click on Header button is now allowed
                    viewToClick.setOnClickListener(titleViewOnClickListener);
                }else{
                    if (viewToClickToExpand.isUseLongClick()){
                        viewToClick.setOnLongClickListener(new TitleViewOnLongClickListener(titleViewOnClickListener));
                    }else{
                        viewToClick.setOnClickListener(titleViewOnClickListener);
                    }
                }
            }else{
                ViewToClickToExpand.CardElementUI cardElementUI=viewToClickToExpand.getCardElementUIToClick();
                if (cardElementUI!=null){
                    switch (cardElementUI){
                        case CARD:
                            viewToClick = this;
                            break;
                        case HEADER:
                            viewToClick = getInternalHeaderLayout();
                            break;
                        case THUMBNAIL:
                            viewToClick = getInternalThumbnailLayout();
                            break;
                        case MAIN_CONTENT:
                            viewToClick = getInternalContentLayout();
                            break;
                    }
                    if (viewToClick != null) {
                        if (viewToClickToExpand.isUseLongClick()){
                            viewToClick.setOnLongClickListener(new TitleViewOnLongClickListener(titleViewOnClickListener));
                        }else{
                            viewToClick.setOnClickListener(titleViewOnClickListener);
                        }
                    }
                }
            }

            if (isExpanded()) {
                //Make layout visible and button selected
                mInternalExpandLayout.setVisibility(View.VISIBLE);
                if (viewToClick != null) {
                    if (viewToClickToExpand.isViewToSelect())
                        viewToClick.setSelected(true);
                }
            } else {
                //Make layout hidden and button not selected
                mInternalExpandLayout.setVisibility(View.GONE);
                if (viewToClick != null) {
                    if (viewToClickToExpand.isViewToSelect())
                        viewToClick.setSelected(false);
                }
            }
        }

    }
}
 
Example 206
Project: Gui2Go   File: EditorActivity.java View source code 5 votes vote down vote up
public void btnClick_widgetUp(View v) {
    // this is an ugly solution due to API lacking something to change Z
    // order
    // IMPORTANT: bring to front actually puts them in the bottom
    if (currentHighlightedID != 0) {
        View target = findViewById(currentHighlightedID);
        ViewGroup parent = (ViewGroup) target.getParent();
        int position = parent.indexOfChild(target);

        LinkedList<View> viewsToFront = new LinkedList<View>();
        if (position != 0) {
            // do it in the tree
            for (int i = 0; i < treeView.getCount(); i++) {
                View viewFromTree = (View) treeView.getChildAt(i);
                if (viewFromTree != null) {
                    String treeViewTag = viewFromTree.getTag().toString();

                    if (treeViewTag.equals(String.valueOf(target.getId()))) {
                        // before moving we should save all its children
                        List<Long> children = manager
                                        .getChildren((long) target.getId());

                        manager.removeNodeRecursively((long) target.getId());
                        insertViewToTreeParentAfterTarget(target, parent,
                                        parent.getChildAt(position - 1));
                        if (children != null) {
                            // re-add all its children
                            for (int j = 0; j < children.size(); j++) {
                                View tempView = ((ViewGroup) target)
                                                .getChildAt(j);
                                manager.addAfterChild(
                                                (long) target.getId(),
                                                (long) tempView.getId(),
                                                null);
                            }
                        }
                    }
                }
            }

            // for (int i = 0; i < treeView.getCount(); i++) { // all this
            // to
            // // find the new
            // // tree view and
            // // highlight it
            // View viewFromTree = (View) treeView.getChildAt(i);
            // if (viewFromTree != null) {
            // String treeViewTag = viewFromTree.getTag().toString();
            // if (treeViewTag.equals(String.valueOf(target.getId()))) {
            // viewFromTree
            // .setBackgroundResource(R.drawable.hightlight_border);
            // }
            // }
            // }

            viewsToFront.add(parent.getChildAt(position - 1));
            for (int i = position + 1; i < parent.getChildCount(); i++) {
                // store the views we need to bring up after
                // up until the position of 2 before the target
                viewsToFront.add(parent.getChildAt(i));
            }

            // now go over the stack and put em all on top in the correct
            // order
            while (!viewsToFront.isEmpty()) {
                View temp = viewsToFront.pop();
                parent.bringChildToFront(temp);
            }
            target.requestLayout();
        }
    } else {
        Toast.makeText(this, "You must select a widget first!",
                        Toast.LENGTH_SHORT).show();
    }
}
 
Example 207
Project: SwipeDismissListView   File: ViewPropertyAnimatorHC.java View source code 5 votes vote down vote up
/**
 * This method handles setting the property values directly in the View object's fields.
 * propertyConstant tells it which property should be set, value is the value to set
 * the property to.
 *
 * @param propertyConstant The property to be set
 * @param value The value to set the property to
 */
private void setValue(int propertyConstant, float value) {
    //final View.TransformationInfo info = mView.mTransformationInfo;
    View v = mView.get();
    if (v != null) {
        switch (propertyConstant) {
            case TRANSLATION_X:
                //info.mTranslationX = value;
                v.setTranslationX(value);
                break;
            case TRANSLATION_Y:
                //info.mTranslationY = value;
                v.setTranslationY(value);
                break;
            case ROTATION:
                //info.mRotation = value;
                v.setRotation(value);
                break;
            case ROTATION_X:
                //info.mRotationX = value;
                v.setRotationX(value);
                break;
            case ROTATION_Y:
                //info.mRotationY = value;
                v.setRotationY(value);
                break;
            case SCALE_X:
                //info.mScaleX = value;
                v.setScaleX(value);
                break;
            case SCALE_Y:
                //info.mScaleY = value;
                v.setScaleY(value);
                break;
            case X:
                //info.mTranslationX = value - v.mLeft;
                v.setX(value);
                break;
            case Y:
                //info.mTranslationY = value - v.mTop;
                v.setY(value);
                break;
            case ALPHA:
                //info.mAlpha = value;
                v.setAlpha(value);
                break;
        }
    }
}
 
Example 208
Project: ABPlayer   File: PLA_ListView.java View source code 5 votes vote down vote up
/**
 * Add a view as a child and make sure it is measured (if necessary) and
 * positioned properly.
 *
 * @param child The view to add
 * @param position The position of this child
 * @param y The y position relative to which this view will be positioned
 * @param flowDown If true, align top edge to y. If false, align bottom
 *        edge to y.
 * @param childrenLeft Left edge where children should be positioned
 * @param selected Is this position selected?
 * @param recycled Has this view been pulled from the recycle bin? If so it
 *        does not need to be remeasured.
 */
private void setupChild(View child, int position, int y, boolean flowDown, int childrenLeft,
		boolean selected, boolean recycled) {

	final boolean isSelected = selected && shouldShowSelector();
	final boolean updateChildSelected = isSelected != child.isSelected();
	final int mode = mTouchMode;
	final boolean isPressed = mode > TOUCH_MODE_DOWN && mode < TOUCH_MODE_SCROLL &&
			mMotionPosition == position;
	final boolean updateChildPressed = isPressed != child.isPressed();
	final boolean needToMeasure = !recycled || updateChildSelected || child.isLayoutRequested();

	// Respect layout params that are already in the view. Otherwise make some up...
	// noinspection unchecked
	PLA_AbsListView.LayoutParams p = (PLA_AbsListView.LayoutParams) child.getLayoutParams();
	if (p == null) {
		p = new PLA_AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
				ViewGroup.LayoutParams.WRAP_CONTENT, 0);
	}
	p.viewType = mAdapter.getItemViewType(position);

	if ((recycled && !p.forceAdd) || (p.recycledHeaderFooter &&
			p.viewType == PLA_AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER)) {
		attachViewToParent(child, flowDown ? -1 : 0, p);
	} else {
		p.forceAdd = false;
		if (p.viewType == PLA_AdapterView.ITEM_VIEW_TYPE_HEADER_OR_FOOTER) {
			p.recycledHeaderFooter = true;
		}
		addViewInLayout(child, flowDown ? -1 : 0, p, true);
	}

	if (updateChildSelected) {
		child.setSelected(isSelected);
	}

	if (updateChildPressed) {
		child.setPressed(isPressed);
	}

	if (needToMeasure) {
		int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
				mListPadding.left + mListPadding.right, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
		}

		onMeasureChild( child, position, childWidthSpec, childHeightSpec );
		//child.measure(childWidthSpec, childHeightSpec);
	} else {
		cleanupLayoutState(child);
	}

	final int w = child.getMeasuredWidth();
	final int h = child.getMeasuredHeight();
	final int childTop = flowDown ? y : y - h;

	if (needToMeasure) {
		final int childRight = childrenLeft + w;
		final int childBottom = childTop + h;
		//child.layout(childrenLeft, childTop, childRight, childBottom);
		onLayoutChild(child, position, childrenLeft, childTop, childRight, childBottom);
	} else {
		final int offsetLeft = childrenLeft - child.getLeft();
		final int offsetTop = childTop - child.getTop();
		onOffsetChild(child, position, offsetLeft, offsetTop);
	}

	if (mCachingStarted && !child.isDrawingCacheEnabled()) {
		child.setDrawingCacheEnabled(true);
	}
}
 
Example 209
Project: packages_apps_Launcher2   File: CellLayout.java View source code 5 votes vote down vote up
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    final int action = ev.getAction();
    final CellInfo cellInfo = mCellInfo;

    if (action == MotionEvent.ACTION_DOWN) {
        final Rect frame = mRect;
        final int x = (int) ev.getX() + mScrollX;
        final int y = (int) ev.getY() + mScrollY;
        final int count = getChildCount();

        boolean found = false;
        for (int i = count - 1; i >= 0; i--) {
            final View child = getChildAt(i);

            if ((child.getVisibility()) == VISIBLE || child.getAnimation() != null) {
                child.getHitRect(frame);
                if (frame.contains(x, y)) {
                    final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                    cellInfo.cell = child;
                    cellInfo.cellX = lp.cellX;
                    cellInfo.cellY = lp.cellY;
                    cellInfo.spanX = lp.cellHSpan;
                    cellInfo.spanY = lp.cellVSpan;
                    cellInfo.valid = true;
                    found = true;
                    mDirtyTag = false;
                    break;
                }
            }
        }
        
        mLastDownOnOccupiedCell = found;

        if (!found) {
            int cellXY[] = mCellXY;
            pointToCellExact(x, y, cellXY);

            final boolean portrait = mPortrait;
            final int xCount = portrait ? mShortAxisCells : mLongAxisCells;
            final int yCount = portrait ? mLongAxisCells : mShortAxisCells;

            final boolean[][] occupied = mOccupied;
            findOccupiedCells(xCount, yCount, occupied, null);

            cellInfo.cell = null;
            cellInfo.cellX = cellXY[0];
            cellInfo.cellY = cellXY[1];
            cellInfo.spanX = 1;
            cellInfo.spanY = 1;
            cellInfo.valid = cellXY[0] >= 0 && cellXY[1] >= 0 && cellXY[0] < xCount &&
                    cellXY[1] < yCount && !occupied[cellXY[0]][cellXY[1]];

            // Instead of finding the interesting vacant cells here, wait until a
            // caller invokes getTag() to retrieve the result. Finding the vacant
            // cells is a bit expensive and can generate many new objects, it's
            // therefore better to defer it until we know we actually need it.

            mDirtyTag = true;
        }
        setTag(cellInfo);
    } else if (action == MotionEvent.ACTION_UP) {
        cellInfo.cell = null;
        cellInfo.cellX = -1;
        cellInfo.cellY = -1;
        cellInfo.spanX = 0;
        cellInfo.spanY = 0;
        cellInfo.valid = false;
        mDirtyTag = false;
        setTag(cellInfo);
    }

    return false;
}
 
Example 210
Project: TwoDAdapter   File: TwoDScrollView.java View source code 5 votes vote down vote up
/**
 * Finds the next focusable component that fits in the specified bounds.
 * </p>
 *
 * @param topFocus look for a candidate is the one at the top of the bounds
 *                 if topFocus is true, or at the bottom of the bounds if topFocus is
 *                 false
 * @param top      the top offset of the bounds in which a focusable must be
 *                 found
 * @param bottom   the bottom offset of the bounds in which a focusable must
 *                 be found
 * @return the next focusable component in the bounds or null if none can
 *         be found
 */
private View findFocusableViewInBounds(boolean topFocus, int top, int bottom, boolean leftFocus, int left, int right) {
	List<View> focusables = getFocusables(View.FOCUS_FORWARD);
	View focusCandidate = null;

	/*
	 * A fully contained focusable is one where its top is below the bound's
	 * top, and its bottom is above the bound's bottom. A partially
	 * contained focusable is one where some part of it is within the
	 * bounds, but it also has some part that is not within bounds.  A fully contained
	 * focusable is preferred to a partially contained focusable.
	 */
	boolean foundFullyContainedFocusable = false;

	int count = focusables.size();
	for (int i = 0; i < count; i++) {
		View view = focusables.get(i);
		int viewTop = view.getTop();
		int viewBottom = view.getBottom();
		int viewLeft = view.getLeft();
		int viewRight = view.getRight();

		if (top < viewBottom && viewTop < bottom && left < viewRight && viewLeft < right) {
			/*
			 * the focusable is in the target area, it is a candidate for
			 * focusing
			 */
			final boolean viewIsFullyContained = (top < viewTop) && (viewBottom < bottom) && (left < viewLeft) && (viewRight < right);
			if (focusCandidate == null) {
				/* No candidate, take this one */
				focusCandidate = view;
				foundFullyContainedFocusable = viewIsFullyContained;
			} else {
				final boolean viewIsCloserToVerticalBoundary =
						(topFocus && viewTop < focusCandidate.getTop()) ||
						(!topFocus && viewBottom > focusCandidate.getBottom());
				final boolean viewIsCloserToHorizontalBoundary =
						(leftFocus && viewLeft < focusCandidate.getLeft()) ||
						(!leftFocus && viewRight > focusCandidate.getRight());
				if (foundFullyContainedFocusable) {
					if (viewIsFullyContained && viewIsCloserToVerticalBoundary && viewIsCloserToHorizontalBoundary) {
						/*
						 * We're dealing with only fully contained views, so
						 * it has to be closer to the boundary to beat our
						 * candidate
						 */
						focusCandidate = view;
					}
				} else {
					if (viewIsFullyContained) {
						/* Any fully contained view beats a partially contained view */
						focusCandidate = view;
						foundFullyContainedFocusable = true;
					} else if (viewIsCloserToVerticalBoundary && viewIsCloserToHorizontalBoundary) {
						/*
						 * Partially contained view beats another partially
						 * contained view if it's closer
						 */
						focusCandidate = view;
					}
				}
			}
		}
	}
	return focusCandidate;
}
 
Example 211
Project: googleio   File: FractionalTouchDelegate.java View source code 5 votes vote down vote up
@Override
public boolean onTouchEvent(MotionEvent event) {
    updateSourcePartial();

    // The logic below is mostly copied from the parent class, since we
    // can't update private mBounds variable.

    // http://android.git.kernel.org/?p=platform/frameworks/base.git;a=blob;
    // f=core/java/android/view/TouchDelegate.java;hb=eclair#l98

    final Rect sourcePartial = mSourcePartial;
    final View target = mTarget;

    int x = (int)event.getX();
    int y = (int)event.getY();

    boolean sendToDelegate = false;
    boolean hit = true;
    boolean handled = false;

    switch (event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        if (sourcePartial.contains(x, y)) {
            mDelegateTargeted = true;
            sendToDelegate = true;
        }
        break;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_MOVE:
        sendToDelegate = mDelegateTargeted;
        if (sendToDelegate) {
            if (!sourcePartial.contains(x, y)) {
                hit = false;
            }
        }
        break;
    case MotionEvent.ACTION_CANCEL:
        sendToDelegate = mDelegateTargeted;
        mDelegateTargeted = false;
        break;
    }

    if (sendToDelegate) {
        if (hit) {
            event.setLocation(target.getWidth() / 2, target.getHeight() / 2);
        } else {
            event.setLocation(-1, -1);
        }
        handled = target.dispatchTouchEvent(event);
    }
    return handled;
}
 
Example 212
Project: XposedGELSettings   File: TabHelperL.java View source code 5 votes vote down vote up
private void syncAppsPageItems(Object thisObject, ArrayList apps, int page) {
    final boolean isRtl = (Boolean) callMethod(thisObject, Methods.pvIsLayoutRtl);
    Tab currTab = getCurrentTabData();
    LayoutInflater mLayoutInflater = (LayoutInflater) getObjectField(thisObject, Fields.acpvLayoutInflater);

    int mCellCountX = getIntField(thisObject, Fields.acpvCellCountX);
    int mCellCountY = getIntField(thisObject, Fields.acpvCellCountY);
    int apps_customize_application = Common.LAUNCHER_CONTEXT.getResources().getIdentifier("apps_customize_application", "layout", Common.HOOKED_PACKAGE);

    int numCells = mCellCountX * mCellCountY;
    int startIndex = page * numCells;
    int endIndex = Math.min(startIndex + numCells, apps.size());
    ViewGroup appsCustomizeCellLayout = (ViewGroup) callMethod(thisObject, Methods.pvGetPageAt, page);
    appsCustomizeCellLayout.getBackground().setColorFilter(currTab.getPrimaryColor(), PorterDuff.Mode.MULTIPLY);

    callMethod(appsCustomizeCellLayout, Methods.acpvRemoveAllViewsOnPage);
    for (int i = startIndex; i < endIndex; ++i) {
        Object info = apps.get(i);
        View icon;

        int index = i - startIndex;
        int x = index % mCellCountX;
        int y = index / mCellCountX;
        if (isRtl) {
            x = mCellCountX - x - 1;
        }

        if (info instanceof Folder) {
            icon = ((Folder) info).makeFolderIcon(appsCustomizeCellLayout);
            if (icon == null) continue;
        } else {
            icon = mLayoutInflater.inflate(apps_customize_application, appsCustomizeCellLayout, false);
            callMethod(icon, Methods.btvApplyFromApplicationInfo, info);
            icon.setOnClickListener((View.OnClickListener) Common.LAUNCHER_INSTANCE);
            icon.setOnLongClickListener((View.OnLongClickListener) thisObject);
            icon.setOnTouchListener((View.OnTouchListener) thisObject);
            icon.setOnKeyListener((View.OnKeyListener) thisObject);
            icon.setOnFocusChangeListener((View.OnFocusChangeListener) getObjectField(appsCustomizeCellLayout, Fields.acclFocusHandlerView));
        }

        callMethod(appsCustomizeCellLayout, Methods.clAddViewToCellLayout, icon, -1, i, newInstance(Classes.CellLayoutLayoutParams, x, y, 1, 1), false);

        if (!PreferencesHelper.hideIconLabelApps) {
            TextView iconName;
            if (!(info instanceof Folder)) {
                iconName = (TextView) icon;
            } else {
                iconName = (TextView) getObjectField(icon, Fields.fiFolderName);
            }

            if (PreferencesHelper.iconSettingsSwitchApps) {
                iconName.setTextColor(PreferencesHelper.appdrawerIconLabelColor);
            } else {
                int color = currTab.getPrimaryColor();
                if (color >= Tab.DEFAULT_COLOR || color == Color.WHITE) {
                    iconName.setTextColor(Tab.DEFAULT_TEXT_COLOR);
                } else {
                    iconName.setTextColor(currTab.getContrastColor());
                }
            }
        }
    }

    callMethod(thisObject, Methods.acpvEnableHwLayersOnVisiblePages);
}
 
Example 213
Project: property-db   File: TabletStatusBar.java View source code 5 votes vote down vote up
public boolean onTouch(View v, MotionEvent event) {
//            Slog.d(TAG, String.format("touch: (%.1f, %.1f) initial: (%.1f, %.1f)",
//                        event.getX(),
//                        event.getY(),
//                        mInitialTouchX,
//                        mInitialTouchY));

            if ((mDisabled & StatusBarManager.DISABLE_EXPAND) != 0) {
                return true;
            }

            final int action = event.getAction();
            switch (action) {
                case MotionEvent.ACTION_DOWN:
                    mVT = VelocityTracker.obtain();
                    mInitialTouchX = event.getX();
                    mInitialTouchY = event.getY();
                    hilite(true);
                    // fall through
                case MotionEvent.ACTION_OUTSIDE:
                case MotionEvent.ACTION_MOVE:
                    // check for fling
                    if (mVT != null) {
                        mVT.addMovement(event);
                        mVT.computeCurrentVelocity(1000); // pixels per second
                        // require a little more oomph once we're already in peekaboo mode
                        if (mVT.getYVelocity() < -mNotificationFlingVelocity) {
                            animateExpandNotificationsPanel();
                            visibilityChanged(true);
                            hilite(false);
                            mVT.recycle();
                            mVT = null;
                        }
                    }
                    return true;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    hilite(false);
                    if (mVT != null) {
                        if (action == MotionEvent.ACTION_UP
                         // was this a sloppy tap?
                         && Math.abs(event.getX() - mInitialTouchX) < mTouchSlop
                         && Math.abs(event.getY() - mInitialTouchY) < (mTouchSlop / 3)
                         // dragging off the bottom doesn't count
                         && (int)event.getY() < v.getBottom()) {
                            animateExpandNotificationsPanel();
                            visibilityChanged(true);
                            v.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
                            v.playSoundEffect(SoundEffectConstants.CLICK);
                        }

                        mVT.recycle();
                        mVT = null;
                        return true;
                    }
            }
            return false;
        }
 
Example 214
Project: WallpaperPicker   File: WallpaperCropActivity.java View source code 5 votes vote down vote up
protected void cropImageAndSetWallpaper(Uri uri,
        OnBitmapCroppedHandler onBitmapCroppedHandler, final boolean finishActivityWhenDone) {
    boolean centerCrop = getResources().getBoolean(R.bool.center_crop);
    // Get the crop
    boolean ltr = mCropView.getLayoutDirection() == View.LAYOUT_DIRECTION_LTR;

    Display d = getWindowManager().getDefaultDisplay();

    Point displaySize = new Point();
    d.getSize(displaySize);
    boolean isPortrait = displaySize.x < displaySize.y;

    Point defaultWallpaperSize = getDefaultWallpaperSize(getResources(),
            getWindowManager());
    // Get the crop
    RectF cropRect = mCropView.getCrop();

    Point inSize = mCropView.getSourceDimensions();

    int cropRotation = mCropView.getImageRotation();
    float cropScale = mCropView.getWidth() / (float) cropRect.width();


    Matrix rotateMatrix = new Matrix();
    rotateMatrix.setRotate(cropRotation);
    float[] rotatedInSize = new float[] { inSize.x, inSize.y };
    rotateMatrix.mapPoints(rotatedInSize);
    rotatedInSize[0] = Math.abs(rotatedInSize[0]);
    rotatedInSize[1] = Math.abs(rotatedInSize[1]);


    // due to rounding errors in the cropview renderer the edges can be slightly offset
    // therefore we ensure that the boundaries are sanely defined
    cropRect.left = Math.max(0, cropRect.left);
    cropRect.right = Math.min(rotatedInSize[0], cropRect.right);
    cropRect.top = Math.max(0, cropRect.top);
    cropRect.bottom = Math.min(rotatedInSize[1], cropRect.bottom);

    // ADJUST CROP WIDTH
    // Extend the crop all the way to the right, for parallax
    // (or all the way to the left, in RTL)
    float extraSpace;
    if (centerCrop) {
        extraSpace = 2f * Math.min(rotatedInSize[0] - cropRect.right, cropRect.left);
    } else {
        extraSpace = ltr ? rotatedInSize[0] - cropRect.right : cropRect.left;
    }
    // Cap the amount of extra width
    float maxExtraSpace = defaultWallpaperSize.x / cropScale - cropRect.width();
    extraSpace = Math.min(extraSpace, maxExtraSpace);

    if (centerCrop) {
        cropRect.left -= extraSpace / 2f;
        cropRect.right += extraSpace / 2f;
    } else {
        if (ltr) {
            cropRect.right += extraSpace;
        } else {
            cropRect.left -= extraSpace;
        }
    }

    // ADJUST CROP HEIGHT
    if (isPortrait) {
        cropRect.bottom = cropRect.top + defaultWallpaperSize.y / cropScale;
    } else { // LANDSCAPE
        float extraPortraitHeight =
                defaultWallpaperSize.y / cropScale - cropRect.height();
        float expandHeight =
                Math.min(Math.min(rotatedInSize[1] - cropRect.bottom, cropRect.top),
                        extraPortraitHeight / 2);
        cropRect.top -= expandHeight;
        cropRect.bottom += expandHeight;
    }
    final int outWidth = (int) Math.round(cropRect.width() * cropScale);
    final int outHeight = (int) Math.round(cropRect.height() * cropScale);

    Runnable onEndCrop = new Runnable() {
        public void run() {
            updateWallpaperDimensions(outWidth, outHeight);
            if (finishActivityWhenDone) {
                setResult(Activity.RESULT_OK);
                finish();
            }
        }
    };
    BitmapCropTask cropTask = new BitmapCropTask(this, uri,
            cropRect, cropRotation, outWidth, outHeight, true, false, onEndCrop);
    if (onBitmapCroppedHandler != null) {
        cropTask.setOnBitmapCropped(onBitmapCroppedHandler);
    }
    cropTask.execute();
}
 
Example 215
Project: ABPlayer   File: PLA_ListView.java View source code 5 votes vote down vote up
@Override
protected void layoutChildren() {
	final boolean blockLayoutRequests = mBlockLayoutRequests;
	if (!blockLayoutRequests) {
		mBlockLayoutRequests = true;
	} else {
		return;
	}

	try {
		super.layoutChildren();
		invalidate();
		if (mAdapter == null) {
			resetList();
			invokeOnItemScrollListener();
			return;
		}

		int childrenTop = mListPadding.top;
		//int childrenBottom = mBottom - mTop - mListPadding.bottom;
		int childrenBottom = getBottom() - getTop() - mListPadding.bottom;

		int childCount = getChildCount();
		int index = 0;

		View oldFirst = null;
		View focusLayoutRestoreView = null;

		// Remember stuff we will need down below
		switch (mLayoutMode) {
		case LAYOUT_FORCE_TOP:
		case LAYOUT_FORCE_BOTTOM:
		case LAYOUT_SPECIFIC:
		case LAYOUT_SYNC:
			break;
		default:
			// Remember the previous first child
			oldFirst = getChildAt(0);
		}


		boolean dataChanged = mDataChanged;
		if (dataChanged) {
			handleDataChanged();
		}

		// Handle the empty set by removing all views that are visible
		// and calling it a day
		if (mItemCount == 0) {
			resetList();
			invokeOnItemScrollListener();
			return;
		} else if (mItemCount != mAdapter.getCount()) {
			throw new IllegalStateException("The content of the adapter has changed but "
					+ "ListView did not receive a notification. Make sure the content of "
					+ "your adapter is not modified from a background thread, but only "
					+ "from the UI thread. [in ListView(" + getId() + ", " + getClass() 
					+ ") with Adapter(" + mAdapter.getClass() + ")]");
		}

		// Pull all children into the RecycleBin.
		// These views will be reused if possible
		final int firstPosition = mFirstPosition;
		final RecycleBin recycleBin = mRecycler;

		// reset the focus restoration

		// Don't put header or footer views into the Recycler. Those are
		// already cached in mHeaderViews;
		if (dataChanged) {
			for (int i = 0; i < childCount; i++) {
				recycleBin.addScrapView(getChildAt(i));
				if (ViewDebug.TRACE_RECYCLER) {
					ViewDebug.trace(getChildAt(i),
							ViewDebug.RecyclerTraceType.MOVE_TO_SCRAP_HEAP, index, i);
				}
			}
		} else {
			recycleBin.fillActiveViews(childCount, firstPosition);
		}

		// take focus back to us temporarily to avoid the eventual
		// call to clear focus when removing the focused child below
		// from messing things up when ViewRoot assigns focus back
		// to someone else
		final View focusedChild = getFocusedChild();
		if (focusedChild != null) {
			// TODO: in some cases focusedChild.getParent() == null
			// we can remember the focused view to restore after relayout if the
			// data hasn't changed, or if the focused position is a header or footer
			if (!dataChanged || isDirectChildHeaderOrFooter(focusedChild)) {
				// remember the specific view that had focus
				focusLayoutRestoreView = findFocus();
				if (focusLayoutRestoreView != null) {
					// tell it we are going to mess with it
					focusLayoutRestoreView.onStartTemporaryDetach();
				}
			}
			requestFocus();
		}


		switch (mLayoutMode) {
		case LAYOUT_SYNC:
			onLayoutSync(mSyncPosition);
			// Clear out old views
			detachAllViewsFromParent();
			fillSpecific(mSyncPosition, mSpecificTop);
			onLayoutSyncFinished(mSyncPosition);
			break;
		case LAYOUT_FORCE_BOTTOM:
			detachAllViewsFromParent();
			fillUp(mItemCount - 1, childrenBottom);
			adjustViewsUpOrDown();
			break;
		case LAYOUT_FORCE_TOP:
			detachAllViewsFromParent();
			mFirstPosition = 0;
			fillFromTop(childrenTop);
			adjustViewsUpOrDown();
			break;
		default:
			if (childCount == 0) {
				detachAllViewsFromParent();
				if (!mStackFromBottom) {
					fillFromTop(childrenTop);
				} else {
					fillUp(mItemCount - 1, childrenBottom);
				}
			} else {
				if (mFirstPosition < mItemCount) {
					onLayoutSync(mFirstPosition);
					detachAllViewsFromParent();
					fillSpecific(mFirstPosition, oldFirst == null ? childrenTop : oldFirst.getTop());
					onLayoutSyncFinished(mFirstPosition);
				} else {
					onLayoutSync(0);
					detachAllViewsFromParent();
					fillSpecific(0, childrenTop);
					onLayoutSyncFinished(0);
				}
			}
			break;
		}

		// Flush any cached views that did not get reused above
		recycleBin.scrapActiveViews();

		if (mTouchMode > TOUCH_MODE_DOWN && mTouchMode < TOUCH_MODE_SCROLL) {
			View child = getChildAt(mMotionPosition - mFirstPosition);
			if (child != null) positionSelector(child);
		} else {
			mSelectedTop = 0;
			mSelectorRect.setEmpty();
		}

		// even if there is not selected position, we may need to restore
		// focus (i.e. something focusable in touch mode)
		if (hasFocus() && focusLayoutRestoreView != null) {
			focusLayoutRestoreView.requestFocus();
		}

		// tell focus view we are done mucking with it, if it is still in
		// our view hierarchy.
		if (focusLayoutRestoreView != null
				&& focusLayoutRestoreView.getWindowToken() != null) {
			focusLayoutRestoreView.onFinishTemporaryDetach();
		}

		mLayoutMode = LAYOUT_NORMAL;
		mDataChanged = false;
		mNeedSync = false;

		invokeOnItemScrollListener();
	} finally {
		if (!blockLayoutRequests) {
			mBlockLayoutRequests = false;
		}
	}
}
 
Example 216
Project: AcDisplay   File: TouchTracker.java View source code 5 votes vote down vote up
@Override
public boolean onTouch(View v, MotionEvent event) {
    final float x = event.getX();
    final float y = event.getY();

    if (v.isClickable() || v.isLongClickable()) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                if ((mPrePressed && pointInView(v, x, y, mTouchSlop)) || v.isPressed()) {
                    // take focus if we don't have it already and we should in
                    // touch mode.
                    boolean focusTaken = false;
                    if (v.isFocusable() && v.isFocusableInTouchMode() && !v.isFocused()) {
                        focusTaken = v.requestFocus();
                    }

                    if (mPrePressed) {
                        // The button is being released before we actually
                        // showed it as pressed.  Make it show the pressed
                        // state now (before scheduling the click) to ensure
                        // the user sees it.
                        setPressed(v, true, x, y);
                    }

                    if (!mHasPerformedLongPress) {
                        // This is a tap, so remove the longpress check
                        removeLongPressCallback(v);

                        // Only perform take click actions if we were in the pressed state
                        if (!focusTaken) {
                            // Use a Runnable and post this rather than calling
                            // performClick directly. This lets other visual state
                            // of the view update before click actions start.
                            if (mPerformClick == null) {
                                mPerformClick = new PerformClick(v);
                            }
                            if (!v.post(mPerformClick)) {
                                v.performClick();
                            }
                        }
                    }

                    if (mUnsetPressedState == null) {
                        mUnsetPressedState = new UnsetPressedState(v);
                    }

                    if (mPrePressed) {
                        v.postDelayed(mUnsetPressedState,
                                ViewConfiguration.getPressedStateDuration());
                    } else if (!v.post(mUnsetPressedState)) {
                        // If the post failed, unpress right now
                        mUnsetPressedState.run();
                    }

                    removeTapCallback(v);

                }
                break;

            case MotionEvent.ACTION_DOWN:
                mHasPerformedLongPress = false;

                if (mInsideScrollContainer) {

                    mPrePressed = true;
                    if (mPendingCheckForTap == null) {
                        mPendingCheckForTap = new CheckForTap(v);
                    }

                    mPendingCheckForTap.x = event.getX();
                    mPendingCheckForTap.y = event.getY();
                    v.postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());

                } else {
                    setPressed(v, true, x, y);
                    checkForLongClick(v, 0);
                }
                break;

            case MotionEvent.ACTION_MOVE:
                mHotspotDrawable.setHotspot(x, y);

                if (mTouchSlop == -1) {
                    mTouchSlop = ViewConfiguration.get(v.getContext()).getScaledTouchSlop();
                }

                // Be lenient about moving outside of buttons
                if (!pointInView(v, x, y, mTouchSlop)) {
                    // Outside button
                    removeTapCallback(v);
                    if (v.isPressed()) {
                        // Remove any future long press/tap checks
                        removeLongPressCallback(v);

                        v.setPressed(false);
                    }
                }
                break;

            case MotionEvent.ACTION_CANCEL:
                v.setPressed(false);
                removeTapCallback(v);
                removeLongPressCallback(v);
                break;
        }
        return true;
    }

    return false;
}
 
Example 217
Project: CSipSimple-old   File: InCallInfoGrid.java View source code 5 votes vote down vote up
synchronized void populate() {
    
    if (mAdapter == null) {
        return;
    }

    // Also, don't populate until we are attached to a window.  This is to
    // avoid trying to populate before we have restored our view hierarchy
    // state and conflicting with what is restored.
    if (getWindowToken() == null) {
        return;
    }
    
    int count = mAdapter.getCount();
    Log.d(THIS_FILE, "Populate " + count + " children");
    
    
    // Compute num of columns 
    int width = getWidth() - (getPaddingRight() + getPaddingLeft());
    int height = getHeight() - (getPaddingTop() + getPaddingBottom());
    int cellWidth = width;
    int cellHeight = height;
    int numRows = 1;
    int numColumns = 1;
    if(count > 0) {
        int possibleColumns = (int) FloatMath.floor( (width * 1.0f)/ (minColumnWidth * 1.0f) );
        if(possibleColumns <= 0) {
            possibleColumns = 1;
        }
        numColumns = Math.min(possibleColumns, count);
        numRows = count / numColumns;
        
        Log.v(THIS_FILE, "Render a grid of " + numColumns + " x " + numRows);
        
        cellWidth = width / numColumns;
        cellHeight = height / numRows;
        
        // TODO : warn - scroll - other?if we are outside bounds with min cell height
        if(cellHeight < minRowHeight) {
            Log.d(THIS_FILE, "May render weird... min height not correct " + cellHeight);
        }
        if(cellHeight <= 0 || cellWidth <= 0) {
            Log.w(THIS_FILE, "The call grid cannot render " + cellHeight + "x" + cellWidth
                    + " for " + width + "x" + height);
            cellWidth = minColumnWidth;
            cellHeight = minRowHeight;
        }
    }
    
    // Add it if needed.
    int curIndex = -1;
    for (curIndex = 0; curIndex < mAdapter.getCount(); curIndex++) {
        
        View ii = null;
        if(mItems.size() > curIndex) {
            ii = mItems.get(curIndex);
        }
        ii = mAdapter.getView(curIndex, ii, this);
        if(mItems.size() > curIndex) {
            mItems.set(curIndex, ii);
        }else {
            mItems.add(ii);
        }
        
        // Set layout of the view
        int posX = curIndex % numColumns;
        int posY = curIndex / numColumns;
        LayoutParams lp = (LayoutParams) ii.getLayoutParams();
        if(lp == null) {
            lp = new FrameLayout.LayoutParams(cellWidth, cellHeight);
        }else {
            lp.height = cellHeight;
            lp.width = cellWidth;
        }
        lp.leftMargin = posX * cellWidth;
        lp.topMargin = posY * cellHeight;
        ii.setLayoutParams(lp);
        // Append to parent if needed
        ViewParent p = ii.getParent();
        if(p == null) {
            addView(ii);
        }else {
            if(p == this) {
                updateViewLayout(ii, lp); 
            }else {
                Log.w(THIS_FILE, "Call card already attached to somebody else");
            }
        }
        ii.forceLayout();
    }
    
    // Remove useles
    if(mItems.size() > mAdapter.getCount()) {
        for(curIndex = mItems.size()-1; curIndex >= mAdapter.getCount() ; curIndex --) {
            removeViewAt(curIndex);
        }
    }
    
}
 
Example 218
Project: cardslib   File: NativeMiscCardFragment.java View source code 5 votes vote down vote up
@Override

        public boolean applyBitmap(final View imageView, Bitmap bitmap) {

            CircleDrawable circle = new CircleDrawable(bitmap);
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
                imageView.setBackground(circle);
            else
                imageView.setBackgroundDrawable(circle);


            ViewCompat.setElevation(imageView, mElevationCircle);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
                imageView.setOutlineProvider(
                        new ViewOutlineProvider(){
                            @TargetApi(Build.VERSION_CODES.LOLLIPOP)
                            @Override
                            public void getOutline(View view, Outline outline) {
                                outline.setOval(0, 0, mSizeCircle, mSizeCircle);
                            }
                        });
                imageView.setClipToOutline(true);

            }


            /*imageView.setOnTouchListener(new View.OnTouchListener() {
                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    switch (motionEvent.getAction()){
                        case MotionEvent.ACTION_DOWN:
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                imageView.animate().setDuration(100).scaleX(1.1f).scaleY(1.1f).translationZ(10);
                            } else {
                                imageView.animate().setDuration(100).scaleX(1.1f).scaleY(1.1f);
                            }
                            return true;
                        case MotionEvent.ACTION_CANCEL:
                        case MotionEvent.ACTION_UP:
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                                imageView.animate().setDuration(100).scaleX(1).scaleY(1).translationZ(0);
                            } else {
                                imageView.animate().setDuration(100).scaleX(1).scaleY(1);
                            }
                            return true;
                    }
                    return false;
                }
            });*/


            return true;

        }
 
Example 219
Project: XieDaDeng   File: TaskViewTransform.java View source code 5 votes vote down vote up
/** Applies this transform to a view. */
public void applyToTaskView(View v, int duration, Interpolator interp, boolean allowLayers,
        boolean allowShadows, ValueAnimator.AnimatorUpdateListener updateCallback) {
    // Check to see if any properties have changed, and update the task view
    if (duration > 0) {
        ViewPropertyAnimator anim = v.animate();
        boolean requiresLayers = false;

        // Animate to the final state
        if (hasTranslationYChangedFrom(v.getTranslationY())) {
            anim.translationY(translationY);
        }
        if (allowShadows && hasTranslationZChangedFrom(v.getTranslationZ())) {
            anim.translationZ(translationZ);
        }
        if (hasScaleChangedFrom(v.getScaleX())) {
            anim.scaleX(scale)
                .scaleY(scale);
            requiresLayers = true;
        }
        if (hasAlphaChangedFrom(v.getAlpha())) {
            // Use layers if we animate alpha
            anim.alpha(alpha);
            requiresLayers = true;
        }
        if (requiresLayers && allowLayers) {
            anim.withLayer();
        }
        if (updateCallback != null) {
            anim.setUpdateListener(updateCallback);
        } else {
            anim.setUpdateListener(null);
        }
        anim.setStartDelay(startDelay)
                .setDuration(duration)
                .setInterpolator(interp)
                .start();
    } else {
        // Set the changed properties
        if (hasTranslationYChangedFrom(v.getTranslationY())) {
            v.setTranslationY(translationY);
        }
        if (allowShadows && hasTranslationZChangedFrom(v.getTranslationZ())) {
            v.setTranslationZ(translationZ);
        }
        if (hasScaleChangedFrom(v.getScaleX())) {
            v.setScaleX(scale);
            v.setScaleY(scale);
        }
        if (hasAlphaChangedFrom(v.getAlpha())) {
            v.setAlpha(alpha);
        }
    }
}
 
Example 220
Project: Fontster   File: ViewUtils.java View source code 5 votes vote down vote up
public static void reveal(Activity activity, View view, View sourceView, int colorRes) {
    if (activity == null || view == null || sourceView == null) return;
    if (isLollipop()) {
        final ViewGroupOverlay groupOverlay =
                (ViewGroupOverlay) activity.getWindow().getDecorView().getOverlay();

        final Rect displayRect = new Rect();
        view.getGlobalVisibleRect(displayRect);

        // Make reveal cover the display and status bar.
        final View revealView = new View(activity);
        revealView.setTop(displayRect.top);
        revealView.setBottom(displayRect.bottom);
        revealView.setLeft(displayRect.left);
        revealView.setRight(displayRect.right);
        revealView.setBackgroundColor(activity.getResources().getColor(colorRes));
        groupOverlay.add(revealView);

        final int[] clearLocation = new int[2];
        sourceView.getLocationInWindow(clearLocation);
        clearLocation[0] += sourceView.getWidth() / 2;
        clearLocation[1] += sourceView.getHeight() / 2;

        final int revealCenterX = clearLocation[0] - revealView.getLeft();
        final int revealCenterY = clearLocation[1] - revealView.getTop();

        final double x1_2 = Math.pow(revealView.getLeft() - revealCenterX, 2);
        final double x2_2 = Math.pow(revealView.getRight() - revealCenterX, 2);
        final double y_2 = Math.pow(revealView.getTop() - revealCenterY, 2);
        final float revealRadius = (float) Math.max(Math.sqrt(x1_2 + y_2), Math.sqrt(x2_2 + y_2));

        try {
            final Animator revealAnimator =
                    ViewAnimationUtils.createCircularReveal(revealView,
                            revealCenterX, revealCenterY, 0.0f, revealRadius);
            revealAnimator.setDuration(
                    activity.getResources().getInteger(android.R.integer.config_mediumAnimTime));

            final Animator alphaAnimator = ObjectAnimator.ofFloat(revealView, View.ALPHA, 0.0f);
            alphaAnimator.setDuration(
                    activity.getResources().getInteger(android.R.integer.config_shortAnimTime));
            alphaAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    view.startAnimation(AnimationUtils.loadAnimation(activity, R.anim.abc_fade_in));
                    view.setVisibility(View.VISIBLE);
                }
            });

            final AnimatorSet animatorSet = new AnimatorSet();
            animatorSet.play(revealAnimator).before(alphaAnimator);
            animatorSet.setInterpolator(new AccelerateDecelerateInterpolator());
            animatorSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animator) {
                    groupOverlay.remove(revealView);
                }
            });

            animatorSet.start();
        } catch (IllegalStateException e) {
            Timber.i("View is detached - not animating");
        }
    } else {
        view.setVisibility(View.VISIBLE);
    }
}
 
Example 221
Project: cordova-plugin-ad-admob   File: AdmobOverlap.java View source code 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
protected void handleLayoutChangeOverlap() {
	//http://stackoverflow.com/questions/24539578/cordova-plugin-listening-to-device-orientation-change-is-it-possible
	//http://developer.android.com/reference/android/view/View.OnLayoutChangeListener.html
	//https://gitshell.com/lvxudong/A530_packages_app_Camera/blob/master/src/com/android/camera/ActivityBase.java
	//plugin.getWebView().addOnLayoutChangeListener(new View.OnLayoutChangeListener(){//only for ~cordova4
	//plugin.getWebView().getRootView().addOnLayoutChangeListener(new View.OnLayoutChangeListener(){//only for ~cordova4
	//plugin.getWebView().getView().addOnLayoutChangeListener(new View.OnLayoutChangeListener(){//only for cordova5~
	getView(plugin.getWebView()).addOnLayoutChangeListener(new View.OnLayoutChangeListener(){
			
		@Override
		public void onLayoutChange(View v, int left, int top, int right, int bottom,
				int oldLeft, int oldTop, int oldRight, int oldBottom) {
			if (left == oldLeft && top == oldTop && right == oldRight
					&& bottom == oldBottom) {
				return;
			}

			Log.d(LOG_TAG, "onLayoutChange");
			//Util.alert(cordova.getActivity(), "onLayoutChange");
			
			int orientation = Util.getDisplayRotation(plugin.getCordova().getActivity());
			if(orientation != lastOrientation) {
				Log.d(LOG_TAG, String.format("orientation: %d", orientation));
				//Util.alert(cordova.getActivity(), String.format("orientation: %d", orientation));
				if (bannerPreviousSize != null && bannerPreviousSize.equals("SMART_BANNER")) {
					Log.d(LOG_TAG, String.format("position: %s, size: %s", bannerPreviousPosition, bannerPreviousSize));
					//Util.alert(cordova.getActivity(), String.format("position: %s, size: %s", position, size));

					//overlap
					//http://stackoverflow.com/questions/11281562/android-admob-resize-on-landscape
					if (bannerView != null) {							
						//if banner is showing
						RelativeLayout bannerViewLayout = (RelativeLayout)bannerView.getParent();
						if (bannerViewLayout != null) {
							//bannerViewLayout.removeView(bannerView);
							//bannerView.destroy();
							//bannerView = null;				
							Log.d(LOG_TAG, String.format("position: %s, size: %s", bannerPreviousPosition, bannerPreviousSize));
							//Util.alert(cordova.getActivity(), String.format("position: %s, size: %s", position, size));

							//http://stackoverflow.com/questions/3072173/how-to-call-a-method-after-a-delay-in-android
							final Handler handler = new Handler();
							handler.postDelayed(new Runnable() {
								@Override
								public void run() {
									_showBannerAd(bannerPreviousPosition, bannerPreviousSize);
								}
							}, 1);//after 1ms
						}
					}						
				}
			}
		
			lastOrientation = orientation;		
		}		    
	});		
   }