Example usage for android.view Display getHeight

List of usage examples for android.view Display getHeight

Introduction

In this page you can find the example usage for android.view Display getHeight.

Prototype

@Deprecated
public int getHeight() 

Source Link

Usage

From source file:com.javielinux.tweettopics2.TweetTopicsActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    try {//from   ww  w  .  j a va2 s.c  om
        DataFramework.getInstance().open(this, Utils.packageName);
    } catch (Exception e) {
        e.printStackTrace();
    }

    super.onCreate(savedInstanceState);

    CacheData.getInstance().fillHide();

    ConnectionManager.getInstance().open(this);
    ConnectionManager.getInstance().loadUsers();

    OnAlarmReceiver.callAlarm(this);

    if (PreferenceUtils.getFinishForceClose(this)) {
        PreferenceUtils.setFinishForceClose(this, false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.title_crash);
        builder.setMessage(R.string.msg_crash);
        builder.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Utils.sendLastCrash(TweetTopicsActivity.this);
            }
        });
        builder.setNegativeButton(R.string.alert_dialog_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
            }
        });
        builder.create();
        builder.show();
    }

    Thread.UncaughtExceptionHandler currentHandler = Thread.getDefaultUncaughtExceptionHandler();
    if (currentHandler != null) {
        Thread.setDefaultUncaughtExceptionHandler(new ErrorReporter(currentHandler, getApplication()));
    }

    if (PreferenceManager.getDefaultSharedPreferences(this).getString("prf_orientation", "2").equals("2")) {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
    }

    // borrar notificaciones
    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("prf_notif_delete_notifications_inside",
            true)) {
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).cancelAll();
    }

    long goToColumnPosition = -1;
    int goToColumnType = -1;
    long goToColumnUser = -1;
    long goToColumnSearch = -1;
    long selectedTweetId = -1;

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_POSITION)) {
            goToColumnPosition = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_POSITION);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_TYPE)) {
            goToColumnType = extras.getInt(KEY_EXTRAS_GOTO_COLUMN_TYPE);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_USER)) {
            goToColumnUser = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_USER);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_COLUMN_SEARCH)) {
            goToColumnSearch = extras.getLong(KEY_EXTRAS_GOTO_COLUMN_SEARCH);
        }
        if (extras.containsKey(KEY_EXTRAS_GOTO_TWEET_ID)) {
            selectedTweetId = extras.getLong(KEY_EXTRAS_GOTO_TWEET_ID);
        }
    }

    int positionFromSensor = -1;
    if (savedInstanceState != null && savedInstanceState.containsKey(KEY_SAVE_STATE_COLUMN_POS)) {
        positionFromSensor = savedInstanceState.getInt(KEY_SAVE_STATE_COLUMN_POS);
    }

    Utils.createDirectoriesIfIsNecessary();

    Display display = getWindowManager().getDefaultDisplay();
    widthScreen = display.getWidth();
    heightScreen = display.getHeight();

    themeManager = new ThemeManager(this);
    themeManager.setTheme();

    setContentView(R.layout.tweettopics_activity);

    fragmentAdapter = new TweetTopicsFragmentAdapter(this, getSupportFragmentManager());

    pager = (ViewPager) findViewById(R.id.tweet_pager);
    pager.setAdapter(fragmentAdapter);

    indicator = (TitlePageIndicator) findViewById(R.id.tweettopics_bar_indicator);
    indicator.setFooterIndicatorStyle(TitlePageIndicator.IndicatorStyle.Triangle);
    indicator.setFooterLineHeight(0);
    indicator.setFooterColor(Color.WHITE);
    indicator.setClipPadding(-getWindowManager().getDefaultDisplay().getWidth());
    indicator.setViewPager(pager);
    indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i1) {
        }

        @Override
        public void onPageSelected(int i) {
            reloadBarAvatar();
            if (i == 0) {
                refreshMyActivity();
            }
        }

        @Override
        public void onPageScrollStateChanged(int i) {

        }
    });
    indicator.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showActionBarColumns();
        }
    });

    findViewById(R.id.tweettopics_bar_my_activity).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showActionBarIndicatorAndMovePager(0);
        }
    });

    findViewById(R.id.tweettopics_bar_options).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showMenuColumnsOptions(view);
        }
    });

    layoutOptionsColumns = (LinearLayout) findViewById(R.id.tweettopics_ll_options_columns);
    layoutMainOptionsColumns = (LinearLayout) findViewById(R.id.tweettopics_ll_main_options_columns);
    layoutMainOptionsColumns.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            hideOptionsColumns();
        }
    });
    btnOptionsColumnsMain = (Button) findViewById(R.id.tweettopics_ll_options_columns_btn_main);
    btnOptionsColumnsMain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int pos = Integer.valueOf(view.getTag().toString());
            Toast.makeText(TweetTopicsActivity.this,
                    getString(R.string.column_main_message, fragmentAdapter.setColumnActive(pos)),
                    Toast.LENGTH_LONG).show();
            hideOptionsColumns();
        }
    });
    btnOptionsColumnsEdit = (Button) findViewById(R.id.tweettopics_ll_options_columns_btn_edit);
    btnOptionsColumnsEdit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            int pos = Integer.valueOf(view.getTag().toString());
            EditColumnDialogFragment frag = new EditColumnDialogFragment(
                    fragmentAdapter.getFragmentList().get(pos), new Callable() {
                        @Override
                        public Object call() throws Exception {
                            refreshActionBarColumns();
                            return null;
                        }
                    });
            frag.show(getSupportFragmentManager(), "dialog");
            hideOptionsColumns();
        }
    });

    // cargar el popup de enlaces

    FrameLayout root = ((FrameLayout) findViewById(R.id.tweettopics_root));
    popupLinks = new PopupLinks(this);
    popupLinks.loadPopup(root);

    splitActionBarMenu = new SplitActionBarMenu(this);
    splitActionBarMenu.loadSplitActionBarMenu(root);

    layoutBackgroundApp = (RelativeLayout) findViewById(R.id.tweettopics_layout_background_app);

    layoutBackgroundBar = (RelativeLayout) findViewById(R.id.tweettopics_bar_background);

    horizontalScrollViewColumns = (HorizontalScrollView) findViewById(R.id.tweettopics_bar_horizontal_scroll);

    layoutBackgroundColumnsBarContainer = (LinearLayout) findViewById(R.id.tweettopics_bar_columns_container);

    layoutBackgroundColumnsBar = (LinearLayout) findViewById(R.id.tweettopics_bar_columns);
    //        layoutBackgroundColumnsBar.setCols(4);
    //
    //        layoutBackgroundColumnsBar.setOnRearrangeListener(new OnRearrangeListener() {
    //            public void onRearrange(int oldIndex, int newIndex) {
    //                reorganizeColumns(oldIndex, newIndex);
    //            }
    //
    //            @Override
    //            public void onStartDrag(int x, int index) {
    //                showOptionsColumns(x, index, true);
    //            }
    //
    //            @Override
    //            public void onMoveDragged(int index) {
    //                hideOptionsColumns();
    //            }
    //
    //        });
    //        layoutBackgroundColumnsBar.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    //            @Override
    //            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
    //                showActionBarIndicatorAndMovePager(position);
    //            }
    //        });

    imgBarAvatar = (ImageView) findViewById(R.id.tweettopics_bar_avatar);
    imgBarAvatarBg = (ImageView) findViewById(R.id.tweettopics_bar_avatar_bg);
    imgBarCounter = (TextView) findViewById(R.id.tweettopics_bar_counter);
    imgNewStatus = (ImageView) findViewById(R.id.tweettopics_bar_new_status);
    imgNewStatus.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            newStatus();
        }
    });

    imgBarAvatarGestureDetector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
        @Override
        public void onLongPress(MotionEvent e) {
            if (fragmentAdapter.instantiateItem(pager, pager.getCurrentItem()) instanceof BaseListFragment) {
                ((BaseListFragment) fragmentAdapter.instantiateItem(pager, pager.getCurrentItem())).goToTop();
            }
        }

        @Override
        public boolean onDoubleTap(MotionEvent e) {
            if (fragmentAdapter.instantiateItem(pager, pager.getCurrentItem()) instanceof BaseListFragment) {
                ((BaseListFragment) fragmentAdapter.instantiateItem(pager, pager.getCurrentItem())).goToTop();
            }
            return true;
        }

        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            animateDragged();
            return true;
        }

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    });

    imgBarAvatarBg.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            return imgBarAvatarGestureDetector.onTouchEvent(motionEvent);
        }
    });

    refreshTheme();

    reloadBarAvatar();

    refreshActionBarColumns();

    if (goToColumnType >= 0) {
        if ((goToColumnType == TweetTopicsUtils.COLUMN_TIMELINE
                || goToColumnType == TweetTopicsUtils.COLUMN_MENTIONS
                || goToColumnType == TweetTopicsUtils.COLUMN_DIRECT_MESSAGES) && goToColumnUser >= 0) {
            openUserColumn(goToColumnUser, goToColumnType);
        }
        if (goToColumnType == TweetTopicsUtils.COLUMN_SEARCH && goToColumnSearch > 0) {
            openSearchColumn(new Entity("search", goToColumnSearch));
        }
    } else if (goToColumnType == TweetTopicsUtils.COLUMN_MY_ACTIVITY) {
    } else if (goToColumnPosition > 0) {
        goToColumn((int) goToColumnPosition, false, selectedTweetId);
    } else if (positionFromSensor >= 0) {
        goToColumn(positionFromSensor, false, selectedTweetId);
    } else {
        int col = fragmentAdapter.getPositionColumnActive();
        if (col > 0)
            goToColumn(col, false, selectedTweetId);
    }

    // comprobar si hay que proponer ir al market

    int access_count = PreferenceUtils.getApplicationAccessCount(this);

    if (access_count <= 20) {
        if (access_count == 20) {
            try {
                AlertDialog dialog = DialogUtils.RateAppDialogBuilder.create(this);
                dialog.show();
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }

        PreferenceUtils.setApplicationAccessCount(this, access_count + 1);
    }

    PreferenceUtils.showChangeLog(this, true);

}

