Example usage for android.widget LinearLayout setBackgroundResource

List of usage examples for android.widget LinearLayout setBackgroundResource

Introduction

In this page you can find the example usage for android.widget LinearLayout setBackgroundResource.

Prototype

@RemotableViewMethod
public void setBackgroundResource(@DrawableRes int resid) 

Source Link

Document

Set the background to a given resource.

Usage

From source file:com.mishiranu.dashchan.ui.navigator.NavigatorActivity.java

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void showThemeDialog() {
    final int checkedItem = Arrays.asList(Preferences.VALUES_THEME).indexOf(Preferences.getTheme());
    Resources resources = getResources();
    float density = ResourceUtils.obtainDensity(resources);
    ScrollView scrollView = new ScrollView(this);
    LinearLayout outer = new LinearLayout(this);
    outer.setOrientation(LinearLayout.VERTICAL);
    int outerPadding = (int) (16f * density);
    outer.setPadding(outerPadding, outerPadding, outerPadding, outerPadding);
    scrollView.addView(outer, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    final AlertDialog dialog = new AlertDialog.Builder(this).setTitle(R.string.action_change_theme)
            .setView(scrollView).setNegativeButton(android.R.string.cancel, null).create();
    View.OnClickListener listener = v -> {
        int index = (int) v.getTag();
        if (index != checkedItem) {
            Preferences.setTheme(Preferences.VALUES_THEME[index]);
            recreate();/*  w ww . j av a  2 s .  c  om*/
        }
        dialog.dismiss();
    };
    int circleSize = (int) (56f * density);
    int itemPadding = (int) (12f * density);
    LinearLayout inner = null;
    for (int i = 0; i < Preferences.ENTRIES_THEME.length; i++) {
        if (i % 3 == 0) {
            inner = new LinearLayout(this);
            inner.setOrientation(LinearLayout.HORIZONTAL);
            outer.addView(inner, LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT);
        }
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setGravity(Gravity.CENTER);
        layout.setBackgroundResource(
                ResourceUtils.getResourceId(this, android.R.attr.selectableItemBackground, 0));
        layout.setPadding(0, itemPadding, 0, itemPadding);
        layout.setOnClickListener(listener);
        layout.setTag(i);
        inner.addView(layout, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
        View view = new View(this);
        int colorBackgroundAttr = Preferences.VALUES_THEME_COLORS[i][0];
        int colorPrimaryAttr = Preferences.VALUES_THEME_COLORS[i][1];
        int colorAccentAttr = Preferences.VALUES_THEME_COLORS[i][2];
        Resources.Theme theme = getResources().newTheme();
        theme.applyStyle(Preferences.VALUES_THEME_IDS[i], true);
        TypedArray typedArray = theme
                .obtainStyledAttributes(new int[] { colorBackgroundAttr, colorPrimaryAttr, colorAccentAttr });
        view.setBackground(new ThemeChoiceDrawable(typedArray.getColor(0, 0), typedArray.getColor(1, 0),
                typedArray.getColor(2, 0)));
        typedArray.recycle();
        if (C.API_LOLLIPOP) {
            view.setElevation(6f * density);
        }
        layout.addView(view, circleSize, circleSize);
        TextView textView = new TextView(this, null, android.R.attr.textAppearanceListItem);
        textView.setSingleLine(true);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setText(Preferences.ENTRIES_THEME[i]);
        if (C.API_LOLLIPOP) {
            textView.setAllCaps(true);
            textView.setTypeface(GraphicsUtils.TYPEFACE_MEDIUM);
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f);
        } else {
            textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f);
        }
        textView.setGravity(Gravity.CENTER_HORIZONTAL);
        textView.setPadding(0, (int) (8f * density), 0, 0);
        layout.addView(textView, LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        if (i + 1 == Preferences.ENTRIES_THEME.length && Preferences.ENTRIES_THEME.length % 3 != 0) {
            if (Preferences.ENTRIES_THEME.length % 3 == 1) {
                inner.addView(new View(this), 0,
                        new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f));
            }
            inner.addView(new View(this),
                    new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1f));
        }
    }
    dialog.show();
}

From source file:de.enlightened.peris.MessageActivity.java

private void renderMessage(final Message message) {
    final Context context = this.getApplicationContext();
    final SharedPreferences appPreferences = context.getSharedPreferences("prefs", 0);
    final boolean useShading = appPreferences.getBoolean("use_shading", false);
    final boolean useOpenSans = appPreferences.getBoolean("use_opensans", false);
    final int fontSize = appPreferences.getInt("font_size", DEFAULT_FONT_SIZE);
    final boolean currentAvatarSetting = appPreferences.getBoolean("show_images", true);
    final Typeface opensans = Typeface.createFromAsset(context.getAssets(), "fonts/opensans.ttf");

    final View view = this.findViewById(R.id.message_layout);
    final TextView poAuthor = (TextView) view.findViewById(R.id.message_author);
    final TextView poTimestamp = (TextView) view.findViewById(R.id.message_timestamp);
    final TextView tvOnline = (TextView) view.findViewById(R.id.message_online_status);

    final LinearLayout llBorderBackground = (LinearLayout) view.findViewById(R.id.ll_border_background);
    final LinearLayout llColorBackground = (LinearLayout) view.findViewById(R.id.ll_color_background);

    String textColor = context.getString(R.string.default_text_color);
    if (this.application.getSession().getServer().serverTextColor.contains("#")) {
        textColor = this.application.getSession().getServer().serverTextColor;
    }// ww w  .  j  a  va 2 s.  c  o  m

    String boxColor = context.getString(R.string.default_element_background);
    if (this.application.getSession().getServer().serverBoxColor != null) {
        boxColor = this.application.getSession().getServer().serverBoxColor;
    }

    if (boxColor.contains("#")) {
        llColorBackground.setBackgroundColor(Color.parseColor(boxColor));
    } else {
        llColorBackground.setBackgroundColor(Color.TRANSPARENT);
    }

    //TODO: remove border?
    String boxBorder = context.getString(R.string.default_element_border);
    if (this.application.getSession().getServer().serverBoxBorder != null) {
        boxBorder = this.application.getSession().getServer().serverBoxBorder;
    }

    if (boxBorder.contentEquals("1")) {
        llBorderBackground.setBackgroundResource(R.drawable.element_border);
    } else {
        llBorderBackground.setBackgroundColor(Color.TRANSPARENT);
    }

    if (useOpenSans) {
        poAuthor.setTypeface(opensans);
        poTimestamp.setTypeface(opensans);
        tvOnline.setTypeface(opensans);
    }

    if (useShading) {
        poAuthor.setShadowLayer(2, 0, 0, Color.parseColor("#66000000"));
        tvOnline.setShadowLayer(2, 0, 0, Color.parseColor("#66000000"));
    }

    final LinearLayout llPostBodyHolder = (LinearLayout) view.findViewById(R.id.message_body_holder);
    llPostBodyHolder.removeAllViews();

    final ImageView poAvatar = (ImageView) view.findViewById(R.id.message_avatar);

    if (boxColor != null && boxColor.contains("#") && boxColor.length() == 7) {
        final ImageView postAvatarFrame = (ImageView) view.findViewById(R.id.message_avatar_frame);
        postAvatarFrame.setColorFilter(Color.parseColor(boxColor));
    } else {
        final ImageView postAvatarFrame = (ImageView) view.findViewById(R.id.message_avatar_frame);
        postAvatarFrame.setVisibility(View.GONE);
    }

    if (message.isAuthorOnline()) {
        tvOnline.setText("ONLINE");
        tvOnline.setVisibility(View.VISIBLE);
    } else {
        tvOnline.setVisibility(View.GONE);
    }

    poAuthor.setText(message.getAuthor());
    poTimestamp.setText(DateTimeUtils.getTimeAgo(message.getTimestamp()));

    final String postContent = message.getBody();
    // TODO: add attachments
    BBCodeParser.parseCode(context, llPostBodyHolder, postContent, opensans, useOpenSans, useShading,
            new ArrayList<PostAttachment>(), fontSize, true, textColor, this.application);

    poAuthor.setTextColor(Color.parseColor(textColor));
    poTimestamp.setTextColor(Color.parseColor(textColor));

    if (currentAvatarSetting) {
        if (Net.isUrl(message.getAuthorAvatar())) {
            final String imageUrl = message.getAuthorAvatar();
            ImageLoader.getInstance().displayImage(imageUrl, poAvatar);
        } else {
            poAvatar.setImageResource(R.drawable.no_avatar);
        }
    } else {
        poAvatar.setVisibility(View.GONE);
    }
}

