Example usage for android.view Gravity CENTER_VERTICAL

List of usage examples for android.view Gravity CENTER_VERTICAL

Introduction

In this page you can find the example usage for android.view Gravity CENTER_VERTICAL.

Prototype

int CENTER_VERTICAL

To view the source code for android.view Gravity CENTER_VERTICAL.

Click Source Link

Document

Place object in the vertical center of its container, not changing its size.

Usage

From source file:ca.cmput301f13t03.adventure_datetime.view.FragmentView.java

public void setUpView() {
    if (_fragment == null)
        return;//  w  w  w .  ja v  a  2 s .c  o  m

    /** Layout items **/
    _filmLayout = (LinearLayout) _rootView.findViewById(R.id.filmstrip);
    _filmstrip = (HorizontalScrollView) _rootView.findViewById(R.id.filmstrip_wrapper);
    _choices = (Button) _rootView.findViewById(R.id.choices);
    _content = (TextView) _rootView.findViewById(R.id.content);

    if (_fragment.getStoryMedia() == null)
        _fragment.setStoryMedia(new ArrayList<Image>());

    /* Run on UI Thread for server stuff */
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {

            /** Programmatically set filmstrip height **/
            if (_fragment.getStoryMedia().size() > 0)
                _filmstrip.getLayoutParams().height = FILM_STRIP_SIZE;
            else
                _filmstrip.getLayoutParams().height = 0;

            _content.setText(_fragment.getStoryText());
            _filmLayout.removeAllViews();

            // 1) Create new ImageView and add to the LinearLayout
            // 2) Set appropriate Layout Params to ImageView
            // 3) Give onClickListener for going to fullscreen
            LinearLayout.LayoutParams lp;
            //for (int i = 0; i < _fragment.getStoryMedia().size(); i++) {
            for (int i = 0; i < _fragment.getStoryMedia().size(); i++) {

                ImageView li = new ImageView(getActivity());
                li.setScaleType(ScaleType.CENTER_INSIDE);
                li.setImageBitmap(_fragment.getStoryMedia().get(i).decodeBitmap());
                _filmLayout.addView(li);

                lp = (LinearLayout.LayoutParams) li.getLayoutParams();
                lp.setMargins(10, 10, 10, 10);
                lp.width = FILM_STRIP_SIZE;
                lp.height = FILM_STRIP_SIZE;
                lp.gravity = Gravity.CENTER_VERTICAL;
                li.setLayoutParams(lp);

                li.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), FullScreen_Image.class);
                        intent.putExtra(FullScreen_Image.TAG_AUTHOR, false);
                        startActivity(intent);
                    }
                });
            }

            if (_fragment.getChoices().size() > 0) {
                /** Choices **/
                final List<String> choices = new ArrayList<String>();
                for (Choice choice : _fragment.getChoices())
                    choices.add(choice.getText());
                choices.add("I'm feeling lucky.");

                _choices.setText("Actions");
                _choices.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(v.getContext()).setTitle("Actions").setCancelable(true)
                                .setItems(choices.toArray(new String[choices.size()]),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                                /** You feeling lucky, punk? **/
                                                if (which == _fragment.getChoices().size())
                                                    which = (int) (Math.random()
                                                            * _fragment.getChoices().size());

                                                Choice choice = _fragment.getChoices().get(which);

                                                Toast.makeText(FragmentView.this.getActivity(),
                                                        choice.getText(), Toast.LENGTH_LONG).show();
                                                Locator.getUserController().MakeChoice(choice);
                                            }
                                        })
                                .create().show();
                    }
                });
            } else {
                /** End of story **/
                Locator.getUserController().deleteBookmark();
                _choices.setText("The End");
                _choices.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(v.getContext()).setTitle("La Fin").setCancelable(true)
                                .setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Locator.getUserController().StartStory(_fragment.getStoryID());
                                    }
                                })
                                .setNegativeButton("Change Adventures", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (!_isEditing)
                                            getActivity().onBackPressed();
                                    }
                                }).create().show();

                    }
                });
            }
        }
    });

}

From source file:com.microsoft.mimickeralarm.ringing.ShareFragment.java