From source file:com.playhaven.android.req.PlayHavenRequest.java

@SuppressWarnings("deprecation")
protected UriComponentsBuilder createUrl(Context context) throws PlayHavenException {
    try {//  ww w . j  a  v  a  2 s .c  om
        SharedPreferences pref = PlayHaven.getPreferences(context);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(getString(pref, APIServer));
        builder.path(context.getResources().getString(getApiPath(context)));
        builder.queryParam("app", getString(pref, AppPkg));
        builder.queryParam("opt_out", getString(pref, OptOut, "0"));
        builder.queryParam("app_version", getString(pref, AppVersion));
        builder.queryParam("os", getInt(pref, OSVersion, 0));
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        builder.queryParam("orientation", display.getRotation());
        builder.queryParam("hardware", getString(pref, DeviceModel));
        PlayHaven.ConnectionType connectionType = getConnectionType(context);
        builder.queryParam("connection", connectionType.ordinal());
        builder.queryParam("idiom",
                context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK);

        /**
         * For height/width we will use getSize(Point) not getRealSize(Point) as this will allow us to automatically
         * account for rotation and screen decorations like the status bar. We only want to know available space.
         *
         * @playhaven.apihack for SDK_INT < 13, have to use getHeight and getWidth!
         */
        Point size = new Point();
        if (Build.VERSION.SDK_INT >= 13) {
            display.getSize(size);
        } else {
            size.x = display.getWidth();
            size.y = display.getHeight();
        }
        builder.queryParam("width", size.x);
        builder.queryParam("height", size.y);

        /**
         * SDK Version needs to be reported as a dotted numeric value
         * So, if it is a -SNAPSHOT build, we will replace -SNAPSHOT with the date of the build
         * IE: 2.0.0.20130201
         * as opposed to an actual released build, which would be like 2.0.0
         */
        String sdkVersion = getString(pref, SDKVersion);
        String[] date = Version.PLUGIN_BUILD_TIME.split("[\\s]");
        sdkVersion = sdkVersion.replace("-SNAPSHOT", "." + date[0].replaceAll("-", ""));
        builder.queryParam("sdk_version", sdkVersion);

        builder.queryParam("plugin", getString(pref, PluginIdentifer));

        Locale locale = context.getResources().getConfiguration().locale;
        builder.queryParam("languages", String.format("%s,%s", locale.toString(), locale.getLanguage()));
        builder.queryParam("token", getString(pref, Token));

        builder.queryParam("device", getString(pref, DeviceId));
        DisplayMetrics metrics = new DisplayMetrics();
        display.getMetrics(metrics);
        builder.queryParam("dpi", metrics.densityDpi);

        String uuid = UUID.randomUUID().toString();
        String nonce = base64Digest(uuid);
        builder.queryParam("nonce", nonce);

        ktsid = KontagentUtil.getSenderId(context);
        if (ktsid != null)
            builder.queryParam("sid", ktsid);

        addSignature(builder, pref, nonce);

        // Setup for signature verification
        String secret = getString(pref, Secret);
        SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC);
        sigMac = Mac.getInstance(HMAC);
        sigMac.init(key);
        sigMac.update(nonce.getBytes(UTF8));

        return builder;
    } catch (Exception e) {
        throw new PlayHavenException(e);
    }
}

