Example usage for android.view Display getWidth

List of usage examples for android.view Display getWidth

Introduction

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

Prototype

@Deprecated
public int getWidth() 

Source Link

Usage

From source file:github.popeen.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);
    rewindButton = (AutoRepeatButton) rootView.findViewById(R.id.download_rewind);
    fastforwardButton = (AutoRepeatButton) rootView.findViewById(R.id.download_fastforward);
    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);
    playbackSpeedButton = (ImageButton) rootView.findViewById(R.id.download_playback_speed);
    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/*w  w  w  .  j  av a2 s.c o  m*/
            public void onClick(View v) {
                getDownloadService().toggleStarred();
                setControlsVisible(true);
            }
        });
    } 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);
    playbackSpeedButton.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(true);
        }
    });

    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(false);
        }
    });

    rewindButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            changeProgress(true);
        }
    });
    rewindButton.setOnRepeatListener(new Runnable() {
        public void run() {
            changeProgress(true);
        }
    });

    fastforwardButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            changeProgress(false);
        }
    });
    fastforwardButton.setOnRepeatListener(new Runnable() {
        public void run() {
            changeProgress(false);
        }
    });

    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();
            setControlsVisible(true);
        }
    });

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

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        setPlaybackSpeed();
    } else {
        playbackSpeedButton.setVisibility(View.GONE);
    }

    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);
            }
            DownloadService downloadService = getDownloadService();
            TextView textTimer = (TextView) context.findViewById(R.id.textTimer);
            if (downloadService != null && downloadService.getSleepTimer()) {
                int timeRemaining = downloadService.getSleepTimeRemaining();
                textTimer.setText(context.getResources().getString(R.string.download_stop_time_remaining,
                        Util.formatDuration(timeRemaining)));
                if (timeRemaining > 0) {
                    textTimer.setVisibility(View.VISIBLE);
                } else {
                    textTimer.setVisibility(View.GONE);
                }
            } else {
                if (textTimer != null) {
                    textTimer.setVisibility(View.GONE);
                }
            }
        }
    });

    return rootView;
}

From source file:com.segma.trim.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    MobileAds.initialize(getApplicationContext(), ADMOB_KEY);
    setContentView(R.layout.activity_main);
    loadAds();//  w w w  .  j a v  a 2s  .c  om
    MEMORY_SIZE = ((ActivityManager) getSystemService(ACTIVITY_SERVICE)).getMemoryClass();
    MAX_BITMAP_PIXELS = calculateMaxBitmapPixels();
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    ipv = (ImageProcessingView) findViewById(R.id.ipv);
    loadLicense();
    loadUserSetting();
    final Runnable runnableOnTextView = new Runnable() {
        @Override
        public void run() {
            ipv.setVisibility(View.VISIBLE);
            // TODO: update pending: the image enlarges due to larger space
            rawBitmap = getSampleImage();
            rawBitmapWidth = rawBitmap.getWidth();
            rawBitmapHeight = rawBitmap.getHeight();
            STATE = STATE_PROCESSING_IMAGE;
            textView.setVisibility(View.GONE);
            ipv.process(rawBitmap);
        }
    };
    Display display = getWindowManager().getDefaultDisplay();
    Point size = new Point();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
        display.getSize(size);
        screenWidth = size.x;
        screenHeight = size.y;
    } else {
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        screenWidth = display.getWidth();
        screenHeight = display.getHeight();
    }

    initControls();
    textView = (TextView) findViewById(R.id.tv_message);
    textView.setEnabled(false);
    ViewTreeObserver viewTreeObserver = ipv.getViewTreeObserver();
    if (viewTreeObserver.isAlive()) {
        viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                ImageProcessingViewWidth = ipv.getWidth();
                ImageProcessingViewHeight = ipv.getHeight();
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                    ipv.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                } else {
                    ipv.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                }
                if (ImageProcessingViewHeight != 0)
                    textView.setEnabled(true);
            }
        });
    }
    textView.setText(MESSAGE_STARTUP);
    textView.setOnTouchListener(new View.OnTouchListener() {
        float original_text_size;

        @Override
        public boolean onTouch(View v, final MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                original_text_size = textView.getTextSize();
                //textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, Math.round(original_text_size * 1.15));
                handlerOnTextView.postDelayed(runnableOnTextView, LONG_PRESS_TIME_ON_TEXTVIEW);
                textView.setEnabled(false);
                break;
            case MotionEvent.ACTION_MOVE:
                handlerOnTextView.removeCallbacks(runnableOnTextView);
                break;
            case MotionEvent.ACTION_UP:
                //textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, original_text_size);
                handlerOnTextView.removeCallbacks(runnableOnTextView);
                v.setEnabled(true);
                break;
            }
            return false;
        }
    });
    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    actionBar = getSupportActionBar();
    //actionBar.setDisplayHomeAsUpEnabled(true);
    ipv.setVisibility(View.INVISIBLE);

    if (MODE_DEBUG) {
        LICENSE = LICENSE_PREMIUM;
        getPackageManager().clearPackagePreferredActivities(getApplicationContext().getPackageName());
    }
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Gets the current orientation.//from  w ww  . j  a v a 2 s . c om
 * 
 * @param context
 * @return   {@link es.javocsoft.android.lib.toolbox.ToolBox.SCREEN_ORIENTATION}
 */