private static void drawStamp(Context context, Bitmap bitmap, String question) {
    Canvas canvas = new Canvas(bitmap);
    canvas.drawBitmap(bitmap, 0, 0, null);

    float opacity = 0.7f;
    int horizontalPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
            context.getResources().getDisplayMetrics());
    int verticalPadding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10,
            context.getResources().getDisplayMetrics());
    int textSize = 16; // defined in SP
    int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 16,
            context.getResources().getDisplayMetrics());

    LinearLayout layout = new LinearLayout(context);
    layout.setOrientation(LinearLayout.HORIZONTAL);
    layout.setBackgroundResource(R.drawable.rounded_corners);
    layout.getBackground().setAlpha((int) (opacity * 255));
    layout.setPadding(horizontalPadding, verticalPadding, horizontalPadding, verticalPadding);

    ImageView logo = new ImageView(context);
    logo.setImageDrawable(ContextCompat.getDrawable(context, R.mipmap.ic_launcher_no_bg));
    layout.addView(logo);/*from   w  w w  .  j a va  2  s. c  om*/

    TextView textView = new TextView(context);
    textView.setVisibility(View.VISIBLE);
    if (question != null) {
        textView.setText(question);
    } else {
        textView.setText("Mimicker");
    }
    textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize);
    textView.setPadding(horizontalPadding, 0, 0, 0);

    LinearLayout.LayoutParams centerInParent = new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    centerInParent.gravity = Gravity.CENTER_VERTICAL;
    layout.addView(textView, centerInParent);

    layout.measure(canvas.getWidth(), height);
    layout.layout(0, 0, layout.getMeasuredWidth(), layout.getMeasuredHeight());

    canvas.translate(horizontalPadding, (float) (canvas.getHeight() * 0.8 - height));
    float scale = Math.min(1.0f, canvas.getWidth() / 1080f);
    canvas.scale(scale, scale);
    layout.draw(canvas);
}

From source file:edu.mum.ml.group7.guessasketch.android.EasyPaint.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // it removes the title from the actionbar(more space for icons?)
    // this.getActionBar().setDisplayShowTitleEnabled(false);

    pixels5 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, getResources().getDisplayMetrics());
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    LinearLayout parent = new LinearLayout(this);

    parent.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
    parent.setOrientation(LinearLayout.VERTICAL);

    LinearLayout scrollViewParent = new LinearLayout(this);

    scrollViewParent.setLayoutParams(//ww w. ja va 2 s  .  co  m
            new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
    scrollViewParent.setOrientation(LinearLayout.HORIZONTAL);

    HorizontalScrollView predictionsHorizontalScrollView = new HorizontalScrollView(this);
    //predictionsHorizontalScrollView.setLayoutParams(new ViewGroup.LayoutParams());

    predictions = new LinearLayout(this);
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
    params.gravity = Gravity.CENTER_VERTICAL;
    predictions.setLayoutParams(params);

    predictions.setOrientation(LinearLayout.HORIZONTAL);

    resetPredictionsView(predictions, true);
    predictionsHorizontalScrollView.addView(predictions);

    saveButton = new Button(this);
    saveButton.setText("Send Feedback");

    predictionsHorizontalScrollView.setLayoutParams(
            new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 10.0f));

    saveButton.setLayoutParams(
            new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1.0f));

    saveButton.setVisibility(View.INVISIBLE);

    FrameLayout frameLayout = new FrameLayout(this);
    frameLayout
            .setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
    frameLayout.addView(saveButton);

    loader = new ProgressBar(this);
    loader.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
    loader.setIndeterminate(true);
    loader.setVisibility(ProgressBar.INVISIBLE);

    frameLayout.addView(loader);

    scrollViewParent.addView(predictionsHorizontalScrollView);
    scrollViewParent.addView(frameLayout);

    contentView = new MyView(this);
    parent.addView(scrollViewParent);
    parent.addView(contentView);

    setContentView(parent);

    otherLabelOnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Log.e("Clicked", "Other Label label '" + (String) view.getTag() + "'");
            sendScreenshot(false, feedbackType, (String) view.getTag());
        }
    };

    mPaint = new Paint();
    mPaint.setAntiAlias(true);
    mPaint.setDither(true);
    mPaint.setColor(Color.BLACK);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeJoin(Paint.Join.ROUND);
    mPaint.setStrokeCap(Paint.Cap.ROUND);
    mPaint.setStrokeWidth(DEFAULT_BRUSH_SIZE);

    // Where did these magic numbers come from? What do they mean? Can I change them? ~TheOpenSourceNinja
    // Absolutely random numbers in order to see the emboss. asd! ~Valerio
    mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);

    mBlur = new BlurMaskFilter(5, BlurMaskFilter.Blur.NORMAL);

    if (isFirstTime()) {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle(R.string.app_name);
        alert.setMessage(R.string.app_description);
        alert.setNegativeButton(R.string.continue_button, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Toast.makeText(getApplicationContext(), R.string.here_is_your_canvas, Toast.LENGTH_SHORT)
                        .show();
            }
        });

        alert.show();
    } else {
        Toast.makeText(getApplicationContext(), R.string.here_is_your_canvas, Toast.LENGTH_SHORT).show();
    }

    loadFromIntents();
}