From source file:com.android.messaging.ui.conversation.ConversationFragment.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    switch (item.getItemId()) {
    case R.id.action_people_and_options:
        Assert.isTrue(mBinding.getData().getParticipantsLoaded());
        UIIntents.get().launchPeopleAndOptionsActivity(getActivity(), mConversationId);
        return true;

    case R.id.action_call:
        final String phoneNumber = mBinding.getData().getParticipantPhoneNumber();
        Assert.notNull(phoneNumber);//from w  w  w. j  a  v a  2 s  .  c  om
        final View targetView = getActivity().findViewById(R.id.action_call);
        Point centerPoint;
        if (targetView != null) {
            final int screenLocation[] = new int[2];
            targetView.getLocationOnScreen(screenLocation);
            final int centerX = screenLocation[0] + targetView.getWidth() / 2;
            final int centerY = screenLocation[1] + targetView.getHeight() / 2;
            centerPoint = new Point(centerX, centerY);
        } else {
            // In the overflow menu, just use the center of the screen.
            final Display display = getActivity().getWindowManager().getDefaultDisplay();
            centerPoint = new Point(display.getWidth() / 2, display.getHeight() / 2);
        }
        UIIntents.get().launchPhoneCallActivity(getActivity(), phoneNumber, centerPoint);
        return true;

    case R.id.action_archive:
        mBinding.getData().archiveConversation(mBinding);
        closeConversation(mConversationId);
        return true;

    case R.id.action_unarchive:
        mBinding.getData().unarchiveConversation(mBinding);
        return true;

    case R.id.action_settings:
        return true;

    case R.id.action_add_contact:
        final ParticipantData participant = mBinding.getData().getOtherParticipant();
        Assert.notNull(participant);
        final String destination = participant.getNormalizedDestination();
        final Uri avatarUri = AvatarUriUtil.createAvatarUri(participant);
        (new AddContactsConfirmationDialog(getActivity(), avatarUri, destination)).show();
        return true;

    case R.id.action_delete:
        if (isReadyForAction()) {
            new AlertDialog.Builder(getActivity())
                    .setTitle(getResources()
                            .getQuantityString(R.plurals.delete_conversations_confirmation_dialog_title, 1))
                    .setPositiveButton(R.string.delete_conversation_confirmation_button,
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(final DialogInterface dialog, final int button) {
                                    deleteConversation();
                                }
                            })
                    .setNegativeButton(R.string.delete_conversation_decline_button, null).show();
        } else {
            warnOfMissingActionConditions(false /*sending*/, null /*commandToRunAfterActionConditionResolved*/);
        }
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:github.daneren2005.dsub.fragments.SelectDirectoryFragment.java