@SuppressWarnings("deprecation")
public static SCREEN_ORIENTATION screen_getOrientation(Context context) {
    SCREEN_ORIENTATION res = SCREEN_ORIENTATION.PORTRAIT;

    Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    //int orientation = Configuration.ORIENTATION_UNDEFINED;
    if (display.getWidth() == display.getHeight()) {
        res = SCREEN_ORIENTATION.SQUARE;
        //orientation = Configuration.ORIENTATION_SQUARE;
    } else {
        if (display.getWidth() < display.getHeight()) {
            res = SCREEN_ORIENTATION.PORTRAIT;
            //orientation = Configuration.ORIENTATION_PORTRAIT;
        } else {
            res = SCREEN_ORIENTATION.LANDSCAPE;
            //orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
    }
    return res;
}

From source file:com.youku.player.base.YoukuBasePlayerActivity.java

private boolean isLand() {
    Display getOrient = getWindowManager().getDefaultDisplay();
    return getOrient.getWidth() > getOrient.getHeight();
}

From source file:com.FluksoViz.FluksoVizActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    Display display = getWindowManager().getDefaultDisplay();
    screen_width = display.getWidth();
    if (screen_width == 320) {
        setContentView(R.layout.main_lowres);
    } else//  www.j a  v  a2  s  .  c o m
        setContentView(R.layout.main);

    context = getApplicationContext();
    SharedPreferences my_app_prefs = PreferenceManager.getDefaultSharedPreferences(this);

    try {
        versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    sensor_number = Integer.parseInt(my_app_prefs.getString("sensor_number", "1"));
    api_server_ip = my_app_prefs.getString("api_server", "178.79.177.6");
    skip_initial_sensor_checks = (Boolean) my_app_prefs.getBoolean("skip_initial_sensor_checks", false);
    ip_addr = (String) my_app_prefs.getString("flukso_ip_addr", "10.10.10.10");
    api_key_1 = (String) my_app_prefs.getString("sensor_1_api_key", "0.0.0.0");
    api_key_2 = (String) my_app_prefs.getString("sensor_2_api_key", "0.0.0.0");
    api_key_3 = (String) my_app_prefs.getString("sensor_3_api_key", "0.0.0.0");
    api_token_1 = (String) my_app_prefs.getString("sensor_1_token", "0.0.0.0");
    api_token_2 = (String) my_app_prefs.getString("sensor_2_token", "0.0.0.0");
    api_token_3 = (String) my_app_prefs.getString("sensor_3_token", "0.0.0.0");
    cost_fixedpart = Double.parseDouble(my_app_prefs.getString("cost_perkwh", "0"));
    cost_perkwh = Double.parseDouble(my_app_prefs.getString("cost_perkwh", "0"));
    cost_currencycode = (String) my_app_prefs.getString("cost_currencycode", "PLN");

    Napis = (TextView) findViewById(R.id.textView1);
    Napis2 = (TextView) findViewById(R.id.textView2);
    Napis01 = (TextView) findViewById(R.id.textView01);
    Napis3 = (TextView) findViewById(R.id.textView_r1);
    Napis4 = (TextView) findViewById(R.id.textView_rd1);
    tv_p1 = (TextView) findViewById(R.id.textView_p1);
    tv_p1.setTextColor(Color.WHITE);
    tv_p1.setVisibility(TextView.INVISIBLE);
    tv_p2 = (TextView) findViewById(R.id.textView_p2);
    tv_p2.setTextColor(Color.WHITE);
    tv_p2.setVisibility(TextView.INVISIBLE);
    tv_p3 = (TextView) findViewById(R.id.textView_p3);
    tv_p3.setTextColor(Color.WHITE);
    tv_p3.setVisibility(TextView.INVISIBLE);
    tv_today_kwh = (TextView) findViewById(R.id.TextView_r2);
    tv_today_cost = (TextView) findViewById(R.id.TextView_r4);
    tv_today_percent = (TextView) findViewById(R.id.TextView_r6);
    tv_today_avg = (TextView) findViewById(R.id.TextView_r22);
    tv_week_kwh = (TextView) findViewById(R.id.TextView_rd2);
    tv_week_avg = (TextView) findViewById(R.id.TextView_rd22);
    tv_week_cost = (TextView) findViewById(R.id.TextView_rd4);
    tv_week_percent = (TextView) findViewById(R.id.TextView_rd6);

    tv_month_kwh = (TextView) findViewById(R.id.TextView_rt2);
    tv_month_avg = (TextView) findViewById(R.id.TextView_rt22);
    tv_month_cost = (TextView) findViewById(R.id.TextView_rt4);
    tv_month_percent = (TextView) findViewById(R.id.TextView_rt6);

    tv_curr1 = (TextView) findViewById(R.id.TextView_r5);
    tv_curr2 = (TextView) findViewById(R.id.TextView_rd5);
    tv_curr3 = (TextView) findViewById(R.id.TextView_rt5);
    tv_curr1.setText(cost_currencycode);
    tv_curr2.setText(cost_currencycode);
    tv_curr3.setText(cost_currencycode);

    Napis01.setText("" + sensor_number);

    iv1 = (ImageView) findViewById(R.id.arrow_image1);
    iv2 = (ImageView) findViewById(R.id.arrow_image2);
    iv3 = (ImageView) findViewById(R.id.arrow_image3);

    W = (TextView) findViewById(R.id.textView4);
    napis_delta = (TextView) findViewById(R.id.textView_delta);
    napis_delta.setText("" + (char) 0x0394);
    napis_delta.setTextColor(Color.WHITE);
    napis_delta.setVisibility(TextView.INVISIBLE);

    Plot1 = (XYPlot) findViewById(R.id.Plot1);
    Plot2 = (XYPlot) findViewById(R.id.Plot2);

    series1m = new SimpleXYSeries("seria 1m");
    series2m = new SimpleXYSeries("seria 2m");
    series3m = new SimpleXYSeries("seria 3m");

    series_p2_1 = new SimpleXYSeries("plot 2 - 1");

    series1mFormat = new LineAndPointFormatter(Color.rgb(0, 180, 0), // line
            Color.rgb(50, 100, 0), // point color
            null);
    line1mFill = new Paint();
    line1mFill.setAlpha(100);
    line1mFill.setShader(
            new LinearGradient(0, 0, 0, 200, Color.rgb(0, 100, 0), Color.BLACK, Shader.TileMode.MIRROR));
    series1mFormat.getLinePaint().setStrokeWidth(3);
    series1mFormat.getVertexPaint().setStrokeWidth(0);
    series1mFormat.setFillPaint(line1mFill);

    series2mFormat = new LineAndPointFormatter( // FAZA 2 formater
            Color.rgb(0, 200, 0), // line color
            Color.rgb(0, 100, 50), // point color
            null);
    line2mFill = new Paint();
    line2mFill.setAlpha(100);
    line2mFill.setShader(
            new LinearGradient(0, 0, 0, 200, Color.rgb(0, 100, 0), Color.BLACK, Shader.TileMode.MIRROR));
    series2mFormat.getLinePaint().setStrokeWidth(3);
    series2mFormat.getVertexPaint().setStrokeWidth(0);
    series2mFormat.setFillPaint(line2mFill);

    series3mFormat = new LineAndPointFormatter( // FAZA 3 formater
            Color.rgb(0, 220, 0), // line color
            Color.rgb(0, 150, 0), // point color
            null);
    line3mFill = new Paint();
    line3mFill.setAlpha(100);
    line3mFill.setShader(
            new LinearGradient(0, 0, 0, 200, Color.rgb(0, 200, 0), Color.BLACK, Shader.TileMode.MIRROR));
    series3mFormat.getLinePaint().setStrokeWidth(3);
    // series3mFormat.getVertexPaint().setStrokeWidth(0);
    series3mFormat.setFillPaint(line3mFill);

    series4mFormat = new LineAndPointFormatter(Color.rgb(0, 140, 220), // line
            Color.rgb(0, 120, 190), // point color
            null);
    line4mFill = new Paint();
    line4mFill.setAlpha(190);
    line4mFill.setShader(
            new LinearGradient(0, 0, 0, 200, Color.rgb(0, 140, 220), Color.BLACK, Shader.TileMode.MIRROR));
    series4mFormat.getLinePaint().setStrokeWidth(5);
    series4mFormat.setFillPaint(line4mFill);

    make_graph_pretty(Plot1); // All formating of the graph goes into
    // seperate method
    make_graph_pretty(Plot2);

    Napis.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (delta_mode) {
                napis_delta.setVisibility(TextView.INVISIBLE);
                delta_mode = false;
                delta_value = 0;
                // Plot1.removeMarker(marker1);
            } else {
                napis_delta.setVisibility(TextView.VISIBLE);
                delta_mode = true;
                try {
                    delta_value = seriesSUM123linkedlist.getLast().intValue();
                    // marker1 = new YValueMarker(delta_value, "" + (char)
                    // 0x0394, new
                    // XPositionMetric(3,XLayoutStyle.ABSOLUTE_FROM_LEFT),
                    // Color.GREEN, Color.WHITE);
                    // Plot1.addMarker(marker1);
                } catch (NullPointerException e) {
                    delta_value = 0;
                }
            }
            ;

        }
    });

    W.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Napis01.setText("restarted");
            thread1_running = true;
            thread2_running = true;

        }
    });

    Plot1.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            /*
             * Change the switch block to an increment and one 
             * if statement. Also, avoid magic numbers
             */
            plot1_mode++;
            if (plot1_mode > MAX_PLOT1_CLICK)
                plot1_mode = 0;

            switch (sensor_number) {
            case 1:
            case 2:
            case 3: {
                switch (plot1_mode) {
                case 0: {
                    Plot1.setTitle("Power (W) - last minute -  stacked");
                    Plot1.removeSeries(series1m);
                    Plot1.addSeries(series2m, series2mFormat);
                    Plot1.addSeries(series3m, series3mFormat);
                    Plot1.addSeries(series1m, series1mFormat);
                    Plot1.redraw();
                    break;
                }
                case 1: {
                    Plot1.setTitle("Power (W) - last minute -  with details");
                    Plot1.redraw(); // update title even if series are not updating (like in set prefs)

                    setDetailsVisibility(true); // show details
                    break;
                }
                case 2: {
                    Plot1.setTitle("Power (W) - last minute -  Total only");
                    Plot1.removeSeries(series2m);
                    Plot1.removeSeries(series1m);
                    Plot1.redraw();

                    setDetailsVisibility(false); // hide details
                    break;
                }
                }
                break;
            }
            case 4: {
                switch (plot1_mode) {
                case 0: {
                    Plot1.setTitle("Power (W) - last minute -  stacked");
                    Plot1.redraw();
                    break;
                }
                case 1: {
                    Plot1.setTitle("Power (W) - last minute -  with details");
                    Plot1.redraw(); // This update plot title even if the series update is stoped

                    setDetailsVisibility(true); // show details
                    break;
                }
                case 2: {
                    Plot1.setTitle("Power (W) - last minute ");
                    // Plot1.removeSeries(series2m);
                    // Plot1.removeSeries(series1m);
                    Plot1.redraw();

                    setDetailsVisibility(false); // hide details
                    break;
                }
                }
                break;
            }
            }

        }
    });

    series1m.setModel(series1linkedlist, SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED);
    series2m.setModel(series2linkedlist, SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED);
    series3m.setModel(series3linkedlist, SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED);

    Plot1.addSeries(series2m, series2mFormat);
    Plot1.addSeries(series3m, series3mFormat);
    Plot1.addSeries(series1m, series1mFormat);

    series_p2_1.setModel(series_day1_linkedlist, SimpleXYSeries.ArrayFormat.XY_VALS_INTERLEAVED);
    Plot2.addSeries(series_p2_1, series4mFormat);

    if (skip_initial_sensor_checks) {
        thread_updater1s.start();
        thread_updater2.start();
    } else {
        run_network_token_test();
        // Alert dialog when application starts
        new AlertDialog.Builder(this).setTitle(R.string.nw_chk_results).setMessage(network_checks_results)
                .setIcon(android.R.drawable.ic_menu_agenda)
                .setPositiveButton(R.string.run_both_th_local_remote, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        thread_updater1s.start();
                        thread_updater2.start();
                    }
                }).setNeutralButton(R.string.run_just_local_th, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        thread_updater1s.start();
                        Plot2.setTitle(getString(R.string.disabled));
                        tv_today_kwh.setVisibility(TextView.INVISIBLE);
                        tv_today_cost.setVisibility(TextView.INVISIBLE);
                        tv_today_percent.setVisibility(TextView.INVISIBLE);
                        tv_today_avg.setVisibility(TextView.INVISIBLE);
                        tv_week_kwh.setVisibility(TextView.INVISIBLE);
                        tv_week_avg.setVisibility(TextView.INVISIBLE);
                        tv_week_cost.setVisibility(TextView.INVISIBLE);
                        tv_week_percent.setVisibility(TextView.INVISIBLE);
                        tv_month_kwh.setVisibility(TextView.INVISIBLE);
                        tv_month_avg.setVisibility(TextView.INVISIBLE);
                        tv_month_cost.setVisibility(TextView.INVISIBLE);
                        tv_month_percent.setVisibility(TextView.INVISIBLE);
                    }
                })
                .setNegativeButton(R.string.let_me_fix_the_prefs_first, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
    } // end of if for skip initial tests

}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Gets the device screen size in pixels.
 * //from w  w w. j a  v  a2 s . co  m
 * @param context
 * @return
 */
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public static Point device_screenSize(Context context) {
    Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    final Point size = new Point();
    try {
        display.getSize(size);
    } catch (NoSuchMethodError ignore) { // Older device
        size.x = display.getWidth();
        size.y = display.getHeight();
    }

    return size;
}