From source file:widgets.Graphical_Info.java

@SuppressLint("HandlerLeak")
public Graphical_Info(tracerengine Trac, Activity context, int id, int dev_id, String name,
        final String state_key, String url, final String usage, int update, int widgetSize, int session_type,
        final String parameters, int place_id, String place_type, SharedPreferences params) {
    super(context, Trac, id, name, "", usage, widgetSize, session_type, place_id, place_type, mytag, container);
    this.Tracer = Trac;
    this.context = context;
    this.dev_id = dev_id;
    this.id = id;
    this.usage = usage;
    this.state_key = state_key;
    this.update = update;
    this.wname = name;
    this.url = url;
    this.myself = this;
    this.session_type = session_type;
    this.parameters = parameters;
    this.place_id = place_id;
    this.place_type = place_type;
    this.params = params;
    setOnClickListener(this);

    mytag = "Graphical_Info (" + dev_id + ")";
    metrics = getResources().getDisplayMetrics();
    //Label Text size according to the screen size
    size10 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10, metrics);
    size5 = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, metrics);

    Tracer.e(mytag, "New instance for name = " + wname + " state_key = " + state_key);
    login = params.getString("http_auth_username", null);
    password = params.getString("http_auth_password", null);

    //state key/*w w w .  j  ava2  s .  co m*/
    state_key_view = new TextView(context);
    state_key_view.setText(state_key);
    state_key_view.setTextColor(Color.parseColor("#333333"));

    //value
    value = new TextView(context);
    value.setTextSize(28);
    value.setTextColor(Color.BLACK);
    animation = new AlphaAnimation(0.0f, 1.0f);
    animation.setDuration(1000);

    if (with_graph) {

        //feature panel 2 which will contain graphic
        featurePan2 = new LinearLayout(context);
        featurePan2.setLayoutParams(
                new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
        featurePan2.setGravity(Gravity.CENTER_VERTICAL);
        featurePan2.setPadding(5, 10, 5, 10);
        //canvas
        canvas = new Graphical_Info_View(Tracer, context, params);
        canvas.dev_id = dev_id;
        canvas.state_key = state_key;
        canvas.url = url;
        canvas.update = update;

        LayoutInflater layoutInflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        featurePan2_buttons = layoutInflater.inflate(R.layout.graph_buttons, null);
        View v = null;

        v = featurePan2_buttons.findViewById(R.id.bt_prev);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_next);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_year);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_month);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_week);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.bt_day);
        if (v != null)
            v.setOnClickListener(canvas);

        v = featurePan2_buttons.findViewById(R.id.period);
        if (v != null)
            canvas.dates = (TextView) v;

        //background_stats.addView(canvas);
        featurePan2.addView(canvas);
    }

    LL_featurePan.addView(value);
    LL_infoPan.addView(state_key_view);

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 9999) {
                //Message from widgetupdate
                //state_engine send us a signal to notify value changed
                if (session == null)
                    return;

                String loc_Value = session.getValue();
                Tracer.d(mytag, "Handler receives a new value <" + loc_Value + ">");
                try {
                    float formatedValue = 0;
                    if (loc_Value != null)
                        formatedValue = Round(Float.parseFloat(loc_Value), 2);
                    try {
                        //Basilic add, number feature has a unit parameter
                        JSONObject jparam = new JSONObject(parameters.replaceAll("&quot;", "\""));
                        String test_unite = jparam.getString("unit");
                        value.setText(formatedValue + " " + test_unite);
                    } catch (JSONException e) {
                        if (state_key.equalsIgnoreCase("temperature") == true)
                            value.setText(formatedValue + " C");
                        else if (state_key.equalsIgnoreCase("pressure") == true)
                            value.setText(formatedValue + " hPa");
                        else if (state_key.equalsIgnoreCase("humidity") == true)
                            value.setText(formatedValue + " %");
                        else if (state_key.equalsIgnoreCase("percent") == true)
                            value.setText(formatedValue + " %");
                        else if (state_key.equalsIgnoreCase("visibility") == true)
                            value.setText(formatedValue + " km");
                        else if (state_key.equalsIgnoreCase("chill") == true)
                            value.setText(formatedValue + " C");
                        else if (state_key.equalsIgnoreCase("speed") == true)
                            value.setText(formatedValue + " km/h");
                        else if (state_key.equalsIgnoreCase("drewpoint") == true)
                            value.setText(formatedValue + " C");
                        else if (state_key.equalsIgnoreCase("condition-code") == true)
                            //Add try catch to avoid other case that make #1794
                            try {
                                value.setText(Graphics_Manager.Names_conditioncodes(getContext(),
                                        (int) formatedValue));
                            } catch (Exception e1) {
                                value.setText(loc_Value);
                            }
                        else
                            value.setText(loc_Value);
                    }
                    value.setAnimation(animation);
                } catch (Exception e) {
                    // It's probably a String that could'nt be converted to a float
                    Tracer.d(mytag, "Handler exception : new value <" + loc_Value + "> not numeric !");
                    try {
                        Tracer.d(mytag, "Try to get value translate from R.STRING");
                        value.setText(
                                Graphics_Manager.getStringIdentifier(getContext(), loc_Value.toLowerCase()));
                    } catch (Exception e1) {
                        Tracer.d(mytag, "Nothing in R.STRING for " + loc_Value);
                        value.setText(loc_Value);
                    }
                }
                //To have the icon colored as it has no state
                IV_img.setBackgroundResource(Graphics_Manager.Icones_Agent(usage, 2));
            } else if (msg.what == 9998) {
                // state_engine send us a signal to notify it'll die !
                Tracer.d(mytag, "state engine disappeared ===> Harakiri !");
                session = null;
                realtime = false;
                removeView(LL_background);
                myself.setVisibility(GONE);
                if (container != null) {
                    container.removeView(myself);
                    container.recomputeViewAttributes(myself);
                }
                try {
                    finalize();
                } catch (Throwable t) {
                } //kill the handler thread itself
            }
        }

    };

    //================================================================================
    /*
     * New mechanism to be notified by widgetupdate engine when our value is changed
     * 
     */
    WidgetUpdate cache_engine = WidgetUpdate.getInstance();
    if (cache_engine != null) {
        session = new Entity_client(dev_id, state_key, mytag, handler, session_type);
        if (Tracer.get_engine().subscribe(session)) {
            realtime = true; //we're connected to engine
            //each time our value change, the engine will call handler
            handler.sendEmptyMessage(9999); //Force to consider current value in session
        }

    }
    //================================================================================
    //updateTimer();   //Don't use anymore cyclic refresh....   

}