private void setupTextDisplay(final View header) {
    final TextView titleView = (TextView) header.findViewById(R.id.select_album_title);
    if (playlistName != null) {
        titleView.setText(playlistName);
    } else if (podcastName != null) {
        titleView.setText(podcastName);//www .  j  a v a 2s  .  c o  m
        titleView.setPadding(0, 6, 4, 8);
    } else if (name != null) {
        titleView.setText(name);

        if (artistInfo != null) {
            titleView.setPadding(0, 6, 4, 8);
        }
    } else if (share != null) {
        titleView.setVisibility(View.GONE);
    }

    int songCount = 0;

    Set<String> artists = new HashSet<String>();
    Set<Integer> years = new HashSet<Integer>();
    Integer totalDuration = 0;
    for (Entry entry : entries) {
        if (!entry.isDirectory()) {
            songCount++;
            if (entry.getArtist() != null) {
                artists.add(entry.getArtist());
            }
            if (entry.getYear() != null) {
                years.add(entry.getYear());
            }
            Integer duration = entry.getDuration();
            if (duration != null) {
                totalDuration += duration;
            }
        }
    }

    final TextView artistView = (TextView) header.findViewById(R.id.select_album_artist);
    if (podcastDescription != null || artistInfo != null) {
        artistView.setVisibility(View.VISIBLE);
        String text = podcastDescription != null ? podcastDescription : artistInfo.getBiography();
        Spanned spanned = null;
        if (text != null) {
            spanned = Html.fromHtml(text);
        }
        artistView.setText(spanned);
        artistView.setSingleLine(false);
        final int minLines = context.getResources().getInteger(R.integer.TextDescriptionLength);
        artistView.setLines(minLines);
        artistView.setTextAppearance(context, android.R.style.TextAppearance_Small);

        final Spanned spannedText = spanned;
        artistView.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                if (artistView.getMaxLines() == minLines) {
                    // Use LeadingMarginSpan2 to try to make text flow around image
                    Display display = context.getWindowManager().getDefaultDisplay();
                    ImageView coverArtView = (ImageView) header.findViewById(R.id.select_album_art);
                    coverArtView.measure(display.getWidth(), display.getHeight());

                    int height, width;
                    ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) coverArtView
                            .getLayoutParams();
                    if (coverArtView.getDrawable() != null) {
                        height = coverArtView.getMeasuredHeight() + coverArtView.getPaddingBottom();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    } else {
                        height = coverArtView.getHeight();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    }
                    float textLineHeight = artistView.getPaint().getTextSize();
                    int lines = (int) Math.ceil(height / textLineHeight);

                    SpannableString ss = new SpannableString(spannedText);
                    ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    View linearLayout = header.findViewById(R.id.select_album_text_layout);
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout
                            .getLayoutParams();
                    int[] rules = params.getRules();
                    rules[RelativeLayout.RIGHT_OF] = 0;
                    params.leftMargin = vlp.rightMargin;

                    artistView.setText(ss);
                    artistView.setMaxLines(100);

                    vlp = (ViewGroup.MarginLayoutParams) titleView.getLayoutParams();
                    vlp.leftMargin = width;
                } else {
                    artistView.setMaxLines(minLines);
                }
            }
        });
        artistView.setMovementMethod(LinkMovementMethod.getInstance());
    } else if (topTracks) {
        artistView.setText(R.string.menu_top_tracks);
        artistView.setVisibility(View.VISIBLE);
    } else if (showAll) {
        artistView.setText(R.string.menu_show_all);
        artistView.setVisibility(View.VISIBLE);
    } else if (artists.size() == 1) {
        String artistText = artists.iterator().next();
        if (years.size() == 1) {
            artistText += " - " + years.iterator().next();
        }
        artistView.setText(artistText);
        artistView.setVisibility(View.VISIBLE);
    } else {
        artistView.setVisibility(View.GONE);
    }

    TextView songCountView = (TextView) header.findViewById(R.id.select_album_song_count);
    TextView songLengthView = (TextView) header.findViewById(R.id.select_album_song_length);
    if (podcastDescription != null || artistInfo != null) {
        songCountView.setVisibility(View.GONE);
        songLengthView.setVisibility(View.GONE);
    } else {
        String s = context.getResources().getQuantityString(R.plurals.select_album_n_songs, songCount,
                songCount);
        songCountView.setText(s.toUpperCase());
        songLengthView.setText(Util.formatDuration(totalDuration));
    }
}

From source file:com.iiordanov.bVNC.RemoteCanvas.java

/**
 * Constructor used by the inflation apparatus
 * /*w w  w. j  a v  a 2  s.  com*/
 * @param context
 */