From source file:com.entradahealth.entrada.android.app.personal.activities.job_list.JobListActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = this;
    application = (EntradaApplication) EntradaApplication.getAppContext();
    sp = getSharedPreferences("Entrada", Context.MODE_WORLD_READABLE);
    if (sp.getBoolean("SECURE_MSG", true))
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE);
    else/*from   w w w .j  av a2s . c  om*/
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_SECURE);
    final JobListActivity thisActivity = this;

    //Custom view as action bar
    LayoutInflater mInflater = LayoutInflater.from(this);
    View mCustomView = mInflater.inflate(R.layout.acbar_job_list, null);
    tvAcTitle = (TextView) mCustomView.findViewById(R.id.tvAcTitle);
    ivInbox = (ImageView) mCustomView.findViewById(R.id.ivInbox);
    ivAddJob = (ImageView) mCustomView.findViewById(R.id.ivAddJob);
    ivSync = (ImageView) mCustomView.findViewById(R.id.ivSync);
    ivSchedule = (ImageView) mCustomView.findViewById(R.id.ivSchedule);
    tvAcTitle.setText(BundleKeys.title);

    //Sample icon badger on Action bar item
    badge = new BadgeView(this, ivInbox);
    if (BundleKeys.fromSecureMessaging || !application.isJobListEnabled()) {
        startActivity(new Intent(JobListActivity.this, SecureMessaging.class));
        finish();
    }

    ivInbox.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            startActivity(new Intent(JobListActivity.this, SecureMessaging.class));
            finish();
        }
    });

    ivAddJob.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent addJobIntent = new Intent(JobListActivity.this, AddJobActivity.class);
            addJobIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(addJobIntent);
            finish();
        }
    });

    ivSync.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            ns = new NetworkState(getApplicationContext());
            isConnected = ns.isConnectingToInternet();
            if (isConnected) {
                running = false;
                ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
                for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
                    if ("com.entradahealth.entrada.android.app.personal.sync.SyncService"
                            .equals(service.service.getClassName())
                            || "com.entradahealth.entrada.android.app.personal.sync.DictationUploadService"
                                    .equals(service.service.getClassName())) {
                        running = true;
                    }
                }

                if (!running) {
                    etSearch.setText(null);
                    if (!isFinishing()) {

                        //retryUploads();
                        boolean canSync = true;
                        try {
                            List<Job> jobs = AndroidState.getInstance().getUserState()
                                    .getProvider(currentAccount).getJobs();

                            for (Job j : jobs) {
                                if (j.isPending()) {
                                    canSync = false;
                                    UserState state = AndroidState.getInstance().getUserState();
                                    Log.e("", "onOptionsItemSelected-syncMenuItem--" + j.id);
                                    DictationUploadService.startUpload(JobListActivity.this, state,
                                            currentAccount, j);
                                }
                            }
                        } catch (Exception ex) {
                            ACRA.getErrorReporter().handleSilentException(ex);
                            canSync = false;
                        }

                        if (!canSync) {
                            Toast.makeText(JobListActivity.this,
                                    "Please wait for all uploads to complete before syncing.",
                                    Toast.LENGTH_SHORT).show();

                        } else {
                            rlSyncError.setVisibility(View.GONE);
                            rlUpdated.setVisibility(View.INVISIBLE);
                            tvUpdating.setVisibility(View.VISIBLE);

                            Intent i = new Intent(JobListActivity.this, SyncService.class);
                            startService(i);

                        }

                        isSyncing = true;
                        BundleKeys.SYNC_FOR_ACC = currentAccount.getDisplayName();
                        //BundleKeys.SYNC_FOR_CLINIC = currentAccount.getClinicCode(); 

                        /*task1 = buildMinderTask();
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                           task1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                        } else {
                           task1.execute();
                        }*/

                    }
                } else {
                    if (!isResumed)
                        Toast.makeText(JobListActivity.this,
                                "Please wait for all uploads to complete before syncing.", Toast.LENGTH_SHORT)
                                .show();
                }
                isResumed = false;
            } else {
                rlSyncError.setVisibility(View.VISIBLE);
                rlUpdated.setVisibility(View.GONE);
                tvUpdating.setVisibility(View.GONE);
            }

        }
    });

    ivSchedule.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(JobListActivity.this, ScheduleActivity.class));
            finish();
        }
    });

    getActionBar().setCustomView(mCustomView);
    getActionBar().setDisplayShowCustomEnabled(true);

    //ActionBar ab = getActionBar();
    //ab.setTitle(BundleKeys.title);
    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    registerReceiver(broadcastReceiver, new IntentFilter("CONNECTIVITY_CHANGED"));
    jobIds = new ArrayList<Long>();
    BundleKeys.fromImageDisplay = false;
    BundleKeys.fromCaputreImages = false;
    BundleKeys.fromSecureMessaging = false;

    /*Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
         @Override
         public void uncaughtException(Thread paramThread, Throwable paramThrowable) {
       Log.e("Job-List-Activity","Uncaught-Exception");
       System.exit(2);
         }
     });*/

    setBehindContentView(R.layout.job_list_sliding_menu);
    tvListTitle = (TextView) findViewById(R.id.tvListTitle);
    tvListTitle.setText("Jobs");
    lvSliding = (ListView) findViewById(R.id.lvSlidingMenu);
    lvSliding.setBackgroundColor(Color.parseColor("#262b38"));

    // Get screen width and set sliding width to 3/4
    Display display = getWindowManager().getDefaultDisplay();
    int width = display.getWidth();
    int req_width = width * 3 / 4;

    slidingMenu = getSlidingMenu();
    slidingMenu.setFadeEnabled(true);
    slidingMenu.setFadeDegree(0.35f);
    slidingMenu.setBehindWidth(req_width);
    slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);

    setContentView(R.layout.job_list);

    ivDrawer = (ImageView) findViewById(R.id.ivDrawer);
    ivDrawer.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            slidingMenu.toggle();
            // JobCountTask();
        }
    });

    rlUpdated = (RelativeLayout) findViewById(R.id.rlDateTime);
    rlSyncError = (RelativeLayout) findViewById(R.id.rlSyncError);
    rlSyncError.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            AlertDialog.Builder builder = new AlertDialog.Builder(JobListActivity.this);
            builder.setTitle(R.string.title_sync_error);
            builder.setMessage(R.string.msg_sync_error);
            builder.setPositiveButton("OK", null);
            dgSyncError = builder.create();
            dgSyncError.show();
        }
    });

    tvDate = (TextView) findViewById(R.id.tvDate);
    tvTime = (TextView) findViewById(R.id.tvTime);
    tvUpdating = (TextView) findViewById(R.id.lblUpdating);
    tvSyncFailed = (TextView) findViewById(R.id.lblSyncError);

    handler = new Handler();
    handler.postDelayed(runnable, BundleKeys.mins_to_sync * 60 * 1000);
    handler.postDelayed(runnable_logs, 5 * 60 * 1000);

    jobListView = (ListView) findViewById(R.id.jobListView);
    jobListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    jobListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
            // TODO: evaluate whether to save search text in
            // UserState to repopulate on back press.

            itemClicked = true;
            if (searchTask != null) {
                searchTask.cancel(true);
            }

            Log.d("", "-- Job ItemClick --");
            List<Long> jobList = thisActivity.getJobIdList();
            Preconditions.checkNotNull(jobList, "null List<Job> when adapter view clicked.");
            Job job = AndroidState.getInstance().getUserState().getProvider(currentAccount)
                    .getJob(jobList.get(position));
            if (job != null) {
                Preconditions.checkNotNull(job, "null item in List<Job> when adapter view clicked.");

                if (job.isFlagSet(Job.Flags.UPLOAD_COMPLETED) || job.isFlagSet(Job.Flags.UPLOAD_IN_PROGRESS)
                        || (job.isFlagSet(Job.Flags.UPLOAD_PENDING) && BundleKeys.which == 6))

                {
                    Toast.makeText(thisActivity, "Cannot open a completed dictation.", Toast.LENGTH_SHORT)
                            .show();
                    return;
                } else if (job.isFlagSet(Job.Flags.LOCALLY_DELETED)) {
                    return;
                }

                Intent intent = new Intent(thisActivity, JobDisplayActivity.class);
                Bundle b = new Bundle();
                if (!job.isFlagSet(Flags.HOLD))
                    job = job.setFlag(Flags.IS_FIRST);
                else
                    job = job.clearFlag(Flags.IS_FIRST);
                try {
                    AndroidState.getInstance().getUserState().getProvider(currentAccount).updateJob(job);
                } catch (DomainObjectWriteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                b.putBoolean("isFirst", true);
                b.putBoolean("isFromList", true);
                b.putBoolean("isNew", false);
                b.putLong(BundleKeys.SELECTED_JOB, job.id);
                b.putString(BundleKeys.SELECTED_JOB_ACCOUNT, currentAccount.getName());
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtras(b);
                thisActivity.startActivity(intent);
                thisActivity.finish();
            }
        }

    });

    jobListView.setMultiChoiceModeListener(new JobListMultiChoiceModeListener(this));

    slidingMenu.setOnOpenListener(new OnOpenListener() {

        @Override
        public void onOpen() {
            // TODO Auto-generated method stub

            openSlide();
        }
    });

    lvSliding.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int pos, long arg3) {
            // TODO Auto-generated method stub

            switch (pos) {

            case 1:
                //getActionBar().setTitle("Today's Jobs");
                tvAcTitle.setText("Today's Jobs");
                BundleKeys.title = "Today's Jobs";
                BundleKeys.which = 1;
                //menuItem = j_Menu.findItem(R.id.addJobMenuItem);
                //menuItem.setVisible(true);
                ivAddJob.setVisibility(View.VISIBLE);
                jobListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
                etSearch.setText("");
                break;
            case 2:
                //getActionBar().setTitle("Tomorrow's Jobs");
                tvAcTitle.setText("Tomorrow's Jobs");
                BundleKeys.which = 2;
                BundleKeys.title = "Tomorrow's Jobs";
                //menuItem = j_Menu.findItem(R.id.addJobMenuItem);
                //menuItem.setVisible(true);
                ivAddJob.setVisibility(View.VISIBLE);
                jobListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
                etSearch.setText("");
                break;
            case 3:
                //getActionBar().setTitle("Stat Jobs");
                tvAcTitle.setText("Stat Jobs");
                BundleKeys.which = 3;
                BundleKeys.title = "Stat Jobs";
                //menuItem = j_Menu.findItem(R.id.addJobMenuItem);
                //menuItem.setVisible(true);
                ivAddJob.setVisibility(View.VISIBLE);
                jobListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
                etSearch.setText("");
                break;
            case 4:
                //getActionBar().setTitle("All Jobs");
                tvAcTitle.setText("All Jobs");
                BundleKeys.which = 4;
                BundleKeys.title = "All Jobs";
                //menuItem = j_Menu.findItem(R.id.addJobMenuItem);
                //menuItem.setVisible(true);
                ivAddJob.setVisibility(View.VISIBLE);
                jobListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
                etSearch.setText("");
                break;
            case 6:
                //getActionBar().setTitle("Hold Jobs");
                tvAcTitle.setText("Hold Jobs");
                BundleKeys.which = 5;
                BundleKeys.title = "Hold Jobs";
                //menuItem = j_Menu.findItem(R.id.addJobMenuItem);
                //menuItem.setVisible(true);
                ivAddJob.setVisibility(View.VISIBLE);
                jobListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
                etSearch.setText("");
                break;
            case 7:
                //getActionBar().setTitle("Deleted Jobs");
                tvAcTitle.setText("Deleted Jobs");
                BundleKeys.which = 7;
                BundleKeys.title = "Deleted Jobs";
                // Hide "Add Job" menu item
                //menuItem = j_Menu.findItem(R.id.addJobMenuItem);
                //menuItem.setVisible(false);
                ivAddJob.setVisibility(View.GONE);
                jobListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
                etSearch.setText("");
                break;
            case 8:
                //getActionBar().setTitle("Completed Jobs");
                tvAcTitle.setText("Completed Jobs");
                BundleKeys.which = 6;
                BundleKeys.title = "Completed Jobs";
                // Hide "Add Job" menu item
                //menuItem = j_Menu.findItem(R.id.addJobMenuItem);
                //menuItem.setVisible(false);
                ivAddJob.setVisibility(View.GONE);
                jobListView.setChoiceMode(ListView.CHOICE_MODE_NONE);
                etSearch.setText("");
                break;

            case 10:
                isSetting = true;
                //getActionBar().setTitle("Settings");
                tvAcTitle.setText("Settings Jobs");
                startActivity(new Intent(JobListActivity.this, EntradaSettings.class)
                        .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                finish();
                break;

            case 11:
                // Check if there are any held jobs or any uploads in
                // progress
                boolean isHeld = true, isPending = true;
                try {
                    List<Job> jobs = AndroidState.getInstance().getUserState().getProvider(currentAccount)
                            .getJobs();

                    for (Job j : jobs) {
                        if (j.isPending())
                            isPending = false;
                        if (j.isFlagSet(Job.Flags.HOLD))
                            isHeld = false;

                    }
                } catch (Exception ex) {
                    ACRA.getErrorReporter().handleSilentException(ex);
                    isPending = false;
                    isHeld = false;
                }
                if (SyncService.isRunning()) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(JobListActivity.this);
                    builder.setTitle(R.string.del_acc_err_title);
                    builder.setMessage(R.string.manage_q_upload_error);
                    builder.setPositiveButton("OK", null);
                    builder.setCancelable(true);
                    dgManageQ = builder.create();
                    dgManageQ.show();
                } else if (isPending && isHeld) {
                    Intent qIntent = new Intent(JobListActivity.this, ManageQueuesActivity.class);
                    qIntent.putExtra("from_settings", false);
                    qIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(qIntent);
                    finish();
                } else if (!isHeld) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(JobListActivity.this);
                    builder.setTitle(R.string.del_acc_err_title);
                    builder.setMessage(R.string.manage_q_hold_error);
                    builder.setPositiveButton("OK", null);
                    builder.setCancelable(true);
                    dgManageQ = builder.create();
                    dgManageQ.show();
                } else if (!isPending) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(JobListActivity.this);
                    builder.setTitle(R.string.del_acc_err_title);
                    builder.setMessage(R.string.manage_q_upload_error);
                    builder.setPositiveButton("OK", null);
                    builder.setCancelable(true);
                    dgManageQ = builder.create();
                    dgManageQ.show();
                }

                break;

            default:
                //getActionBar().setTitle("Today's Jobs");
                tvAcTitle.setText("Today's Jobs");
                BundleKeys.title = "Today's Jobs";
                BundleKeys.which = 1;
                //menuItem = j_Menu.findItem(R.id.addJobMenuItem);
                //menuItem.setVisible(true);
                ivAddJob.setVisibility(View.VISIBLE);
                jobListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
            }
            Log.e(LOG_NAME, Integer.toString(BundleKeys.which) + " - " + BundleKeys.title);
            isSync = false;
            slidingMenu.toggle(true);
            /*
             * Log.e("isSetting", Boolean.toString(isSetting));
             * if(BundleKeys.which != 8 && BundleKeys.which != 9 &&
             * !isSetting) etSearch.setText("");
             */
        }

    });

    rlSearch = (RelativeLayout) findViewById(R.id.rlSearch);

    etSearch = (EditText) findViewById(R.id.etSearch);
    etSearch.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            //launchSearchTask();

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            launchSearchTask();
        }
    });

    GetResourcesTask task = new GetResourcesTask();
    task.execute();

}