From source file:com.java2s.intents4.IntentsDemo4Activity.java

void addRow(final LinearLayout layout, String label, String hintStr, boolean addRadioGroup) {
    LinearLayout.LayoutParams rowLayoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    LinearLayout.LayoutParams editTextLayoutParams = new LinearLayout.LayoutParams(400,
            LinearLayout.LayoutParams.WRAP_CONTENT, 1);
    if (addRadioGroup) {
        editTextLayoutParams = new LinearLayout.LayoutParams(400, LinearLayout.LayoutParams.WRAP_CONTENT, 1);
    }// w w  w.  j  a v a  2s. c  om
    LinearLayout.LayoutParams buttonLayoutParams = new LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 0);

    LinearLayout row = new LinearLayout(this);
    row.setOrientation(LinearLayout.HORIZONTAL);
    row.setGravity(Gravity.CENTER_VERTICAL);

    TextView textView = new TextView(this);
    textView.setText(label);
    row.addView(textView);
    EditText editText = new EditText(this);
    editText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
    editText.setHint(hintStr);
    editText.setLayoutParams(editTextLayoutParams);
    if (!isFirstTime) {
        editText.requestFocus();
    }
    row.addView(editText);

    if (addRadioGroup) {
        LinearLayout groupLayout = new LinearLayout(this);
        groupLayout.setOrientation(LinearLayout.VERTICAL);
        groupLayout.setGravity(Gravity.CENTER_HORIZONTAL);

        RadioGroup group = new RadioGroup(this);
        group.setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT,
                RadioGroup.LayoutParams.WRAP_CONTENT));

        final Button patternButton = new Button(this);
        patternButton.setText(pathPatterns[0]);
        patternButton.setTextSize(8);
        patternButton.setLayoutParams(buttonLayoutParams);
        patternButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String patternButtonText = patternButton.getText().toString().trim();
                if (patternButtonText.equals(pathPatterns[0])) {
                    patternButton.setText(pathPatterns[1]);
                } else if (patternButtonText.equals(pathPatterns[1])) {
                    patternButton.setText(pathPatterns[2]);
                } else if (patternButtonText.equals(pathPatterns[2])) {
                    patternButton.setText(pathPatterns[0]);
                }
            }
        });
        groupLayout.addView(patternButton);
        row.addView(groupLayout);
    }
    Button button = new Button(this);
    button.setTextSize(10);
    button.setTypeface(null, Typeface.BOLD);
    button.setText("X");
    button.setTypeface(Typeface.SANS_SERIF, Typeface.BOLD);
    button.setLayoutParams(buttonLayoutParams);
    button.setOnClickListener(new OnClickListener() {
        public void onClick(View view) {
            layout.removeView((LinearLayout) view.getParent());
        }
    });
    row.addView(button);

    row.setLayoutParams(rowLayoutParams);
    layout.addView(row);
}