public RemoteCanvas(final Context context, AttributeSet attrs) {
    super(context, attrs);

    clipboard = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE);

    decoder = new Decoder(this);

    isRdp = getContext().getPackageName().contains("RDP");
    isSpice = getContext().getPackageName().contains("SPICE");

    final Display display = ((Activity) context).getWindow().getWindowManager().getDefaultDisplay();
    displayWidth = display.getWidth();
    displayHeight = display.getHeight();
    DisplayMetrics metrics = new DisplayMetrics();
    display.getMetrics(metrics);
    displayDensity = metrics.density;

    if (android.os.Build.MODEL.contains("BlackBerry") || android.os.Build.BRAND.contains("BlackBerry")
            || android.os.Build.MANUFACTURER.contains("BlackBerry")) {
        bb = true;
    }
}

From source file:github.daneren2005.dsub.fragments.NowPlayingFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
    rootView = inflater.inflate(R.layout.download, container, false);
    setTitle(R.string.button_bar_now_playing);

    WindowManager w = context.getWindowManager();
    Display d = w.getDefaultDisplay();
    swipeDistance = (d.getWidth() + d.getHeight()) * PERCENTAGE_OF_SCREEN_FOR_SWIPE / 100;
    swipeVelocity = (d.getWidth() + d.getHeight()) * PERCENTAGE_OF_SCREEN_FOR_SWIPE / 100;
    gestureScanner = new GestureDetector(this);

    playlistFlipper = (ViewFlipper) rootView.findViewById(R.id.download_playlist_flipper);
    emptyTextView = (TextView) rootView.findViewById(R.id.download_empty);
    songTitleTextView = (TextView) rootView.findViewById(R.id.download_song_title);
    albumArtImageView = (ImageView) rootView.findViewById(R.id.download_album_art_image);
    positionTextView = (TextView) rootView.findViewById(R.id.download_position);
    durationTextView = (TextView) rootView.findViewById(R.id.download_duration);
    statusTextView = (TextView) rootView.findViewById(R.id.download_status);
    progressBar = (SeekBar) rootView.findViewById(R.id.download_progress_bar);
    previousButton = (AutoRepeatButton) rootView.findViewById(R.id.download_previous);
    nextButton = (AutoRepeatButton) rootView.findViewById(R.id.download_next);
    pauseButton = rootView.findViewById(R.id.download_pause);
    stopButton = rootView.findViewById(R.id.download_stop);
    startButton = rootView.findViewById(R.id.download_start);
    repeatButton = (ImageButton) rootView.findViewById(R.id.download_repeat);
    bookmarkButton = (ImageButton) rootView.findViewById(R.id.download_bookmark);
    rateBadButton = (ImageButton) rootView.findViewById(R.id.download_rating_bad);
    rateGoodButton = (ImageButton) rootView.findViewById(R.id.download_rating_good);
    toggleListButton = rootView.findViewById(R.id.download_toggle_list);

    playlistView = (RecyclerView) rootView.findViewById(R.id.download_list);
    FastScroller fastScroller = (FastScroller) rootView.findViewById(R.id.download_fast_scroller);
    fastScroller.attachRecyclerView(playlistView);
    setupLayoutManager(playlistView, false);
    ItemTouchHelper touchHelper = new ItemTouchHelper(new DownloadFileItemHelperCallback(this, true));
    touchHelper.attachToRecyclerView(playlistView);

    starButton = (ImageButton) rootView.findViewById(R.id.download_star);
    if (Util.getPreferences(context).getBoolean(Constants.PREFERENCES_KEY_MENU_STAR, true)) {
        starButton.setOnClickListener(new OnClickListener() {
            @Override//from w  w w  .  ja  v  a2 s.com
            public void onClick(View v) {
                DownloadFile currentDownload = getDownloadService().getCurrentPlaying();
                if (currentDownload != null) {
                    final Entry currentSong = currentDownload.getSong();
                    toggleStarred(currentSong, new OnStarChange() {
                        @Override
                        void starChange(boolean starred) {
                            if (currentSong.isStarred()) {
                                starButton.setImageDrawable(
                                        DrawableTint.getTintedDrawable(context, R.drawable.ic_toggle_star));
                            } else {
                                if (context.getResources()
                                        .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                                    starButton.setImageResource(
                                            DrawableTint.getDrawableRes(context, R.attr.star_outline));
                                } else {
                                    starButton.setImageResource(R.drawable.ic_toggle_star_outline_dark);
                                }
                            }
                        }
                    });
                }
            }
        });
    } else {
        starButton.setVisibility(View.GONE);
    }

    View.OnTouchListener touchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent me) {
            return gestureScanner.onTouchEvent(me);
        }
    };
    pauseButton.setOnTouchListener(touchListener);
    stopButton.setOnTouchListener(touchListener);
    startButton.setOnTouchListener(touchListener);
    bookmarkButton.setOnTouchListener(touchListener);
    rateBadButton.setOnTouchListener(touchListener);
    rateGoodButton.setOnTouchListener(touchListener);
    emptyTextView.setOnTouchListener(touchListener);
    albumArtImageView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent me) {
            if (me.getAction() == MotionEvent.ACTION_DOWN) {
                lastY = (int) me.getRawY();
            }
            return gestureScanner.onTouchEvent(me);
        }
    });

    previousButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            warnIfStorageUnavailable();
            new SilentBackgroundTask<Void>(context) {
                @Override
                protected Void doInBackground() throws Throwable {
                    getDownloadService().previous();
                    return null;
                }
            }.execute();
            setControlsVisible(true);
        }
    });
    previousButton.setOnRepeatListener(new Runnable() {
        public void run() {
            changeProgress(-INCREMENT_TIME);
        }
    });

    nextButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            warnIfStorageUnavailable();
            new SilentBackgroundTask<Boolean>(context) {
                @Override
                protected Boolean doInBackground() throws Throwable {
                    getDownloadService().next();
                    return true;
                }
            }.execute();
            setControlsVisible(true);
        }
    });
    nextButton.setOnRepeatListener(new Runnable() {
        public void run() {
            changeProgress(INCREMENT_TIME);
        }
    });

    pauseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new SilentBackgroundTask<Void>(context) {
                @Override
                protected Void doInBackground() throws Throwable {
                    getDownloadService().pause();
                    return null;
                }
            }.execute();
        }
    });

    stopButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            new SilentBackgroundTask<Void>(context) {
                @Override
                protected Void doInBackground() throws Throwable {
                    getDownloadService().reset();
                    return null;
                }
            }.execute();
        }
    });

    startButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            warnIfStorageUnavailable();
            new SilentBackgroundTask<Void>(context) {
                @Override
                protected Void doInBackground() throws Throwable {
                    start();
                    return null;
                }
            }.execute();
        }
    });

    repeatButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            RepeatMode repeatMode = getDownloadService().getRepeatMode().next();
            getDownloadService().setRepeatMode(repeatMode);
            switch (repeatMode) {
            case OFF:
                Util.toast(context, R.string.download_repeat_off);
                break;
            case ALL:
                Util.toast(context, R.string.download_repeat_all);
                break;
            case SINGLE:
                Util.toast(context, R.string.download_repeat_single);
                break;
            default:
                break;
            }
            updateRepeatButton();
            setControlsVisible(true);
        }
    });

    bookmarkButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            createBookmark();
        }
    });

    rateBadButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DownloadService downloadService = getDownloadService();
            if (downloadService == null) {
                return;
            }

            DownloadFile downloadFile = downloadService.getCurrentPlaying();
            if (downloadFile == null) {
                return;
            }
            Entry entry = downloadFile.getSong();

            // If rating == 1, already set so unset
            if (entry.getRating() == 1) {
                setRating(entry, 0);

                if (context.getResources()
                        .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    rateBadButton.setImageResource(R.drawable.ic_action_rating_bad_dark);
                } else {
                    rateBadButton.setImageResource(DrawableTint.getDrawableRes(context, R.attr.rating_bad));
                }
            } else {
                // Immediately skip to the next song
                downloadService.next(true);

                // Otherwise set rating to 1
                setRating(entry, 1);
                rateBadButton.setImageDrawable(
                        DrawableTint.getTintedDrawable(context, R.drawable.ic_action_rating_bad_selected));

                // Make sure good rating is blank
                if (context.getResources()
                        .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    rateGoodButton.setImageResource(R.drawable.ic_action_rating_good_dark);
                } else {
                    rateGoodButton.setImageResource(DrawableTint.getDrawableRes(context, R.attr.rating_good));
                }
            }
        }
    });
    rateGoodButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            DownloadService downloadService = getDownloadService();
            if (downloadService == null) {
                return;
            }

            DownloadFile downloadFile = downloadService.getCurrentPlaying();
            if (downloadFile == null) {
                return;
            }
            Entry entry = downloadFile.getSong();

            // If rating == 5, already set so unset
            if (entry.getRating() == 5) {
                setRating(entry, 0);

                if (context.getResources()
                        .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    rateGoodButton.setImageResource(R.drawable.ic_action_rating_good_dark);
                } else {
                    rateGoodButton.setImageResource(DrawableTint.getDrawableRes(context, R.attr.rating_good));
                }
            } else {
                // Otherwise set rating to maximum
                setRating(entry, 5);
                rateGoodButton.setImageDrawable(
                        DrawableTint.getTintedDrawable(context, R.drawable.ic_action_rating_good_selected));

                // Make sure bad rating is blank
                if (context.getResources()
                        .getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    rateBadButton.setImageResource(R.drawable.ic_action_rating_bad_dark);
                } else {
                    rateBadButton.setImageResource(DrawableTint.getDrawableRes(context, R.attr.rating_bad));
                }
            }
        }
    });

    toggleListButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            toggleFullscreenAlbumArt();
            setControlsVisible(true);
        }
    });

    View overlay = rootView.findViewById(R.id.download_overlay_buttons);
    final int overlayHeight = overlay != null ? overlay.getHeight() : -1;
    albumArtImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (overlayHeight == -1 || lastY < (view.getBottom() - overlayHeight)) {
                toggleFullscreenAlbumArt();
                setControlsVisible(true);
            }
        }
    });

    progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onStopTrackingTouch(final SeekBar seekBar) {
            new SilentBackgroundTask<Void>(context) {
                @Override
                protected Void doInBackground() throws Throwable {
                    getDownloadService().seekTo(progressBar.getProgress());
                    return null;
                }

                @Override
                protected void done(Void result) {
                    seekInProgress = false;
                }
            }.execute();
        }

        @Override
        public void onStartTrackingTouch(final SeekBar seekBar) {
            seekInProgress = true;
        }

        @Override
        public void onProgressChanged(final SeekBar seekBar, final int position, final boolean fromUser) {
            if (fromUser) {
                positionTextView.setText(Util.formatDuration(position / 1000));
                setControlsVisible(true);
            }
        }
    });

    if (Build.MODEL.equals("Nexus 4") || Build.MODEL.equals("GT-I9100")) {
        View slider = rootView.findViewById(R.id.download_slider);
        slider.setPadding(0, 0, 0, 0);
    }

    return rootView;
}