From source file:com.farmerbb.taskbar.activity.ContextMenuActivity.java

@SuppressLint("RtlHardcoded")
@SuppressWarnings("deprecation")
@Override//from ww w. jav  a2 s  . co  m
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);

    LocalBroadcastManager.getInstance(this)
            .sendBroadcast(new Intent("com.farmerbb.taskbar.CONTEXT_MENU_APPEARING"));

    boolean isNonAppMenu = !getIntent().hasExtra("package_name") && !getIntent().hasExtra("app_name");
    showStartMenu = getIntent().getBooleanExtra("launched_from_start_menu", false);
    isStartButton = isNonAppMenu && getIntent().getBooleanExtra("is_start_button", false);
    isOverflowMenu = isNonAppMenu && getIntent().getBooleanExtra("is_overflow_menu", false);
    contextMenuFix = getIntent().hasExtra("context_menu_fix");

    // Determine where to position the dialog on screen
    WindowManager.LayoutParams params = getWindow().getAttributes();
    DisplayManager dm = (DisplayManager) getSystemService(DISPLAY_SERVICE);
    Display display = dm.getDisplay(Display.DEFAULT_DISPLAY);

    int statusBarHeight = 0;
    int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
    if (resourceId > 0)
        statusBarHeight = getResources().getDimensionPixelSize(resourceId);

    if (showStartMenu) {
        int x = getIntent().getIntExtra("x", 0);
        int y = getIntent().getIntExtra("y", 0);
        int offset = getResources().getDimensionPixelSize(
                isOverflowMenu ? R.dimen.context_menu_offset_overflow : R.dimen.context_menu_offset);

        switch (U.getTaskbarPosition(this)) {
        case "bottom_left":
        case "bottom_vertical_left":
            params.gravity = Gravity.BOTTOM | Gravity.LEFT;
            params.x = x;
            params.y = display.getHeight() - y - offset;
            break;
        case "bottom_right":
        case "bottom_vertical_right":
            params.gravity = Gravity.BOTTOM | Gravity.LEFT;
            params.x = x - getResources().getDimensionPixelSize(R.dimen.context_menu_width) + offset + offset;
            params.y = display.getHeight() - y - offset;
            break;
        case "top_left":
        case "top_vertical_left":
            params.gravity = Gravity.TOP | Gravity.LEFT;
            params.x = x;
            params.y = y - offset + statusBarHeight;
            break;
        case "top_right":
        case "top_vertical_right":
            params.gravity = Gravity.TOP | Gravity.LEFT;
            params.x = x - getResources().getDimensionPixelSize(R.dimen.context_menu_width) + offset + offset;
            params.y = y - offset + statusBarHeight;
            break;
        }
    } else {
        LocalBroadcastManager.getInstance(this)
                .sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));

        int x = getIntent().getIntExtra("x", display.getWidth());
        int y = getIntent().getIntExtra("y", display.getHeight());
        int offset = getResources().getDimensionPixelSize(R.dimen.icon_size);

        switch (U.getTaskbarPosition(this)) {
        case "bottom_left":
            params.gravity = Gravity.BOTTOM | Gravity.LEFT;
            params.x = isStartButton ? 0 : x;
            params.y = offset;
            break;
        case "bottom_vertical_left":
            params.gravity = Gravity.BOTTOM | Gravity.LEFT;
            params.x = offset;
            params.y = display.getHeight() - y - (isStartButton ? 0 : offset);
            break;
        case "bottom_right":
            params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
            params.x = display.getWidth() - x;
            params.y = offset;
            break;
        case "bottom_vertical_right":
            params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
            params.x = offset;
            params.y = display.getHeight() - y - (isStartButton ? 0 : offset);
            break;
        case "top_left":
            params.gravity = Gravity.TOP | Gravity.LEFT;
            params.x = isStartButton ? 0 : x;
            params.y = offset;
            break;
        case "top_vertical_left":
            params.gravity = Gravity.TOP | Gravity.LEFT;
            params.x = offset;
            params.y = isStartButton ? 0 : y - statusBarHeight;
            break;
        case "top_right":
            params.gravity = Gravity.TOP | Gravity.RIGHT;
            params.x = display.getWidth() - x;
            params.y = offset;
            break;
        case "top_vertical_right":
            params.gravity = Gravity.TOP | Gravity.RIGHT;
            params.x = offset;
            params.y = isStartButton ? 0 : y - statusBarHeight;
            break;
        }
    }

    params.width = getResources().getDimensionPixelSize(R.dimen.context_menu_width);
    params.dimAmount = 0;

    getWindow().setAttributes(params);

    View view = findViewById(android.R.id.list);
    if (view != null)
        view.setPadding(0, 0, 0, 0);

    generateMenu();

    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.farmerbb.taskbar.START_MENU_APPEARING");
    intentFilter.addAction("com.farmerbb.taskbar.DASHBOARD_APPEARING");

    LocalBroadcastManager.getInstance(this).registerReceiver(finishReceiver, intentFilter);
}