From source file:com.manuelpeinado.imagelayout.ImageLayout.java

public void setGravity(int newValue) {
    if (fitter != null && gravity == newValue) {
        return;//from  www  .  j  a  v  a  2  s .c om
    }
    if ((newValue & Gravity.HORIZONTAL_GRAVITY_MASK) == 0) {
        newValue |= Gravity.CENTER_HORIZONTAL;
    }
    if ((newValue & Gravity.VERTICAL_GRAVITY_MASK) == 0) {
        newValue |= Gravity.CENTER_VERTICAL;
    }
    gravity = newValue;
    rebuildFitter();
}

From source file:com.markupartist.sthlmtraveling.ui.view.TripView.java

public void updateViews() {
    this.setOrientation(VERTICAL);

    float scale = getResources().getDisplayMetrics().density;

    this.setPadding(getResources().getDimensionPixelSize(R.dimen.list_horizontal_padding),
            getResources().getDimensionPixelSize(R.dimen.list_vertical_padding),
            getResources().getDimensionPixelSize(R.dimen.list_horizontal_padding),
            getResources().getDimensionPixelSize(R.dimen.list_vertical_padding));

    LinearLayout timeStartEndLayout = new LinearLayout(getContext());
    TextView timeStartEndText = new TextView(getContext());
    timeStartEndText.setText(DateTimeUtil.routeToTimeDisplay(getContext(), trip));
    timeStartEndText.setTextColor(ContextCompat.getColor(getContext(), R.color.body_text_1));
    timeStartEndText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);

    ViewCompat.setPaddingRelative(timeStartEndText, 0, 0, 0, (int) (2 * scale));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        if (RtlUtils.isRtl(Locale.getDefault())) {
            timeStartEndText.setTextDirection(View.TEXT_DIRECTION_RTL);
        }//from  ww  w.j  ava2  s  . c om
    }

    // Check if we have Realtime for start and or end.
    boolean hasRealtime = false;
    Pair<Date, RealTimeState> transitTime = trip.departsAt(true);
    if (transitTime.second != RealTimeState.NOT_SET) {
        hasRealtime = true;
    } else {
        transitTime = trip.arrivesAt(true);
        if (transitTime.second != RealTimeState.NOT_SET) {
            hasRealtime = true;
        }
    }
    //        if (hasRealtime) {
    //            ImageView liveDrawable = new ImageView(getContext());
    //            liveDrawable.setImageResource(R.drawable.ic_live);
    //            ViewCompat.setPaddingRelative(liveDrawable, 0, (int) (2 * scale), (int) (4 * scale), 0);
    //            timeStartEndLayout.addView(liveDrawable);
    //
    //            AlphaAnimation animation1 = new AlphaAnimation(0.4f, 1.0f);
    //            animation1.setDuration(600);
    //            animation1.setRepeatMode(Animation.REVERSE);
    //            animation1.setRepeatCount(Animation.INFINITE);
    //
    //            liveDrawable.startAnimation(animation1);
    //        }

    timeStartEndLayout.addView(timeStartEndText);

    LinearLayout startAndEndPointLayout = new LinearLayout(getContext());
    TextView startAndEndPoint = new TextView(getContext());
    BidiFormatter bidiFormatter = BidiFormatter.getInstance(RtlUtils.isRtl(Locale.getDefault()));
    startAndEndPoint.setText(String.format("%s  %s", bidiFormatter.unicodeWrap(trip.fromStop().getName()),
            bidiFormatter.unicodeWrap(trip.toStop().getName())));

    startAndEndPoint.setTextColor(getResources().getColor(R.color.body_text_1)); // Dark gray
    startAndEndPoint.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        if (RtlUtils.isRtl(Locale.getDefault())) {
            startAndEndPoint.setTextDirection(View.TEXT_DIRECTION_RTL);
        }
    }
    ViewCompat.setPaddingRelative(startAndEndPoint, 0, (int) (4 * scale), 0, (int) (4 * scale));
    startAndEndPointLayout.addView(startAndEndPoint);

    RelativeLayout timeLayout = new RelativeLayout(getContext());

    LinearLayout routeChanges = new LinearLayout(getContext());
    routeChanges.setGravity(Gravity.CENTER_VERTICAL);

    LinearLayout.LayoutParams changesLayoutParams = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
            LayoutParams.MATCH_PARENT);
    changesLayoutParams.gravity = Gravity.CENTER_VERTICAL;

    if (trip.hasAlertsOrNotes()) {
        ImageView warning = new ImageView(getContext());
        warning.setImageResource(R.drawable.ic_trip_deviation);
        ViewCompat.setPaddingRelative(warning, 0, (int) (2 * scale), (int) (4 * scale), 0);
        routeChanges.addView(warning);
    }

    int currentTransportCount = 1;
    int transportCount = trip.getLegs().size();
    for (Leg leg : trip.getLegs()) {
        if (!leg.isTransit() && transportCount > 3) {
            if (leg.getDistance() < 150) {
                continue;
            }
        }
        if (currentTransportCount > 1 && transportCount >= currentTransportCount) {
            ImageView separator = new ImageView(getContext());
            separator.setImageResource(R.drawable.transport_separator);
            ViewCompat.setPaddingRelative(separator, 0, 0, (int) (2 * scale), 0);
            separator.setLayoutParams(changesLayoutParams);
            routeChanges.addView(separator);
            if (RtlUtils.isRtl(Locale.getDefault())) {
                ViewCompat.setScaleX(separator, -1f);
            }
        }

        ImageView changeImageView = new ImageView(getContext());
        Drawable transportDrawable = LegUtil.getTransportDrawable(getContext(), leg);
        changeImageView.setImageDrawable(transportDrawable);
        if (RtlUtils.isRtl(Locale.getDefault())) {
            ViewCompat.setScaleX(changeImageView, -1f);
        }
        ViewCompat.setPaddingRelative(changeImageView, 0, 0, 0, 0);
        changeImageView.setLayoutParams(changesLayoutParams);
        routeChanges.addView(changeImageView);

        if (currentTransportCount <= 3) {
            String lineName = leg.getRouteShortName();
            if (!TextUtils.isEmpty(lineName)) {
                TextView lineNumberView = new TextView(getContext());
                lineNumberView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 13);
                RoundedBackgroundSpan roundedBackgroundSpan = new RoundedBackgroundSpan(
                        LegUtil.getColor(getContext(), leg), Color.WHITE,
                        ViewHelper.dipsToPix(getContext().getResources(), 4));
                SpannableStringBuilder sb = new SpannableStringBuilder();
                sb.append(lineName);
                sb.append(' ');
                sb.setSpan(roundedBackgroundSpan, 0, lineName.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                lineNumberView.setText(sb);

                ViewCompat.setPaddingRelative(lineNumberView, (int) (5 * scale), (int) (1 * scale),
                        (int) (2 * scale), 0);
                lineNumberView.setLayoutParams(changesLayoutParams);
                routeChanges.addView(lineNumberView);
            }
        }

        currentTransportCount++;
    }

    TextView durationText = new TextView(getContext());
    durationText.setText(DateTimeUtil.formatDetailedDuration(getResources(), trip.getDuration() * 1000));
    durationText.setTextColor(ContextCompat.getColor(getContext(), R.color.body_text_1));
    durationText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16);
    durationText.setTypeface(Typeface.DEFAULT_BOLD);

    timeLayout.addView(routeChanges);
    timeLayout.addView(durationText);

    RelativeLayout.LayoutParams durationTextParams = (RelativeLayout.LayoutParams) durationText
            .getLayoutParams();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        durationTextParams.addRule(RelativeLayout.ALIGN_PARENT_END);
    } else {
        durationTextParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
    }
    durationText.setLayoutParams(durationTextParams);

    View divider = new View(getContext());
    ViewGroup.LayoutParams dividerParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 1);
    divider.setLayoutParams(dividerParams);

    this.addView(timeLayout);

    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) routeChanges.getLayoutParams();
    params.height = LayoutParams.MATCH_PARENT;
    params.addRule(RelativeLayout.CENTER_VERTICAL);
    routeChanges.setLayoutParams(params);

    this.addView(startAndEndPointLayout);
    this.addView(timeStartEndLayout);

    if (mShowDivider) {
        this.addView(divider);
    }
}