From source file:com.abc.driver.MainActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_weixin);
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

    mTabPager = (ViewPager) findViewById(R.id.tabpager);
    mTabPager.setOnPageChangeListener(new MyOnPageChangeListener());

    mTab1 = (ImageView) findViewById(R.id.img_weixin);
    mTab2 = (ImageView) findViewById(R.id.img_address);
    mTab3 = (ImageView) findViewById(R.id.img_friends);
    mTab4 = (ImageView) findViewById(R.id.img_settings);
    mTabImg = (ImageView) findViewById(R.id.img_tab_now);
    mTab1.setOnClickListener(new MyOnClickListener(0));
    mTab2.setOnClickListener(new MyOnClickListener(1));
    mTab3.setOnClickListener(new MyOnClickListener(2));
    mTab4.setOnClickListener(new MyOnClickListener(3));
    Display currDisplay = getWindowManager().getDefaultDisplay();
    int displayWidth = currDisplay.getWidth();
    int displayHeight = currDisplay.getHeight();
    one = displayWidth / 4;/*from   w  w w . j ava  2 s . c  o  m*/
    two = one * 2;
    three = one * 3;

    LayoutInflater mLi = LayoutInflater.from(this);
    // View view1 = mLi.inflate(R.layout.main_tab_horder_create, null);
    View view1 = mLi.inflate(R.layout.main_tab_truckplan, null);
    View view2 = mLi.inflate(R.layout.main_tab_huoyun, null);
    View view3 = mLi.inflate(R.layout.main_tab_horder, null);
    View view4 = mLi.inflate(R.layout.main_tab_me, null);

    final ArrayList<View> views = new ArrayList<View>();
    views.add(view1);
    views.add(view2);
    views.add(view3);
    views.add(view4);

    PagerAdapter mPagerAdapter = new PagerAdapter() {

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public int getCount() {
            return views.size();
        }

        @Override
        public void destroyItem(View container, int position, Object object) {
            ((ViewPager) container).removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(View container, int position) {
            ((ViewPager) container).addView(views.get(position));
            return views.get(position);
        }
    };

    mTabPager.setAdapter(mPagerAdapter);

    initData();
}