From source file:org.linphone.InCallActivity.java

private void setRowBackground(LinearLayout callView, int index) {
    int backgroundResource;
    if (index == 0) {
        //         backgroundResource = active ? R.drawable.cell_call_first_highlight : R.drawable.cell_call_first;
        backgroundResource = R.drawable.cell_call_first;
    } else {//from w ww. j  av  a2s. c o m
        //         backgroundResource = active ? R.drawable.cell_call_highlight : R.drawable.cell_call;
        backgroundResource = R.drawable.cell_call;
    }
    callView.setBackgroundResource(backgroundResource);
}

From source file:org.xingjitong.InCallActivity.java

private void setRowBackground(LinearLayout callView, int index) {
    int backgroundResource;
    if (index == 0) {
        // backgroundResource = active ?
        // R.drawable.cell_call_first_highlight :
        // R.drawable.cell_call_first;
        //yyppcallingui //yyppcallinguiui
        //?//from   ww  w  . j  a  va2 s.  co  m
        //backgroundResource = R.drawable.cell_call_first;
        backgroundResource = R.color.white;
    } else {
        // backgroundResource = active ? R.drawable.cell_call_highlight :
        // R.drawable.cell_call;
        //yyppcallingui //yyppcallinguiui
        //backgroundResource = R.drawable.cell_call;
        backgroundResource = R.color.white;
    }
    callView.setBackgroundResource(backgroundResource);
}

From source file:org.otempo.view.StationActivity.java

/**
 * Actualiza la parte del layout que visualiza predicciones
 *//*from w  w  w  .ja va  2  s  .co  m*/
private void updateLayout() {

    final LinearLayout scrolled = findViewById(R.id.scrolled);
    scrolled.removeAllViews();
    final LinearLayout predictedGroup = findViewById(R.id.predictedGroup);
    if (predictedGroup != null) { // en landscape no hay
        predictedGroup.setVisibility(LinearLayout.INVISIBLE);
    }
    final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutUtils.dips(75, this),
            LinearLayout.LayoutParams.WRAP_CONTENT);
    Station currentStation = _stationManager.getStation();
    if (currentStation == null) {
        // Si no hay estacin elegida, nada ms que hacer...
        return;
    }
    final int currentStationId = currentStation.getId();
    if (currentStation.getPredictions().size() > 0) {
        removeDialog(DIALOG_LOADING_ID);
        if (predictedGroup != null) { // en landscape no hay
            final TextView predictionTime = findViewById(R.id.predictionTime);
            predictionTime.setText(getPredictionTimeString(currentStation.getLastCreationDate()));
            predictedGroup.setVisibility(LinearLayout.VISIBLE);
        }
        currentStation.acceptPredictionVisitor(new StationPredictionVisitor() {
            @Override
            public void apply(@NonNull StationShortTermPrediction shortPred, final int index) {
                Calendar predictionDate = shortPred.getDate();
                if (predictionDate == null || !DateUtils.isFromToday(predictionDate)) {
                    return;
                }
                LinearLayout day = new LinearLayout(StationActivity.this);
                day.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        showDialog(DIALOG_DAY_COMMENT_MASK + index + currentStationId * MAX_PREDICTED_DAYS);
                    }
                });
                day.setOrientation(LinearLayout.VERTICAL);
                TextView dayName = getDayName(shortPred.getDate());
                day.addView(dayName);
                ImageView morningIcon = new ImageView(StationActivity.this);
                morningIcon.setImageResource(ResourceUtils.getResource(shortPred.getSkyStateMorning(), true));
                day.addView(morningIcon);
                ImageView afternoonIcon = new ImageView(StationActivity.this);
                afternoonIcon
                        .setImageResource(ResourceUtils.getResource(shortPred.getSkyStateAfternoon(), true));
                day.addView(afternoonIcon);
                ImageView nightIcon = new ImageView(StationActivity.this);
                nightIcon.setImageResource(ResourceUtils.getResource(shortPred.getSkyStateNight(), false));
                day.addView(nightIcon);
                TextView temps = new TextView(StationActivity.this);
                temps.setText(shortPred.getMinTemp() + " - " + shortPred.getMaxTemp() + " C");
                temps.setGravity(Gravity.CENTER_HORIZONTAL);
                day.addView(temps);
                if (DateUtils.isToday(predictionDate)) {
                    day.setBackgroundResource(R.drawable.today_bg);
                    temps.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
                    dayName.setTypeface(Typeface.DEFAULT, Typeface.BOLD);
                }
                scrolled.addView(day, params);
            }

            @Override
            public void apply(@NonNull StationMediumTermPrediction medPred, final int index) {
                Calendar predictionDate = medPred.getDate();
                if (predictionDate == null || !DateUtils.isFromToday(predictionDate)) {
                    return;
                }
                LinearLayout day = new LinearLayout(StationActivity.this);
                day.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        showDialog(DIALOG_DAY_COMMENT_MASK + index + currentStationId * MAX_PREDICTED_DAYS);
                    }
                });
                day.setOrientation(LinearLayout.VERTICAL);
                TextView dayName = getDayName(medPred.getDate());
                day.addView(dayName);
                ImageView morningIcon = new ImageView(StationActivity.this);
                morningIcon.setImageResource(ResourceUtils.getResource(medPred.getSkyState(), true));
                day.addView(morningIcon);
                TextView temps = new TextView(StationActivity.this);
                temps.setText(medPred.getMinTemp() + " - " + medPred.getMaxTemp() + " C");
                temps.setGravity(Gravity.CENTER_HORIZONTAL);
                temps.setTextColor(Color.WHITE);
                day.addView(temps);
                scrolled.addView(day, params);
            }
        });
    } else {
        // Ahora mostramos el dilogo si hace falta, y sino borramos la marca de skip
        if (_skipDialog) {
            _skipDialog = false;
        } else {
            if (!this.isFinishing()) {
                showDialog(DIALOG_LOADING_ID);
                fetchThenShow(currentStation, false);
            }
        }
    }
}

From source file:foam.starwisp.StarwispBuilder.java