From source file:org.catnut.ui.HelloActivity.java

private void init() {
    setContentView(R.layout.about);//from  ww w  .j a  va  2  s. c om

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setOnPageChangeListener(new PagerListener());

    mImages = new ArrayList<Image>();

    mPagerAdapter = new Gallery();
    mViewPager.setAdapter(mPagerAdapter);
    mViewPager.setPageTransformer(true, new PageTransformer.DepthPageTransformer());
    if (mTargetFromGrid != null) {
        mImages.add(mTargetFromGrid);
        mPagerAdapter.notifyDataSetChanged();
    }

    mAbout = findViewById(R.id.about);
    mFantasyDesc = (TextView) findViewById(R.id.description);
    mFantasyDesc.setMovementMethod(LinkMovementMethod.getInstance());
    ActionBar bar = getActionBar();
    TextView about = (TextView) findViewById(R.id.about_body);
    TextView version = (TextView) findViewById(R.id.app_version);
    TextView appName = (TextView) findViewById(R.id.app_name);
    TextView weiboApp = (TextView) findViewById(R.id.weibo_app);
    weiboApp.setText(R.string.weibo_app);
    appName.setText(R.string.app_name);
    TextView appDesc = (TextView) findViewById(R.id.app_desc);
    appDesc.setText(R.string.app_desc);
    if (CatnutApp.getBoolean(R.string.pref_fantasy_say_salutation, R.bool.default_fantasy_say_salutation)) {
        version.setText(getString(R.string.about_version_template, getString(R.string.version_name)));
        int n = (int) (Math.random() * 101);
        if (0 < n && n < 35) {
            bar.setTitle(R.string.fantasy);
            about.setText(Html.fromHtml(getString(R.string.about_body)));
            about.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            bar.setTitle(R.string.fantasy);
            about.setText(Html.fromHtml(getString(R.string.salutation)));
            about.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
        }
    } else {
        mAbout.setVisibility(View.GONE);
    }

    loadImage();
    mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    if (mApp.getPreferences().getBoolean(getString(R.string.enable_analytics), true)) {
        mTracker = EasyTracker.getInstance(this);
    }
}