From source file:com.plusot.senselib.SenseMain.java

private void adjustViews() {
    vgs = new ViewGroup[4];
    vgs[0] = (ViewGroup) findViewById(R.id.double1);
    vgs[1] = (ViewGroup) findViewById(R.id.double2);
    vgs[2] = (ViewGroup) findViewById(R.id.double3);
    vgs[3] = (ViewGroup) findViewById(R.id.double4);
    int devider = 1;
    if (this.viewsAdded <= 4) {
        if (map == null) {
            if (vgs[3].getChildCount() == 0 && vgs[1].getChildCount() == 2) {
                View view = vgs[1].getChildAt(1);
                vgs[1].removeView(view);
                vgs[3].addView(view);// ww  w.  j  a v a  2 s .co m
            }
            if (vgs[2].getChildCount() == 0 && vgs[0].getChildCount() == 2) {
                View view = vgs[0].getChildAt(1);
                vgs[0].removeView(view);
                vgs[2].addView(view);
            }
        } else {
            if (vgs[3].getChildCount() == 1 && vgs[1].getChildCount() == 1) {
                View view = vgs[3].getChildAt(0);
                vgs[3].removeView(view);
                vgs[1].addView(view);
            }
            if (vgs[2].getChildCount() == 1 && vgs[0].getChildCount() == 1) {
                View view = vgs[2].getChildAt(0);
                vgs[2].removeView(view);
                vgs[0].addView(view);
            }
        }
    }
    for (int i = 0; i < 4; i++) {
        if (vgs[i].getChildCount() > 0) {
            devider = i + 1;
            vgs[i].setVisibility(View.VISIBLE);
        } else
            vgs[i].setVisibility(View.GONE);
    }
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.MATCH_PARENT, 1.0f / devider);
    for (int i = 0; i < 4; i++)
        vgs[i].setLayoutParams(params);

    Display display = getWindowManager().getDefaultDisplay();
    @SuppressWarnings("deprecation")
    int w = display.getWidth();
    @SuppressWarnings("deprecation")
    int h = display.getHeight();
    //LLog.d(Globals.TAG,  CLASSTAG + " Size = " + w + " x " + h);

    for (int i = 0; i < 8; i++) {
        if (map == null) {
            View view = findViewById(i + VIEW_ID_BASE);
            if (view == null)
                continue;
            params = (LinearLayout.LayoutParams) view.getLayoutParams();
            params.setMargins(1, 1, 1, 1);
            view.setBackgroundResource(R.drawable.round_border);
            view.setLayoutParams(params);
        } else {

            int x = w / 10;
            if (w < 500)
                x = w / 40;
            int y = h / 6;
            switch (devider) {
            case 1:
                y = h / 6 + h / 2;
                break;
            case 2:
                y = h / 6;
                break;
            case 3:
                y = h / 8;
                break;
            case 4:
                y = h / 10;
                break;
            }
            View view = null;
            switch (i) {
            case 0:
                view = vgs[0].getChildAt(0);
                if (view == null)
                    break;
                params = (LinearLayout.LayoutParams) view.getLayoutParams();
                if (vgs[0].getChildCount() == 1)
                    params.setMargins(0, 0, 0, y);
                else
                    params.setMargins(0, 0, x, y);
                break;
            case 1:
                view = vgs[0].getChildAt(1);
                if (view == null)
                    break;
                params = (LinearLayout.LayoutParams) view.getLayoutParams();
                params.setMargins(x, 0, 0, y);
                break;
            case 2:
                view = vgs[1].getChildAt(0);

                if (view == null)
                    break;
                params = (LinearLayout.LayoutParams) view.getLayoutParams();
                if (devider > 2) {
                    if (vgs[1].getChildCount() == 1)
                        params.setMargins(0, y, x + w / 2, 0);
                    else
                        params.setMargins(0, y / 2, x, y / 2);
                } else if (vgs[1].getChildCount() == 1)
                    params.setMargins(0, y, 0, 0);
                else
                    params.setMargins(0, y, x, 0);
                break;
            case 3:
                view = vgs[1].getChildAt(1);
                if (view == null)
                    break;
                params = (LinearLayout.LayoutParams) view.getLayoutParams();
                if (devider > 2)
                    params.setMargins(x, y / 2, 0, y / 2);
                else
                    params.setMargins(x, y, 0, 0);
                break;
            case 4:
                view = vgs[2].getChildAt(0);
                if (view == null)
                    break;
                params = (LinearLayout.LayoutParams) view.getLayoutParams();
                if (devider > 3) {
                    if (vgs[2].getChildCount() == 1)
                        params.setMargins(0, y, x + w / 2, 0);
                    else
                        params.setMargins(0, y / 2, x, y / 2);
                } else if (vgs[2].getChildCount() == 1)
                    params.setMargins(0, y, 0, 0);
                else
                    params.setMargins(0, y, x, 0);
                break;
            case 5:
                view = vgs[2].getChildAt(1);
                if (view == null)
                    break;
                params = (LinearLayout.LayoutParams) view.getLayoutParams();
                if (devider > 3)
                    params.setMargins(x, y / 2, 0, y / 2);
                else
                    params.setMargins(x, y, 0, 0);
                break;
            case 6:
                view = vgs[3].getChildAt(0);
                if (view == null)
                    break;
                params = (LinearLayout.LayoutParams) view.getLayoutParams();
                if (vgs[3].getChildCount() == 1)
                    params.setMargins(0, y, 0, 0);
                else
                    params.setMargins(0, y, x, 0);
                break;
            case 7:
                view = vgs[3].getChildAt(1);
                if (view == null)
                    break;
                params = (LinearLayout.LayoutParams) view.getLayoutParams();
                params.setMargins(x, y, 0, 0);
                break;

            }
            if (view != null) {
                view.setLayoutParams(params);
                view.setBackgroundResource(R.drawable.transparent_border);
            }
        }

        //View v = view.findViewById(R.id.graph_view_layout);
    }

}