public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) {

    if (StarwispLinearLayout.m_DisplayMetrics == null) {
        StarwispLinearLayout.m_DisplayMetrics = ctx.getResources().getDisplayMetrics();
    }/*from   w w w.  j a  v  a 2  s .  co  m*/

    try {
        String type = arr.getString(0);

        //Log.i("starwisp","building started "+type);

        if (type.equals("build-fragment")) {
            String name = arr.getString(1);
            int ID = arr.getInt(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            inner.setId(ID);
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, fragment);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("map")) {
            int ID = arr.getInt(1);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            inner.setId(ID);
            Fragment mapfrag = SupportMapFragment.newInstance();
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, mapfrag);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("drawmap")) {
            final LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            DrawableMap dm = new DrawableMap();
            dm.init(arr.getInt(1), inner, (StarwispActivity) ctx, this, arr.getString(3));
            parent.addView(inner);
            m_DMaps.put(arr.getInt(1), dm);
            return;
        }

        if (type.equals("linear-layout")) {
            StarwispLinearLayout.Build(this, ctx, ctxname, arr, parent);
            return;
        }

        if (type.equals("relative-layout")) {
            StarwispRelativeLayout.Build(this, ctx, ctxname, arr, parent);
            return;
        }

        if (type.equals("draggable")) {
            final LinearLayout v = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String behaviour_type = arr.getString(5);
            v.setPadding(20, 20, 20, 10);
            v.setId(id);
            v.setOrientation(StarwispLinearLayout.BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setClickable(true);
            v.setFocusable(true);

            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundResource(R.drawable.draggable);

            GradientDrawable drawable = (GradientDrawable) v.getBackground();
            final int colour = Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2));
            drawable.setColor(colour);

            /*LayerDrawable bgDrawable = (LayerDrawable)v.getBackground();
            GradientDrawable bgShape = (GradientDrawable)bgDrawable.findDrawableByLayerId(R.id.draggableshape);
            bgShape.setColor(colour);*/
            /*v.getBackground().setColorFilter(colour, PorterDuff.Mode.MULTIPLY);*/

            parent.addView(v);
            JSONArray children = arr.getJSONArray(6);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }

            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            if (!behaviour_type.equals("drop-only") && !behaviour_type.equals("drop-only-consume")) {
                v.setOnLongClickListener(new View.OnLongClickListener() {
                    public boolean onLongClick(View vv) {
                        if (id != 99) {
                            ClipData dragData = new ClipData(
                                    new ClipDescription("" + id,
                                            new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }),
                                    new ClipData.Item("" + id));

                            View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                            Log.i("starwisp", "start drag id " + vv.getId() + " " + v);
                            v.startDrag(dragData, myShadow, v, 0);
                            v.setVisibility(View.GONE);
                            return true;
                        }
                        return false;
                    }
                });
            }

            if (!behaviour_type.equals("drag-only")) {
                // ye gads - needed as drag/drop doesn't deal with nested targets
                final StarwispBuilder that = this;

                v.setOnDragListener(new View.OnDragListener() {
                    public boolean onDrag(View vv, DragEvent event) {

                        //Log.i("starwisp","on drag event happened");

                        final int action = event.getAction();
                        switch (action) {
                        case DragEvent.ACTION_DRAG_STARTED:
                            //Log.i("starwisp","Drag started"+v );
                            if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                                // returns true to indicate that the View can accept the dragged data.
                                return true;
                            } else {
                                // Returns false. During the current drag and drop operation, this View will
                                // not receive events again until ACTION_DRAG_ENDED is sent.
                                return false;
                            }
                        case DragEvent.ACTION_DRAG_ENTERED: {
                            if (that.m_LastDragHighlighted != null) {
                                that.m_LastDragHighlighted.getBackground().setColorFilter(null);
                            }
                            v.getBackground().setColorFilter(0x77777777, PorterDuff.Mode.MULTIPLY);
                            that.m_LastDragHighlighted = v;
                            //Log.i("starwisp","Drag entered"+v );
                            return true;
                        }
                        case DragEvent.ACTION_DRAG_LOCATION: {
                            //View dragee = (View)event.getLocalState();
                            //dragee.setVisibility(View.VISIBLE);
                            //Log.i("starwisp","Drag location"+v );
                            return true;
                        }
                        case DragEvent.ACTION_DRAG_EXITED: {
                            //Log.i("starwisp","Drag exited "+v );
                            v.getBackground().setColorFilter(null);
                            return true;
                        }
                        case DragEvent.ACTION_DROP: {
                            v.getBackground().setColorFilter(null);
                            //Log.i("starwisp","Drag dropped "+v );
                            View otherw = (View) event.getLocalState();
                            //Log.i("starwisp","removing from parent "+((View)otherw.getParent()).getId());

                            // check we are not adding to ourself
                            if (id != otherw.getId()) {
                                ((ViewManager) otherw.getParent()).removeView(otherw);
                                //Log.i("starwisp","adding to " + id);

                                if (!behaviour_type.equals("drop-only-consume")) {
                                    v.addView(otherw);
                                }
                            }
                            otherw.setVisibility(View.VISIBLE);
                            return true;
                        }
                        case DragEvent.ACTION_DRAG_ENDED: {
                            //Log.i("starwisp","Drag ended "+v );
                            v.getBackground().setColorFilter(null);

                            View dragee = (View) event.getLocalState();
                            dragee.setVisibility(View.VISIBLE);

                            if (event.getResult()) {
                                //Log.i("starwisp","sucess " );
                            } else {
                                //Log.i("starwisp","fail " );
                            }
                            ;
                            return true;
                        }
                        // An unknown action type was received.
                        default:
                            //Log.e("starwisp","Unknown action type received by OnDragListener.");
                            break;
                        }
                        ;
                        return true;
                    }
                });
                return;
            }
        }

        if (type.equals("frame-layout")) {
            FrameLayout v = new FrameLayout(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        /*
        if (type.equals("grid-layout")) {
        GridLayout v = new GridLayout(ctx);
        v.setId(arr.getInt(1));
        v.setRowCount(arr.getInt(2));
        //v.setColumnCount(arr.getInt(2));
        v.setOrientation(BuildOrientation(arr.getString(3)));
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
                
        parent.addView(v);
        JSONArray children = arr.getJSONArray(5);
        for (int i=0; i<children.length(); i++) {
            Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
        }
                
        return;
        }
        */

        if (type.equals("scroll-view")) {
            HorizontalScrollView v = new HorizontalScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("scroll-view-vert")) {
            ScrollView v = new ScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("view-pager")) {
            ViewPager v = new ViewPager(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.setOffscreenPageLimit(3);
            final JSONArray items = arr.getJSONArray(3);

            v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {

                @Override
                public int getCount() {
                    return items.length();
                }

                @Override
                public Fragment getItem(int position) {
                    try {
                        String fragname = items.getString(position);
                        return ActivityManager.GetFragment(fragname);
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing fragment data " + e.toString());
                    }
                    return null;
                }
            });
            parent.addView(v);
            return;
        }

        if (type.equals("space")) {
            // Space v = new Space(ctx); (class not found runtime error??)
            TextView v = new TextView(ctx);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
        }

        if (type.equals("image-view")) {
            ImageView v = new ImageView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setAdjustViewBounds(true);

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                Bitmap b = BitmapCache.Load(image);
                if (b != null) {
                    v.setImageBitmap(b);
                }
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            parent.addView(v);
        }

        if (type.equals("image-button")) {
            ImageButton v = new ImageButton(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                v.setImageBitmap(BitmapCache.Load(image));
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            final String fn = arr.getString(4);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });

            v.setAdjustViewBounds(true);
            v.setScaleType(ImageView.ScaleType.CENTER_INSIDE);

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)), BufferType.SPANNABLE);
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setLinkTextColor(0xff00aa00);

            // uncomment all this to get hyperlinks to work in text...
            // should make this an option of course

            //v.setClickable(true); // make links
            //v.setMovementMethod(LinkMovementMethod.getInstance());
            //v.setEnabled(true);   // go to browser
            /*v.setOnTouchListener(new View.OnTouchListener() {
            public boolean onTouch(View vv, MotionEvent event) {
                return false;
            }
            };*/

            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.CENTER);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

        if (type.equals("debug-text-view")) {
            TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null);
            //                v.setBackgroundResource(R.color.black);
            v.setId(arr.getInt(1));
            //                v.setText(Html.fromHtml(arr.getString(2)));
            //                v.setTextColor(R.color.white);
            //                v.setTextSize(arr.getInt(3));
            //                v.setMovementMethod(LinkMovementMethod.getInstance());
            //                v.setMaxLines(10);
            //                v.setVerticalScrollBarEnabled(true);
            //                v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            //v.setMovementMethod(new ScrollingMovementMethod());

            /*
            if (arr.length()>5) {
            if (arr.getString(5).equals("left")) {
                v.setGravity(Gravity.LEFT);
            } else {
                if (arr.getString(5).equals("fill")) {
                    v.setGravity(Gravity.FILL);
                } else {
                    v.setGravity(Gravity.CENTER);
                }
            }
            } else {
            v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/
            parent.addView(v);
        }

        if (type.equals("web-view")) {
            WebView v = new WebView(ctx);
            v.setId(arr.getInt(1));
            v.setVerticalScrollBarEnabled(false);
            v.loadData(arr.getString(2), "text/html", "utf-8");
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            parent.addView(v);
        }

        if (type.equals("edit-text")) {
            final EditText v = new EditText(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setGravity(Gravity.LEFT | Gravity.TOP);

            String inputtype = arr.getString(4);
            if (inputtype.equals("text")) {
                //v.setInputType(InputType.TYPE_CLASS_TEXT);
            } else if (inputtype.equals("numeric")) {
                v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                        | InputType.TYPE_NUMBER_FLAG_SIGNED);
            } else if (inputtype.equals("email")) {
                v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
            }

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            //v.setSingleLine(true);

            v.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\"");
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });

            parent.addView(v);
        }

        if (type.equals("colour-button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            JSONArray col = arr.getJSONArray(6);
            v.getBackground().setColorFilter(
                    Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)),
                    PorterDuff.Mode.MULTIPLY);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });
            parent.addView(v);
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = new ToggleButton(ctx);
            if (arr.getString(5).equals("fancy")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null);
            }

            if (arr.getString(5).equals("yes")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null);
            }

            if (arr.getString(5).equals("maybe")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null);
            }

            if (arr.getString(5).equals("no")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null);
            }

            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(6);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String arg = "#f";
                    if (((ToggleButton) v).isChecked())
                        arg = "#t";
                    CallbackArgs(ctx, ctxname, v.getId(), arg);
                }
            });
            parent.addView(v);
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            v.setId(arr.getInt(1));
            v.setMax(arr.getInt(2));
            v.setProgress(arr.getInt(2) / 2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            final String fn = arr.getString(4);

            v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar v, int a, boolean s) {
                    CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a));
                }

                public void onStartTrackingTouch(SeekBar v) {
                }

                public void onStopTrackingTouch(SeekBar v) {
                }
            });
            parent.addView(v);
        }

        if (type.equals("spinner")) {
            Spinner v = new Spinner(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            final JSONArray items = arr.getJSONArray(2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setMinimumWidth(100); // stops tiny buttons
            ArrayList<String> spinnerArray = new ArrayList<String>();

            for (int i = 0; i < items.length(); i++) {
                spinnerArray.add(items.getString(i));
            }

            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                    spinnerArray) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                    return v;
                }
            };

            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);

            v.setAdapter(spinnerArrayAdapter);
            v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                    CallbackArgs(ctx, ctxname, wid, "" + pos);
                }

                public void onNothingSelected(AdapterView<?> v) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("nomadic")) {
            final int wid = arr.getInt(1);
            NomadicSurfaceView v = new NomadicSurfaceView(ctx, wid);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            Log.e("starwisp", "built the thing");
            parent.addView(v);
            Log.e("starwisp", "addit to the view");
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = new StarwispCanvas(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.SetDrawList(arr.getJSONArray(3));
            parent.addView(v);
        }

        if (type.equals("camera-preview")) {
            PictureTaker pt = new PictureTaker();
            CameraPreview v = new CameraPreview(ctx, pt);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);

            Log.i("starwisp", "in camera-preview...");

            List<List<String>> info = v.mPictureTaker.GetInfo();
            // can't find a way to do this via a callback yet
            String arg = "'(";
            for (List<String> e : info) {
                arg += "(" + e.get(0) + " " + e.get(1) + ")";
                //Log.i("starwisp","converting prop "+arg);
            }
            arg += ")";
            m_Scheme.eval("(set! camera-properties " + arg + ")");
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

            for (int i = 0; i < count; i++) {
                JSONArray button = buttons.getJSONArray(i);

                if (vertcount == 0) {
                    vert = new LinearLayout(ctx);
                    vert.setId(0);
                    vert.setOrientation(LinearLayout.VERTICAL);
                    horiz.addView(vert);
                }
                vertcount = (vertcount + 1) % height;

                if (buttontype.equals("button")) {
                    Button b = new Button(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                        }
                    });
                    vert.addView(b);
                } else if (buttontype.equals("toggle")) {
                    ToggleButton b = new ToggleButton(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            String arg = "#f";
                            if (((ToggleButton) v).isChecked())
                                arg = "#t";
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                        }
                    });
                    vert.addView(b);
                }
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString());
    }

    //Log.i("starwisp","building ended");

}

From source file:foam.opensauces.StarwispBuilder.java

public void Build(final StarwispActivity ctx, final String ctxname, JSONArray arr, ViewGroup parent) {

    try {/*from   w  ww .j  a v  a 2 s.  c om*/
        String type = arr.getString(0);

        //Log.i("starwisp","building started "+type);

        if (type.equals("build-fragment")) {
            String name = arr.getString(1);
            int ID = arr.getInt(2);
            Fragment fragment = ActivityManager.GetFragment(name);
            LinearLayout inner = new LinearLayout(ctx);
            inner.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            inner.setId(ID);
            FragmentTransaction fragmentTransaction = ctx.getSupportFragmentManager().beginTransaction();
            fragmentTransaction.add(ID, fragment);
            fragmentTransaction.commit();
            parent.addView(inner);
            return;
        }

        if (type.equals("linear-layout")) {
            LinearLayout v = new LinearLayout(ctx);
            v.setId(arr.getInt(1));
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            //v.setPadding(2,2,2,2);
            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundColor(Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("draggable")) {
            final LinearLayout v = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            v.setPadding(20, 20, 20, 20);
            v.setId(id);
            v.setOrientation(BuildOrientation(arr.getString(2)));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            v.setClickable(true);
            v.setFocusable(true);

            JSONArray col = arr.getJSONArray(4);
            v.setBackgroundResource(R.drawable.draggable);

            GradientDrawable drawable = (GradientDrawable) v.getBackground();
            final int colour = Color.argb(col.getInt(3), col.getInt(0), col.getInt(1), col.getInt(2));
            drawable.setColor(colour);

            parent.addView(v);
            JSONArray children = arr.getJSONArray(5);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }

            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            /*                v.setOnLongClickListener(new View.OnLongClickListener() {
            public boolean onLongClick(View vv) {
                if (id!=99) {
                    ClipData dragData = ClipData.newPlainText("simple text", ""+id);
                    View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                    Log.i("starwisp","start drag id "+vv.getId());
                    v.startDrag(dragData, myShadow, null, 0);
                    v.setVisibility(View.GONE);
                    return true;
                }
                return false;
            }
                            });
            */
            // Sets a long click listener for the ImageView using an anonymous listener object that
            // implements the OnLongClickListener interface
            v.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View vv, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN && id != 99) {
                        //                            ClipData dragData = ClipData.newPlainText("simple text", ""+id);

                        ClipData dragData = new ClipData(
                                new ClipDescription(null, new String[] { ClipDescription.MIMETYPE_TEXT_PLAIN }),
                                new ClipData.Item("" + id));

                        View.DragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                        Log.i("starwisp", "start drag id " + vv.getId());
                        v.startDrag(dragData, myShadow, null, 0);
                        v.setVisibility(View.GONE);
                        return true;
                    }
                    return false;
                }
            });

            v.setOnDragListener(new View.OnDragListener() {
                public boolean onDrag(View vv, DragEvent event) {
                    final int action = event.getAction();
                    switch (action) {
                    case DragEvent.ACTION_DRAG_STARTED:
                        if (event.getClipDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
                            // returns true to indicate that the View can accept the dragged data.
                            return true;
                        } else {
                            // Returns false. During the current drag and drop operation, this View will
                            // not receive events again until ACTION_DRAG_ENDED is sent.
                            return false;
                        }
                    case DragEvent.ACTION_DRAG_ENTERED: {
                        return true;
                    }
                    case DragEvent.ACTION_DRAG_LOCATION:
                        return true;
                    case DragEvent.ACTION_DRAG_EXITED: {
                        return true;
                    }
                    case DragEvent.ACTION_DROP: {
                        ClipData.Item item = event.getClipData().getItemAt(0);
                        String dragData = item.getText().toString();
                        Log.i("starwisp", "Dragged view is " + dragData);
                        int otherid = Integer.parseInt(dragData);
                        View otherw = ctx.findViewById(otherid);
                        Log.i("starwisp", "removing from parent " + ((View) otherw.getParent()).getId());

                        // check we are not adding to ourself
                        if (id != otherid) {
                            ((ViewManager) otherw.getParent()).removeView(otherw);
                            Log.i("starwisp", "adding to " + id);
                            v.addView(otherw);
                        }
                        otherw.setVisibility(View.VISIBLE);
                        return true;
                    }
                    case DragEvent.ACTION_DRAG_ENDED: {
                        if (event.getResult()) {
                        } else {
                        }
                        ;
                        return true;
                    }
                    // An unknown action type was received.
                    default:
                        Log.e("starwisp", "Unknown action type received by OnDragListener.");
                        break;
                    }
                    ;
                    return true;
                }
            });
            return;
        }

        if (type.equals("frame-layout")) {
            FrameLayout v = new FrameLayout(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        /*
        if (type.equals("grid-layout")) {
        GridLayout v = new GridLayout(ctx);
        v.setId(arr.getInt(1));
        v.setRowCount(arr.getInt(2));
        //v.setColumnCount(arr.getInt(2));
        v.setOrientation(BuildOrientation(arr.getString(3)));
        v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
                
        parent.addView(v);
        JSONArray children = arr.getJSONArray(5);
        for (int i=0; i<children.length(); i++) {
            Build(ctx,ctxname,new JSONArray(children.getString(i)), v);
        }
                
        return;
        }
        */

        if (type.equals("scroll-view")) {
            HorizontalScrollView v = new HorizontalScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("scroll-view-vert")) {
            ScrollView v = new ScrollView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
            JSONArray children = arr.getJSONArray(3);
            for (int i = 0; i < children.length(); i++) {
                Build(ctx, ctxname, new JSONArray(children.getString(i)), v);
            }
            return;
        }

        if (type.equals("view-pager")) {
            ViewPager v = new ViewPager(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.setOffscreenPageLimit(3);
            final JSONArray items = arr.getJSONArray(3);

            v.setAdapter(new FragmentPagerAdapter(ctx.getSupportFragmentManager()) {

                @Override
                public int getCount() {
                    return items.length();
                }

                @Override
                public Fragment getItem(int position) {
                    try {
                        String fragname = items.getString(position);
                        return ActivityManager.GetFragment(fragname);
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                    return null;
                }
            });
            parent.addView(v);
            return;
        }

        if (type.equals("space")) {
            // Space v = new Space(ctx); (class not found runtime error??)
            TextView v = new TextView(ctx);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            parent.addView(v);
        }

        if (type.equals("image-view")) {
            ImageView v = new ImageView(ctx);
            v.setId(arr.getInt(1));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));

            String image = arr.getString(2);

            if (image.startsWith("/")) {
                Bitmap bitmap = BitmapFactory.decodeFile(image);
                v.setImageBitmap(bitmap);
            } else {
                int id = ctx.getResources().getIdentifier(image, "drawable", ctx.getPackageName());
                v.setImageResource(id);
            }

            parent.addView(v);
        }

        if (type.equals("text-view")) {
            TextView v = new TextView(ctx);
            v.setId(arr.getInt(1));
            v.setText(Html.fromHtml(arr.getString(2)));
            v.setTextSize(arr.getInt(3));
            v.setMovementMethod(LinkMovementMethod.getInstance());
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setClickable(false);
            v.setEnabled(false);

            v.setOnTouchListener(new View.OnTouchListener() {
                public boolean onTouch(View vv, MotionEvent event) {
                    return false;
                }
            });

            if (arr.length() > 5) {
                if (arr.getString(5).equals("left")) {
                    v.setGravity(Gravity.LEFT);
                } else {
                    if (arr.getString(5).equals("fill")) {
                        v.setGravity(Gravity.FILL);
                    } else {
                        v.setGravity(Gravity.CENTER);
                    }
                }
            } else {
                v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            parent.addView(v);
        }

        if (type.equals("debug-text-view")) {
            TextView v = (TextView) ctx.getLayoutInflater().inflate(R.layout.debug_text, null);
            //                v.setBackgroundResource(R.color.black);
            v.setId(arr.getInt(1));
            //                v.setText(Html.fromHtml(arr.getString(2)));
            //                v.setTextColor(R.color.white);
            //                v.setTextSize(arr.getInt(3));
            //                v.setMovementMethod(LinkMovementMethod.getInstance());
            //                v.setMaxLines(10);
            //                v.setVerticalScrollBarEnabled(true);
            //                v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            //v.setMovementMethod(new ScrollingMovementMethod());

            /*
            if (arr.length()>5) {
            if (arr.getString(5).equals("left")) {
                v.setGravity(Gravity.LEFT);
            } else {
                if (arr.getString(5).equals("fill")) {
                    v.setGravity(Gravity.FILL);
                } else {
                    v.setGravity(Gravity.CENTER);
                }
            }
            } else {
            v.setGravity(Gravity.LEFT);
            }
            v.setTypeface(((StarwispActivity)ctx).m_Typeface);*/
            parent.addView(v);
        }

        if (type.equals("web-view")) {
            WebView v = new WebView(ctx);
            v.setId(arr.getInt(1));
            v.setVerticalScrollBarEnabled(false);
            v.loadData(arr.getString(2), "text/html", "utf-8");
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            parent.addView(v);
        }

        if (type.equals("edit-text")) {
            final EditText v = new EditText(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));

            String inputtype = arr.getString(4);
            if (inputtype.equals("text")) {
                //v.setInputType(InputType.TYPE_CLASS_TEXT);
            } else if (inputtype.equals("numeric")) {
                v.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
            } else if (inputtype.equals("email")) {
                v.setInputType(InputType.TYPE_TEXT_VARIATION_WEB_EMAIL_ADDRESS);
            }

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(5)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            //v.setSingleLine(true);

            v.addTextChangedListener(new TextWatcher() {
                public void afterTextChanged(Editable s) {
                    CallbackArgs(ctx, ctxname, v.getId(), "\"" + s.toString() + "\"");
                }

                public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                }

                public void onTextChanged(CharSequence s, int start, int before, int count) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("button")) {
            Button v = new Button(ctx);
            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(5);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Callback(ctx, ctxname, v.getId());
                }
            });

            parent.addView(v);
        }

        if (type.equals("toggle-button")) {
            ToggleButton v = new ToggleButton(ctx);
            if (arr.getString(5).equals("fancy")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_fancy, null);
            }

            if (arr.getString(5).equals("yes")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_yes, null);
            }

            if (arr.getString(5).equals("maybe")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_maybe, null);
            }

            if (arr.getString(5).equals("no")) {
                v = (ToggleButton) ctx.getLayoutInflater().inflate(R.layout.toggle_button_no, null);
            }

            v.setId(arr.getInt(1));
            v.setText(arr.getString(2));
            v.setTextSize(arr.getInt(3));
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(4)));
            v.setTypeface(((StarwispActivity) ctx).m_Typeface);
            final String fn = arr.getString(6);
            v.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    String arg = "#f";
                    if (((ToggleButton) v).isChecked())
                        arg = "#t";
                    CallbackArgs(ctx, ctxname, v.getId(), arg);
                }
            });
            parent.addView(v);
        }

        if (type.equals("seek-bar")) {
            SeekBar v = new SeekBar(ctx);
            v.setId(arr.getInt(1));
            v.setMax(arr.getInt(2));
            v.setProgress(arr.getInt(2) / 2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            final String fn = arr.getString(4);

            v.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar v, int a, boolean s) {
                    CallbackArgs(ctx, ctxname, v.getId(), Integer.toString(a));
                }

                public void onStartTrackingTouch(SeekBar v) {
                }

                public void onStopTrackingTouch(SeekBar v) {
                }
            });
            parent.addView(v);
        }

        if (type.equals("spinner")) {
            Spinner v = new Spinner(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            final JSONArray items = arr.getJSONArray(2);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(3)));
            ArrayList<String> spinnerArray = new ArrayList<String>();

            for (int i = 0; i < items.length(); i++) {
                spinnerArray.add(items.getString(i));
            }

            ArrayAdapter spinnerArrayAdapter = new ArrayAdapter<String>(ctx, R.layout.spinner_item,
                    spinnerArray) {
                public View getView(int position, View convertView, ViewGroup parent) {
                    View v = super.getView(position, convertView, parent);
                    ((TextView) v).setTypeface(((StarwispActivity) ctx).m_Typeface);
                    return v;
                }
            };

            spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_layout);

            v.setAdapter(spinnerArrayAdapter);
            v.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> a, View v, int pos, long id) {
                    try {
                        CallbackArgs(ctx, ctxname, wid, "\"" + items.getString(pos) + "\"");
                    } catch (JSONException e) {
                        Log.e("starwisp", "Error parsing data " + e.toString());
                    }
                }

                public void onNothingSelected(AdapterView<?> v) {
                }
            });

            parent.addView(v);
        }

        if (type.equals("canvas")) {
            StarwispCanvas v = new StarwispCanvas(ctx);
            final int wid = arr.getInt(1);
            v.setId(wid);
            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));
            v.SetDrawList(arr.getJSONArray(3));
            parent.addView(v);
        }

        if (type.equals("camera-preview")) {
            PictureTaker pt = new PictureTaker();
            CameraPreview v = new CameraPreview(ctx, pt);
            final int wid = arr.getInt(1);
            v.setId(wid);

            //              LinearLayout.LayoutParams lp =
            //  new LinearLayout.LayoutParams(minWidth, minHeight, 1);

            v.setLayoutParams(BuildLayoutParams(arr.getJSONArray(2)));

            //                v.setLayoutParams(lp);
            parent.addView(v);
        }

        if (type.equals("button-grid")) {
            LinearLayout horiz = new LinearLayout(ctx);
            final int id = arr.getInt(1);
            final String buttontype = arr.getString(2);
            horiz.setId(id);
            horiz.setOrientation(LinearLayout.HORIZONTAL);
            parent.addView(horiz);
            int height = arr.getInt(3);
            int textsize = arr.getInt(4);
            LinearLayout.LayoutParams lp = BuildLayoutParams(arr.getJSONArray(5));
            JSONArray buttons = arr.getJSONArray(6);
            int count = buttons.length();
            int vertcount = 0;
            LinearLayout vert = null;

            for (int i = 0; i < count; i++) {
                JSONArray button = buttons.getJSONArray(i);

                if (vertcount == 0) {
                    vert = new LinearLayout(ctx);
                    vert.setId(0);
                    vert.setOrientation(LinearLayout.VERTICAL);
                    horiz.addView(vert);
                }
                vertcount = (vertcount + 1) % height;

                if (buttontype.equals("button")) {
                    Button b = new Button(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " #t");
                        }
                    });
                    vert.addView(b);
                } else if (buttontype.equals("toggle")) {
                    ToggleButton b = new ToggleButton(ctx);
                    b.setId(button.getInt(0));
                    b.setText(button.getString(1));
                    b.setTextSize(textsize);
                    b.setLayoutParams(lp);
                    b.setTypeface(((StarwispActivity) ctx).m_Typeface);
                    final String fn = arr.getString(6);
                    b.setOnClickListener(new View.OnClickListener() {
                        public void onClick(View v) {
                            String arg = "#f";
                            if (((ToggleButton) v).isChecked())
                                arg = "#t";
                            CallbackArgs(ctx, ctxname, id, "" + v.getId() + " " + arg);
                        }
                    });
                    vert.addView(b);
                }
            }
        }

    } catch (JSONException e) {
        Log.e("starwisp", "Error parsing [" + arr.toString() + "] " + e.toString());
    }

    //Log.i("starwisp","building ended");

}