From source file:eu.power_switch.gui.adapter.SceneRecyclerViewAdapter.java

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
    final Scene scene = scenes.get(holder.getAdapterPosition());

    String inflaterString = Context.LAYOUT_INFLATER_SERVICE;
    LayoutInflater inflater = (LayoutInflater) fragmentActivity.getSystemService(inflaterString);

    holder.sceneName.setText(scene.getName());
    holder.sceneName.setOnClickListener(new View.OnClickListener() {
        @Override//from  ww w.j ava  2  s .  c o  m
        public void onClick(View v) {
            if (holder.linearLayoutSceneItems.getVisibility() == View.VISIBLE) {
                holder.linearLayoutSceneItems.setVisibility(View.GONE);
            } else {
                holder.linearLayoutSceneItems.setVisibility(View.VISIBLE);
            }
        }
    });
    holder.sceneName.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            if (onItemLongClickListener != null) {
                onItemLongClickListener.onItemLongClick(v, holder.getAdapterPosition());
            }
            return true;
        }
    });

    holder.buttonActivateScene.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (SmartphonePreferencesHandler.getVibrateOnButtonPress()) {
                VibrationHandler.vibrate(fragmentActivity, SmartphonePreferencesHandler.getVibrationDuration());
            }

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... params) {
                    ActionHandler.execute(fragmentActivity, scene);
                    return null;
                }
            }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
    });

    // clear previous items
    holder.linearLayoutSceneItems.removeAllViews();
    // hide setup by default
    holder.linearLayoutSceneItems.setVisibility(View.GONE);
    // add current setup
    for (final SceneItem sceneItem : scene.getSceneItems()) {
        // create a new receiverRow for our current receiver and add it
        // to our table of all devices of our current room
        // the row will contain the device name and all buttons
        LinearLayout receiverRow = new LinearLayout(fragmentActivity);
        receiverRow.setOrientation(LinearLayout.HORIZONTAL);
        holder.linearLayoutSceneItems.addView(receiverRow);

        // setup TextView to display receiver name
        AppCompatTextView receiverName = new AppCompatTextView(fragmentActivity);
        receiverName.setText(sceneItem.getReceiver().getName());
        receiverName.setTextSize(18);
        receiverName
                .setTextColor(ThemeHelper.getThemeAttrColor(fragmentActivity, android.R.attr.textColorPrimary));
        receiverName.setGravity(Gravity.CENTER_VERTICAL);
        receiverRow.addView(receiverName,
                new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1.0f));

        TableLayout buttonLayout = new TableLayout(fragmentActivity);
        receiverRow.addView(buttonLayout,
                new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        int buttonsPerRow;
        if (sceneItem.getReceiver().getButtons().size() % 3 == 0) {
            buttonsPerRow = 3;
        } else {
            buttonsPerRow = 2;
        }

        int i = 0;
        TableRow buttonRow = null;
        for (final Button button : sceneItem.getReceiver().getButtons()) {
            final android.widget.Button buttonView = (android.widget.Button) inflater
                    .inflate(R.layout.simple_button, buttonRow, false);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                buttonView.setElevation(0);
                buttonView.setStateListAnimator(null);
            }
            buttonView.setText(button.getName());
            buttonView.setEnabled(false);

            final int accentColor = ThemeHelper.getThemeAttrColor(fragmentActivity, R.attr.colorAccent);
            final int inactiveColor = ThemeHelper.getThemeAttrColor(fragmentActivity, R.attr.textColorInactive);
            if (sceneItem.getActiveButton().equals(button)) {
                buttonView.setTextColor(accentColor);
            } else {
                buttonView.setTextColor(inactiveColor);
            }

            if (i == 0 || i % buttonsPerRow == 0) {
                buttonRow = new TableRow(fragmentActivity);
                buttonRow.setLayoutParams(
                        new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
                buttonRow.addView(buttonView);
                buttonLayout.addView(buttonRow);
            } else {
                buttonRow.addView(buttonView);
            }

            i++;
        }
    }

    if (holder.getAdapterPosition() == getItemCount() - 1) {
        holder.footer.setVisibility(View.VISIBLE);
    } else {
        holder.footer.setVisibility(View.GONE);
    }
}