From source file:com.kaltura.playersdk.PlayerViewController.java

@SuppressLint("NewApi")
private Point getRealScreenSize() {
    Display display = mActivity.getWindowManager().getDefaultDisplay();
    int realWidth = 0;
    int realHeight = 0;

    if (Build.VERSION.SDK_INT >= 17) {
        //new pleasant way to get real metrics
        DisplayMetrics realMetrics = new DisplayMetrics();
        display.getRealMetrics(realMetrics);
        realWidth = realMetrics.widthPixels;
        realHeight = realMetrics.heightPixels;

    } else {/*w ww  .j  a  v  a 2 s .co  m*/
        try {
            Method mGetRawH = Display.class.getMethod("getRawHeight");
            Method mGetRawW = Display.class.getMethod("getRawWidth");
            realWidth = (Integer) mGetRawW.invoke(display);
            realHeight = (Integer) mGetRawH.invoke(display);
        } catch (Exception e) {
            realWidth = display.getWidth();
            realHeight = display.getHeight();
            Log.e("Display Info", "Couldn't use reflection to get the real display metrics.");
        }

    }
    return new Point(realWidth, realHeight);
}

From source file:github.popeen.dsub.fragments.SelectDirectoryFragment.java

private void setupTextDisplay(final View header) {

    final TextView titleView = (TextView) header.findViewById(R.id.select_album_title);
    if (playlistName != null) {
        titleView.setText(playlistName);
    } else if (podcastName != null) {
        Collections.reverse(entries);
        titleView.setText(podcastName);//from www  . j  av  a2s. c o m
        titleView.setPadding(0, 6, 4, 8);
    } else if (name != null) {
        titleView.setText(name);
        if (artistInfo != null) {
            titleView.setPadding(0, 6, 4, 8);
        }
    } else if (share != null) {
        titleView.setVisibility(View.GONE);
    }

    int songCount = 0;

    Set<String> artists = new HashSet<String>();
    Set<Integer> years = new HashSet<Integer>();
    totalDuration = 0;
    for (Entry entry : entries) {
        if (!entry.isDirectory()) {
            songCount++;
            if (entry.getArtist() != null) {
                artists.add(entry.getArtist());
            }
            if (entry.getYear() != null) {
                years.add(entry.getYear());
            }
            Integer duration = entry.getDuration();
            if (duration != null) {
                totalDuration += duration;
            }
        }
    }
    String artistName = "";
    bookDescription = "Could not collect any info about the book at this time";
    try {

        artistName = artists.iterator().next();
        String endpoint = "getBookDirectory";
        if (Util.isTagBrowsing(context)) {
            endpoint = "getBook";
        }
        SharedPreferences prefs = Util.getPreferences(context);
        String url = Util.getRestUrl(context, endpoint) + "&id=" + directory.getId() + "&f=json";

        Log.w("GetInfo", url);
        String artist, title;
        int year = 0;
        artist = title = "";

        try {
            artist = artists.iterator().next();
        } catch (Exception e) {
            Log.w("GetInfoArtist", e.toString());
        }
        try {
            title = titleView.getText().toString();
        } catch (Exception e) {
            Log.w("GetInfoTitle", e.toString());
        }
        try {
            year = years.iterator().next();
        } catch (Exception e) {
            Log.w("GetInfoYear", e.toString());
        }

        BookInfoAPIParams params = new BookInfoAPIParams(url, artist, title, year);
        bookInfo = new BookInfoAPI(context).execute(params).get();
        bookDescription = bookInfo[0];
        bookReader = bookInfo[1];

    } catch (Exception e) {
        Log.w("GetInfoError", e.toString());
    }
    if (bookDescription.equals("noInfo")) {
        bookDescription = "The server has no description for this book";
    }

    final TextView artistView = (TextView) header.findViewById(R.id.select_album_artist);
    if (podcastDescription != null || artistInfo != null || bookDescription != null) {
        artistView.setVisibility(View.VISIBLE);

        String text = "";
        if (bookDescription != null) {
            text = bookDescription;
        }
        if (podcastDescription != null) {
            text = podcastDescription;
        }
        if (artistInfo != null) {
            text = artistInfo.getBiography();
        }
        Spanned spanned = null;
        if (text != null) {
            String newText = "";
            try {
                if (!artistName.equals("")) {
                    newText += "<b>" + context.getResources().getString(R.string.main_artist) + "</b>: "
                            + artistName + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                if (totalDuration > 0) {
                    newText += "<b>" + context.getResources().getString(R.string.album_book_reader) + "</b>: "
                            + bookReader + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                if (totalDuration > 0) {
                    newText += "<b>" + context.getResources().getString(R.string.album_book_length) + "</b>: "
                            + Util.formatDuration(totalDuration) + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                newText += text + "<br/>";
            } catch (Exception e) {
            }
            spanned = Html.fromHtml(newText);
        }

        artistView.setText(spanned);
        artistView.setSingleLine(false);
        final int minLines = context.getResources().getInteger(R.integer.TextDescriptionLength);
        artistView.setLines(minLines);
        artistView.setTextAppearance(context, android.R.style.TextAppearance_Small);

        final Spanned spannedText = spanned;
        artistView.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                if (artistView.getMaxLines() == minLines) {
                    // Use LeadingMarginSpan2 to try to make text flow around image
                    Display display = context.getWindowManager().getDefaultDisplay();
                    ImageView coverArtView = (ImageView) header.findViewById(R.id.select_album_art);
                    coverArtView.measure(display.getWidth(), display.getHeight());

                    int height, width;
                    ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) coverArtView
                            .getLayoutParams();
                    if (coverArtView.getDrawable() != null) {
                        height = coverArtView.getMeasuredHeight() + coverArtView.getPaddingBottom();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    } else {
                        height = coverArtView.getHeight();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    }
                    float textLineHeight = artistView.getPaint().getTextSize();

                    int lines = (int) Math.ceil(height / textLineHeight) + 1;

                    SpannableString ss = new SpannableString(spannedText);
                    ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    View linearLayout = header.findViewById(R.id.select_album_text_layout);
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout
                            .getLayoutParams();
                    int[] rules = params.getRules();
                    rules[RelativeLayout.RIGHT_OF] = 0;
                    params.leftMargin = vlp.rightMargin;

                    artistView.setText(ss);
                    artistView.setMaxLines(100);

                    vlp = (ViewGroup.MarginLayoutParams) titleView.getLayoutParams();
                    vlp.leftMargin = width;
                } else {
                    artistView.setMaxLines(minLines);
                }
            }
        });
        artistView.setMovementMethod(LinkMovementMethod.getInstance());
    } else if (topTracks) {
        artistView.setText(R.string.menu_top_tracks);
        artistView.setVisibility(View.VISIBLE);
    } else if (showAll) {
        artistView.setText(R.string.menu_show_all);
        artistView.setVisibility(View.VISIBLE);
    } else if (artists.size() == 1) {
        String artistText = artists.iterator().next();
        if (years.size() == 1) {
            artistText += " - " + years.iterator().next();
        }
        artistView.setText(artistText);
        artistView.setVisibility(View.VISIBLE);
    } else {
        artistView.setVisibility(View.GONE);
    }

    TextView songCountView = (TextView) header.findViewById(R.id.select_album_song_count);
    TextView songLengthView = (TextView) header.findViewById(R.id.select_album_song_length);
    if (podcastDescription != null || artistInfo != null) {
        songCountView.setVisibility(View.GONE);
        songLengthView.setVisibility(View.GONE);
    } else {
        String s = context.getResources().getQuantityString(R.plurals.select_album_n_songs, songCount,
                songCount);

        songCountView.setVisibility(View.GONE);
        songLengthView.setVisibility(View.GONE);
    }
}