From source file:cm.aptoide.pt.MainActivity.java

public void setBackgroundDialogStoreTheme(String theme, LinearLayout store_background_dialog) {
    EnumStoreTheme aptoideThemeDefault = null;
    String storeThemeString = "APTOIDE_STORE_THEME_" + theme.toUpperCase(Locale.ENGLISH);
    try {//from  ww w .j a va2 s .  c  o  m
        aptoideThemeDefault = EnumStoreTheme.valueOf(storeThemeString);
    } catch (Exception e) {
        aptoideThemeDefault = EnumStoreTheme.APTOIDE_STORE_THEME_NONE;
    }

    switch (aptoideThemeDefault) {
    case APTOIDE_STORE_THEME_DEFAULT:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_default);
        break;

    case APTOIDE_STORE_THEME_GOLD:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_gold);
        break;
    case APTOIDE_STORE_THEME_MAROON:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_maroon);
        break;
    case APTOIDE_STORE_THEME_MIDNIGHT:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_midnight);
        break;
    case APTOIDE_STORE_THEME_ORANGE:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_orange);
        break;
    case APTOIDE_STORE_THEME_SPRINGGREEN:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_springgreen);
        break;
    case APTOIDE_STORE_THEME_MAGENTA:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_magenta);
        break;
    case APTOIDE_STORE_THEME_BLUE:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_blue);
        break;
    case APTOIDE_STORE_THEME_DIMGRAY:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_dimgray);
        break;
    case APTOIDE_STORE_THEME_LIGHTSKY:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_lightsky);
        break;
    case APTOIDE_STORE_THEME_PINK:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_pink);
        break;
    case APTOIDE_STORE_THEME_RED:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_red);
        break;
    case APTOIDE_STORE_THEME_SEAGREEN:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_seagreen);
        break;
    case APTOIDE_STORE_THEME_SILVER:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_silver);
        break;
    case APTOIDE_STORE_THEME_SLATEGRAY:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light_slategray);
        break;
    case APTOIDE_STORE_THEME_NONE:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light);
        break;
    default:
        store_background_dialog.setBackgroundResource(R.drawable.dialog_background_light);
        break;
    }

}