From source file:kookmin.cs.sympathymusiz.VideoListDemoActivity.java

/**
 * Sets up the layout programatically for the three different states. Portrait, landscape or
 * fullscreen+landscape. This has to be done programmatically because we handle the orientation
 * changes ourselves in order to get fluent fullscreen transitions, so the xml layout resources
 * do not get reloaded./* w ww .  j a v  a  2 s  . c  o m*/
 */
private void layout() {
    boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;

    //ArrayList<ArrayList<String>> list = (ArrayList<ArrayList<String>>) getIntent("exIntent"");
    listFragment.getView().setVisibility(isFullscreen ? View.GONE : View.VISIBLE);
    listFragment.setLabelVisibility(isPortrait);
    closeButton.setVisibility(isPortrait ? View.VISIBLE : View.GONE);
    if (isFullscreen) {
        videoBox.setTranslationY(0); // Reset any translation that was applied in portrait.
        setLayoutSize(videoFragment.getView(), MATCH_PARENT, MATCH_PARENT);
        setLayoutSizeAndGravity(videoBox, MATCH_PARENT, MATCH_PARENT, Gravity.TOP | Gravity.LEFT);
    } else if (isPortrait) {
        setLayoutSize(listFragment.getView(), MATCH_PARENT, MATCH_PARENT);
        setLayoutSize(videoFragment.getView(), MATCH_PARENT, WRAP_CONTENT);
        setLayoutSizeAndGravity(videoBox, MATCH_PARENT, WRAP_CONTENT, Gravity.BOTTOM);
    } else {
        videoBox.setTranslationY(0); // Reset any translation that was applied in portrait.
        int screenWidth = dpToPx(getResources().getConfiguration().screenWidthDp);
        setLayoutSize(listFragment.getView(), screenWidth / 4, MATCH_PARENT);
        int videoWidth = screenWidth - screenWidth / 4 - dpToPx(LANDSCAPE_VIDEO_PADDING_DP);
        setLayoutSize(videoFragment.getView(), videoWidth, WRAP_CONTENT);
        setLayoutSizeAndGravity(videoBox, videoWidth, WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL);
    }
}