From source file:me.ububble.speakall.fragment.ConversationChatFragment.java

public void showMensajeAudio(int position, Context context, final Message message, View rowView,
        TextView icnMessageArrow) {/*from   w w w . j  a  v  a  2 s.c o  m*/
    final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
    TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
    final TextView icnMesajeTempo = (TextView) rowView.findViewById(R.id.icn_message_tempo);
    final View icnMensajeTempoDivider = (View) rowView.findViewById(R.id.icn_message_tempo_divider);
    final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
    final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
    TextView messageStatus = (TextView) rowView.findViewById(R.id.message_status);
    final LinearLayout messageMenu = (LinearLayout) rowView.findViewById(R.id.messages_menu_layout);
    final LinearLayout mensajeLayout = (LinearLayout) rowView.findViewById(R.id.mensaje_layout);
    TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
    final TextView audioTime = (TextView) rowView.findViewById(R.id.message_audio_time);
    final SeekBar audioSeekBar = (SeekBar) rowView.findViewById(R.id.audio_seekbar);
    final TextView playAudio = (TextView) rowView.findViewById(R.id.play_audio);
    final ProgressBar progressBar = (ProgressBar) rowView.findViewById(R.id.progress_bar);
    final RelativeLayout progressLayout = (RelativeLayout) rowView.findViewById(R.id.progress_layout);
    final TextView progressText = (TextView) rowView.findViewById(R.id.progress_message);

    TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, icnMesajeTempo, TFCache.TF_SPEAKALL);
    TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
    TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
    TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
    TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, audioTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, playAudio, TFCache.TF_SPEAKON);

    if (position == 0) {
        if (mensajesTotal > mensajesOffset) {
            prevMessages.setVisibility(View.VISIBLE);
            prevMessages.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    prevMessages.setVisibility(View.GONE);
                    if (mensajesTotal - mensajesOffset >= 10) {
                        mensajesLimit = 10;
                        mensajesOffset += mensajesLimit;
                        showPreviousMessages(mensajesOffset);
                    } else {
                        mensajesLimit = mensajesTotal - mensajesOffset;
                        mensajesOffset += mensajesLimit;
                        showPreviousMessages(mensajesOffset);
                    }
                }
            });
        }
    }

    DateFormat dateDay = new SimpleDateFormat("d");
    DateFormat dateDayText = new SimpleDateFormat("EEEE");
    DateFormat dateMonth = new SimpleDateFormat("MMMM");
    DateFormat dateYear = new SimpleDateFormat("yyyy");
    DateFormat timeFormat = new SimpleDateFormat("h:mm a");

    Calendar fechamsj = Calendar.getInstance();
    fechamsj.setTimeInMillis(message.emitedAt);
    String time = timeFormat.format(fechamsj.getTime());
    String dayMessage = dateDay.format(fechamsj.getTime());
    String monthMessage = dateMonth.format(fechamsj.getTime());
    String yearMessage = dateYear.format(fechamsj.getTime());
    String dayMessageText = dateDayText.format(fechamsj.getTime());
    char[] caracteres = dayMessageText.toCharArray();
    caracteres[0] = Character.toUpperCase(caracteres[0]);
    dayMessageText = new String(caracteres);

    Calendar fechaActual = Calendar.getInstance();
    String dayActual = dateDay.format(fechaActual.getTime());
    String monthActual = dateMonth.format(fechaActual.getTime());
    String yearActual = dateYear.format(fechaActual.getTime());

    String fechaMostrar = "";
    if (dayMessage.equals(dayActual) && monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
        fechaMostrar = getString(R.string.messages_today);
    } else if (monthMessage.equals(monthActual) && yearMessage.equals(yearActual)) {
        int days = Integer.parseInt(dayActual) - Integer.parseInt(dayMessage);
        if (days < 7) {
            switch (days) {
            case 1:
                fechaMostrar = getString(R.string.messages_yesterday);
                break;
            default:
                fechaMostrar = dayMessageText;
                break;
            }
        } else {
            fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
        }
    } else {
        fechaMostrar = (dayMessage + " " + monthMessage + " " + yearMessage).toUpperCase();
    }

    messageDate.setText(fechaMostrar);
    if (position != -1) {

        if (itemAnterior != null) {
            if (!fechaMostrar.equals(fechaAnterior)) {
                itemAnterior.findViewById(R.id.message_date).setVisibility(View.VISIBLE);
            } else {
                itemAnterior.findViewById(R.id.message_date).setVisibility(View.GONE);
            }
        }
        itemAnterior = rowView;
        fechaAnterior = fechaMostrar;
    } else {
        View v = messagesList.getChildAt(messagesList.getChildCount() - 1);
        if (v != null) {
            TextView tv = (TextView) v.findViewById(R.id.message_date);
            if (tv.getText().toString().equals(fechaMostrar)) {
                messageDate.setVisibility(View.GONE);
            } else {
                messageDate.setVisibility(View.VISIBLE);
            }
        }
    }
    messageTime.setText(time);

    if (message.emisor.equals(u.id)) {
        mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
        GradientDrawable drawable1 = (GradientDrawable) mensajeLayout.getBackground();
        drawable1.setCornerRadius(radius);
        drawable1.setColor(BalloonFragment.getBackgroundColor(activity));
        progressBar.getProgressDrawable().setColorFilter(getResources().getColor(R.color.speak_all_red),
                PorterDuff.Mode.SRC_IN);
        if (message.status != -1) {
            rowView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    if (messageSelected != null) {
                        View vista = messagesList.findViewWithTag(messageSelected);
                        vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                View vista = messagesList.findViewWithTag(messageSelected);
                                vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                ((MainActivity) activity).setOnBackPressedListener(null);
                                messageSelected = null;
                            }
                        });
                    } else {
                        messageSelected = message.mensajeId;
                        ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                            @Override
                            public void doBack() {
                                if (messageSelected != null) {
                                    View vista = messagesList.findViewWithTag(messageSelected);
                                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                                    ((MainActivity) activity).setOnBackPressedListener(null);
                                    messageSelected = null;
                                }
                            }
                        });
                    }

                    Vibrator x = (Vibrator) activity.getApplicationContext()
                            .getSystemService(Context.VIBRATOR_SERVICE);
                    x.vibrate(30);
                    Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                            .executeSingle();
                    if (mensaje.status != 4) {
                        icnMesajeTempo.setVisibility(View.VISIBLE);
                        icnMensajeTempoDivider.setVisibility(View.VISIBLE);
                        icnMesajeCopy.setVisibility(View.VISIBLE);
                        icnMesajeBack.setVisibility(View.VISIBLE);
                        messageMenu.setVisibility(View.VISIBLE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(icnMesajeTempo, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeTempo, "translationX", 150, 0),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                        set.setDuration(200).start();
                    } else {
                        icnMesajeCopy.setVisibility(View.VISIBLE);
                        icnMesajeBack.setVisibility(View.VISIBLE);
                        messageMenu.setVisibility(View.VISIBLE);
                        AnimatorSet set = new AnimatorSet();
                        set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                                ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", 100, 0),
                                ObjectAnimator.ofFloat(icnMesajeBack, "translationX", 50, 0));
                        set.setDuration(200).start();
                    }

                    return false;
                }
            });
        }
        if (message.status == 1) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setTextColor(getResources().getColor(R.color.speak_all_ligh_gray));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SENDING.toString());
            ValueAnimator colorAnim = ObjectAnimator.ofFloat(messageStatus, "alpha", 1, 0);
            colorAnim.setRepeatCount(ValueAnimator.INFINITE);
            colorAnim.setRepeatMode(ValueAnimator.REVERSE);
            colorAnim.setDuration(1000).start();
            animaciones.put(message.mensajeId, colorAnim);
            final JSONObject data = new JSONObject();
            try {
                data.put("message_id", message.mensajeId);
                data.put("source", message.emisor);
                data.put("source_email", message.emisorEmail);
                data.put("target_email", message.receptorEmail);
                data.put("target", message.receptor);
                data.put("type", message.tipo);
                if (!message.fileUploaded) {
                    progressLayout.setVisibility(View.VISIBLE);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    uploadAudioToServer(message.audioName, message, data, progressBar,
                                            progressLayout, progressText);
                                }
                            });
                        }
                    }).start();
                } else {
                    data.put("videos", message.fileName);
                    if (SpeakSocket.mSocket != null)
                        if (SpeakSocket.mSocket.connected()) {
                            message.status = 1;
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            message.status = -1;
                        }
                    message.save();
                    changeStatus(message.mensajeId, message.status);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (message.status == -1) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
        }
        if (message.status == 3) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
        }
        if (message.status == 2) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
        }
        if (message.status == 4) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            icnMessageArrow.setTextColor(BalloonFragment.getBackgroundColor(activity));
            messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
            icnMensajeTempoDivider.setVisibility(View.GONE);
            icnMesajeTempo.setVisibility(View.GONE);
        } else {
            icnMensajeTempoDivider.setVisibility(View.INVISIBLE);
            icnMesajeTempo.setVisibility(View.INVISIBLE);
        }

        icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                JSONObject notifyMessage = new JSONObject();
                try {
                    Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                            .executeSingle();
                    Log.w("mensaje detail",
                            mensaje.status + " : " + mensaje.receptorEmail + " : " + mensaje.tipo);
                    if (mensaje.status != 4) {
                        notifyMessage.put("type", mensaje.tipo);
                        notifyMessage.put("message_id", mensaje.mensajeId);
                        notifyMessage.put("source", mensaje.emisor);
                        notifyMessage.put("target", mensaje.receptor);
                        notifyMessage.put("status", 5);
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected())
                                SpeakSocket.mSocket.emit("message-status", notifyMessage);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    } else {
        mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
        GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
        drawable.setCornerRadius(radius);
        drawable.setColor(BalloonFragment.getFriendBalloon(activity));
        if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_AUDIO))) {
            messageStatus.setTextSize(15);
            messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
        }
        rowView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (messageSelected != null) {
                    View vista = messagesList.findViewWithTag(messageSelected);
                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                    messageSelected = message.mensajeId;
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            ((MainActivity) activity).setOnBackPressedListener(null);
                            messageSelected = null;
                        }
                    });
                } else {
                    messageSelected = message.mensajeId;
                    ((MainActivity) activity).setOnBackPressedListener(new BackPressedListener(activity) {
                        @Override
                        public void doBack() {
                            View vista = messagesList.findViewWithTag(messageSelected);
                            vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                            ((MainActivity) activity).setOnBackPressedListener(null);
                            messageSelected = null;
                        }
                    });
                }

                Vibrator x = (Vibrator) activity.getApplicationContext()
                        .getSystemService(Context.VIBRATOR_SERVICE);
                x.vibrate(20);
                icnMesajeTempo.setVisibility(View.GONE);
                icnMensajeTempoDivider.setVisibility(View.GONE);
                icnMesajeCopy.setVisibility(View.VISIBLE);
                icnMesajeBack.setVisibility(View.VISIBLE);
                messageMenu.setVisibility(View.VISIBLE);
                AnimatorSet set = new AnimatorSet();
                set.playTogether(ObjectAnimator.ofFloat(icnMesajeCopy, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(icnMesajeBack, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(messageMenu, "alpha", 0, 1),
                        ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                        ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                set.setDuration(200).start();
                return false;
            }
        });
    }

    /*icnMesajeCopy.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
          ClipData clip = ClipData.newPlainText("text", messageContent.getText().toString());
          ClipboardManager clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
          clipboard.setPrimaryClip(clip);
          Toast.makeText(activity, "Copiado", Toast.LENGTH_SHORT).show();
      }
    });*/

    icnMesajeBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (message.emisor.equals(u.id)) {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container2, ForwarForFragment.newInstance(message.mensaje))
                        .addToBackStack(null).commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            } else {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container2, ForwarForFragment.newInstance(message.mensajeTrad))
                        .addToBackStack(null).commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            }
        }
    });

    rowView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (messageSelected != null) {
                View vista = messagesList.findViewWithTag(messageSelected);
                if (!messageSelected.equals(message.mensajeId)) {
                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                    ((MainActivity) activity).setOnBackPressedListener(null);
                    messageSelected = null;
                }
            }
            final Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                    .executeSingle();
            if (mensaje.status == -1) {
                final JSONObject data = new JSONObject();
                try {
                    data.put("message_id", mensaje.mensajeId);
                    data.put("source", mensaje.emisor);
                    data.put("source_email", mensaje.emisorEmail);
                    data.put("target_email", mensaje.receptorEmail);
                    data.put("target", mensaje.receptor);
                    data.put("type", mensaje.tipo);
                    if (!mensaje.fileUploaded) {
                        progressLayout.setVisibility(View.VISIBLE);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                activity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        uploadAudioToServer(mensaje.audioName, mensaje, data, progressBar,
                                                progressLayout, progressText);
                                    }
                                });
                            }
                        }).start();
                    } else {
                        data.put("audios", mensaje.fileName);
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                mensaje.status = 1;
                                SpeakSocket.mSocket.emit("message", data);
                            } else {
                                mensaje.status = -1;
                            }
                        mensaje.save();
                        changeStatus(mensaje.mensajeId, mensaje.status);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    });

    File audioFile = null;
    final MediaPlayer mediaPlayer1 = new MediaPlayer();
    audioFile = new File(message.audioName);
    try {
        mediaPlayer1.setDataSource(audioFile.getAbsolutePath());
        mediaPlayer1.prepare();
        long timePlayer = mediaPlayer1.getDuration();
        long days, hours, minutes, seconds;
        long secondsTotal = timePlayer / 1000;
        days = (Math.round(secondsTotal) / 86400);
        hours = (Math.round(secondsTotal) / 3600) - (days * 24);
        minutes = (Math.round(secondsTotal) / 60) - (days * 1440) - (hours * 60);
        seconds = Math.round(secondsTotal) % 60;
        audioTime.setText(String.format("%02d", minutes) + " : " + String.format("%02d", seconds));
        audioSeekBar.setMax(mediaPlayer1.getDuration());
        audioSeekBar.setTag(message.mensajeId);
        mediaPlayer1.release();
    } catch (IOException e) {
        e.printStackTrace();
    }

    final File finalAudioFile = audioFile;
    playAudio.setOnClickListener(new View.OnClickListener() {
        boolean isplayAudio = false;

        @Override
        public void onClick(View v) {

            if (activeAudioSeekBarr != null) {
                if (!activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) {
                    isplayAudio = false;
                }
            }
            if (!isplayAudio) {
                try {
                    if (activeAudioSeekBarr != null) {
                        if (activeAudioSeekBarr.getTag().equals(audioSeekBar.getTag())) {
                            seekHandler.postDelayed(runAudio, 1000);
                            playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                            mediaPlayer.start();
                        } else {
                            if (mediaPlayer != null) {
                                mediaPlayer.stop();
                                mediaPlayer.release();
                            }
                            if (activeAudioSeekBarr != null) {
                                activeAudioSeekBarr.setProgress(0);
                                activeAudioSeekBarr.setOnSeekBarChangeListener(null);
                            }
                            if (activeAudioTime != null) {
                                activeAudioTime.setText(activeAudioDuration);
                            }
                            if (!activeAudioDuration.equals("")) {
                                activeAudioDuration = "";
                            }
                            if (activePlayer != null) {
                                activePlayer.setText(Finder.STRING.ICN_PLAY.toString());
                            }
                            seekHandler.removeCallbacks(runAudio);
                            mediaPlayer = new MediaPlayer();
                            mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath());
                            mediaPlayer.prepare();
                            activeAudioDuration = audioTime.getText().toString();
                            audioSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                            audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                                @Override
                                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                    if (fromUser) {
                                        mediaPlayer.seekTo(progress);
                                    }
                                }

                                @Override
                                public void onStartTrackingTouch(SeekBar seekBar) {

                                }

                                @Override
                                public void onStopTrackingTouch(SeekBar seekBar) {

                                }
                            });
                            activeAudioSeekBarr = audioSeekBar;
                            activePlayer = playAudio;
                            activeAudioTime = audioTime;
                            seekHandler.postDelayed(runAudio, 1000);
                            mediaPlayer.start();
                            playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                        }
                    } else {
                        if (mediaPlayer != null) {
                            mediaPlayer.stop();
                            mediaPlayer.release();
                        }
                        if (activeAudioSeekBarr != null) {
                            activeAudioSeekBarr.setProgress(0);
                            activeAudioSeekBarr.setOnSeekBarChangeListener(null);
                        }
                        if (activeAudioTime != null) {
                            activeAudioTime.setText(activeAudioDuration);
                        }
                        if (!activeAudioDuration.equals("")) {
                            activeAudioDuration = "";
                        }
                        seekHandler.removeCallbacks(runAudio);
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setDataSource(finalAudioFile.getAbsolutePath());
                        mediaPlayer.prepare();
                        activeAudioDuration = audioTime.getText().toString();
                        audioSeekBar.setProgress(mediaPlayer.getCurrentPosition());
                        audioSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                            @Override
                            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                                if (fromUser) {
                                    mediaPlayer.seekTo(progress);
                                }
                            }

                            @Override
                            public void onStartTrackingTouch(SeekBar seekBar) {

                            }

                            @Override
                            public void onStopTrackingTouch(SeekBar seekBar) {

                            }
                        });
                        activeAudioSeekBarr = audioSeekBar;
                        activePlayer = playAudio;
                        activeAudioTime = audioTime;
                        seekHandler.postDelayed(runAudio, 1000);
                        mediaPlayer.start();
                        playAudio.setText(Finder.STRING.ICN_PAUSE.toString());
                    }
                    //file2.delete();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                isplayAudio = true;
            } else {
                playAudio.setText(Finder.STRING.ICN_PLAY.toString());
                mediaPlayer.pause();
                seekHandler.removeCallbacks(runAudio);
                isplayAudio = false;
            }
        }
    });

}