Example usage for android.widget TextView setOnClickListener

List of usage examples for android.widget TextView setOnClickListener

Introduction

In this page you can find the example usage for android.widget TextView setOnClickListener.

Prototype

public void setOnClickListener(@Nullable OnClickListener l) 

Source Link

Document

Register a callback to be invoked when this view is clicked.

Usage

From source file:hu.fnf.devel.atlas.Atlas.java

private void setViewCategoryProperties(int page) {
    /*/*w ww .  j av  a2 s .  co  m*/
     * List LABEL
     */
    TextView header = (TextView) findViewById(R.id.header_text_view);
    TextView newe = (TextView) findViewById(R.id.new_etwas_text);
    EditText newc = (EditText) findViewById(R.id.new_etwas);
    ContentResolver cr = getContentResolver();
    Uri.Builder builder = new Builder();
    builder.scheme("content");
    builder.authority(AtlasData.DB_AUTHORITY);
    Cursor list = null;
    String[] projection = null;

    switch (page) {
    case AtlasData.PINCOME:
        newe.setText(getResources().getString(R.string.category) + ":");
        newc.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);

        builder.appendPath(AtlasData.TABLE_DATA);
        builder.appendPath("guess");

        list = cr.query(builder.build(), AtlasData.DATA_COLUMNS, null, null, null);

        header.setText(getResources().getString(R.string.guess) + "(" + String.valueOf(list.getCount()) + ")");
        list.close();

        builder = new Builder();
        builder.scheme("content");
        builder.authority(AtlasData.DB_AUTHORITY);
        builder.appendPath(AtlasData.TABLE_DATA);
        projection = AtlasData.DATA_COLUMNS;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.d("onCreate", "only toptask");
            builder.appendPath("topguess");

        } else {
            Log.d("onCreate", "all tasks");
            builder.appendPath("guess");
        }
        break;
    case AtlasData.PSUMMARY:
        newe.setText(getResources().getString(R.string.amount) + ":");
        newc.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL
                | InputType.TYPE_NUMBER_FLAG_SIGNED);
        builder.appendPath(AtlasData.TABLE_TRANSACTIONS);
        builder.appendPath("tasks");

        list = cr.query(builder.build(), AtlasData.TRANSACTIONS_COLUMNS, null, null, null);
        header.setText(getResources().getString(R.string.tasks) + "(" + String.valueOf(list.getCount()) + ")");
        list.close();

        builder = new Builder();
        builder.scheme("content");
        builder.authority(AtlasData.DB_AUTHORITY);
        builder.appendPath(AtlasData.TABLE_TRANSACTIONS);
        projection = AtlasData.TRANSACTIONS_COLUMNS;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.d("onCreate", "only toptask");
            builder.appendPath("toptask");

        } else {
            Log.d("onCreate", "all tasks");
            builder.appendPath("tasks");
        }
        break;
    case AtlasData.POUTCOME:
        newe.setText(getResources().getString(R.string.category) + ":");
        newc.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);

        builder.appendPath(AtlasData.TABLE_DATA);
        builder.appendPath("data");

        list = cr.query(builder.build(), AtlasData.DATA_COLUMNS, null, null, null);
        header.setText(getResources().getString(R.string.data) + "(" + String.valueOf(list.getCount()) + ")");
        list.close();

        builder = new Builder();
        builder.scheme("content");
        builder.authority(AtlasData.DB_AUTHORITY);
        builder.appendPath(AtlasData.TABLE_DATA);
        projection = AtlasData.DATA_COLUMNS;
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.d("onCreate", "only toptask");
            builder.appendPath("topdata");

        } else {
            Log.d("onCreate", "all tasks");
            builder.appendPath("data");
        }
        break;
    default:
        Log.e("onPageSelected", "page?!: " + page);
        break;
    }
    header.setOnClickListener(onHeaderClickListener);
    Cursor tasks_result = cr.query(builder.build(), projection, null, null, null);
    DatabaseQueryAdapter ta = new DatabaseQueryAdapter(this, tasks_result, 0,
            builder.build().getPathSegments().get(0));

    Log.d("onCreate", "result count: " + tasks_result.getColumnCount());
    ListView lv = (ListView) findViewById(R.id.tasklist);
    lv.setAdapter(ta);
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.ProductDetails.java

/**
 * Initializing user interface/*  ww  w.  j  a  va  2 s  . c  om*/
 */
private void initializeUI() {
    setContentView(R.layout.details_layout);
    hideTopBar();

    navBarHolder = (RelativeLayout) findViewById(R.id.navbar_holder);
    List<String> imageUrls = new ArrayList<>();
    imageUrls.add(product.imageURL);
    imageUrls.addAll(product.imageUrls);

    final float density = getResources().getDisplayMetrics().density;
    int topBarHeight = (int) (TOP_BAR_HEIGHT * density);
    TextView apply_button = (TextView) findViewById(R.id.apply_button);
    View basket = findViewById(R.id.basket);
    View bottomSeparator = findViewById(R.id.bottom_separator);
    quantity = (EditText) findViewById(R.id.quantity);

    roundsList = (RecyclerView) findViewById(R.id.details_recyclerview);
    if (imageUrls.size() <= 1)
        roundsList.setVisibility(View.GONE);

    LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

    roundsList.setLayoutManager(layoutManager);
    pager = (ViewPager) findViewById(R.id.viewpager);

    if (!"".equals(imageUrls.get(0))) {

        final RoundAdapter rAdapter = new RoundAdapter(this, imageUrls);
        roundsList.setAdapter(rAdapter);

        float width = getResources().getDisplayMetrics().widthPixels;
        float height = getResources().getDisplayMetrics().heightPixels;
        height -= 2 * topBarHeight;
        height -= com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.getStatusBarHeight(this);
        pager.getLayoutParams().width = (int) width;
        pager.getLayoutParams().height = (int) height;
        newCurrentItem = 0;
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                oldCurrentItem = newCurrentItem;
                newCurrentItem = position;

                rAdapter.setCurrentItem(newCurrentItem);
                rAdapter.notifyItemChanged(newCurrentItem);

                if (oldCurrentItem != -1)
                    rAdapter.notifyItemChanged(oldCurrentItem);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        pager.setPageTransformer(true, new InnerPageTransformer());
        adapter = new DetailsViewPagerAdapter(getSupportFragmentManager(), imageUrls);
        roundsList.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int totalWidth = (int) (adapter.getCount() * 21 * density);
                int screenWidth = getResources().getDisplayMetrics().widthPixels;
                int position = parent.getChildAdapterPosition(view);

                if ((totalWidth < screenWidth) && position == 0)
                    outRect.left = (screenWidth - totalWidth) / 2;
            }
        });

        pager.setAdapter(adapter);
    } else {
        roundsList.setVisibility(View.GONE);
        pager.setVisibility(View.GONE);
    }
    buyLayout = (RelativeLayout) findViewById(R.id.details_buy_layout);

    if (product.itemType.equals(ProductItemType.EXTERNAL))
        quantity.setVisibility(View.GONE);
    else
        quantity.setVisibility(View.VISIBLE);

    if (Statics.isBasket) {
        buyLayout.setVisibility(View.VISIBLE);
        onShoppingCartItemAdded();
        apply_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideKeyboard();
                quantity.setText(StringUtils.isBlank(quantity.getText().toString()) ? "1"
                        : quantity.getText().toString());
                quantity.clearFocus();

                String message = "";
                int quant = Integer.valueOf(quantity.getText().toString());
                List<ShoppingCart.Product> products = ShoppingCart.getProducts();
                int count = 0;

                for (ShoppingCart.Product product : products)
                    count += product.getQuantity();

                try {
                    message = new PluralResources(getResources()).getQuantityString(R.plurals.items_to_cart,
                            count + quant, count + quant);
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                }

                int index = products.indexOf(new ShoppingCart.Product.Builder().setId(product.id).build());
                ShoppingCart.insertProduct(new ShoppingCart.Product.Builder().setId(product.id)
                        .setQuantity((index == -1 ? 0 : products.get(index).getQuantity()) + quant).build());
                onShoppingCartItemAdded();
                com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.showDialog(ProductDetails.this,
                        R.string.shopping_cart_dialog_title, message, R.string.shopping_cart_dialog_continue,
                        R.string.shopping_cart_dialog_view_cart,
                        new com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.OnDialogButtonClickListener() {
                            @Override
                            public void onPositiveClick(DialogInterface dialog) {
                                dialog.dismiss();
                            }

                            @Override
                            public void onNegativeClick(DialogInterface dialog) {
                                Intent intent = new Intent(ProductDetails.this, ShoppingCartPage.class);
                                ProductDetails.this.startActivity(intent);
                            }
                        });
            }
        });
        if (product.itemType.equals(ProductItemType.EXTERNAL)) {
            basket.setVisibility(View.GONE);
            apply_button.setText(product.itemButtonText);
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ProductDetails.this, ExternalProductDetailsActivity.class);
                    intent.putExtra("itemUrl", product.itemUrl);
                    startActivity(intent);
                }
            });
        } else {
            basket.setVisibility(View.VISIBLE);
            apply_button.setText(R.string.shopping_cart_add_to_cart);
        }
    } else {
        if (product.itemType.equals(ProductItemType.EXTERNAL))
            buyLayout.setVisibility(View.VISIBLE);
        else
            buyLayout.setVisibility(View.GONE);

        apply_button.setText(R.string.buy_now);
        basket.setVisibility(View.GONE);
        findViewById(R.id.cart_items).setVisibility(View.GONE);
        /*apply_button_padding_left = 0;
        apply_button.setGravity(Gravity.CENTER);
        apply_button.setPadding(apply_button_padding_left, 0, 0, 0);*/

        if (TextUtils.isEmpty(Statics.PAYPAL_CLIENT_ID) || product.price == 0) {
            bottomSeparator.setVisibility(View.GONE);
            apply_button.setVisibility(View.GONE);
            basket.setVisibility(View.GONE);

        } else {
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    payer.singlePayment(new Payer.Item.Builder().setPrice(product.price)
                            .setCurrencyCode(Payer.CurrencyCode.valueOf(Statics.uiConfig.currency))
                            .setName(product.name).setEndpoint(Statics.ENDPOINT).setAppId(Statics.appId)
                            .setWidgetId(Statics.widgetId).setItemId(product.item_id).build());
                }
            });
        }

        if (product.itemType.equals(ProductItemType.EXTERNAL)) {
            basket.setVisibility(View.GONE);
            apply_button.setText(product.itemButtonText);
            apply_button.setVisibility(View.VISIBLE);
            apply_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(ProductDetails.this, ExternalProductDetailsActivity.class);
                    intent.putExtra("itemUrl", product.itemUrl);
                    startActivity(intent);
                }
            });
        }
    }

    backBtn = (LinearLayout) findViewById(R.id.back_btn);
    backBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
    title = (TextView) findViewById(R.id.title_text);
    title.setMaxWidth((int) (screenWidth * 0.55));
    if (category != null && !TextUtils.isEmpty(category.name))
        title.setText(category.name);

    View basketBtn = findViewById(R.id.basket_view_btn);
    View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(ProductDetails.this, ShoppingCartPage.class);
            startActivity(intent);
        }
    };
    basketBtn.setOnClickListener(listener);
    View hamburgerView = findViewById(R.id.hamburger_view_btn);
    hamburgerView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            animateRootContainer();
        }
    });
    if (!showSideBar) {
        hamburgerView.setVisibility(View.GONE);
        basketBtn.setVisibility(View.VISIBLE);
        basketBtn.setVisibility(Statics.isBasket ? View.VISIBLE : View.GONE);
        findViewById(R.id.cart_items).setVisibility(View.VISIBLE);
    } else {
        hamburgerView.setVisibility(View.VISIBLE);
        findViewById(R.id.cart_items).setVisibility(View.INVISIBLE);
        basketBtn.setVisibility(View.GONE);
        if (Statics.isBasket)
            shopingCartIndex = setTopBarRightButton(basketBtn, getResources().getString(R.string.shopping_cart),
                    listener);
    }

    productTitle = (TextView) findViewById(R.id.product_title);
    productTitle.setText(product.name);

    product_sku = (TextView) findViewById(R.id.product_sku);

    if (TextUtils.isEmpty(product.sku)) {
        product_sku.setVisibility(View.GONE);
        product_sku.setText("");
    } else {
        product_sku.setVisibility(View.VISIBLE);
        product_sku.setText(getString(R.string.item_sku) + " " + product.sku);
    }

    productDescription = (WebView) findViewById(R.id.product_description);
    productDescription.getSettings().setJavaScriptEnabled(true);
    productDescription.getSettings().setDomStorageEnabled(true);
    productDescription.setWebChromeClient(new WebChromeClient());
    productDescription.setWebViewClient(new WebViewClient() {
        @Override
        public void onLoadResource(WebView view, String url) {
            if (!alreadyLoaded
                    && (url.startsWith("http://www.youtube.com/get_video_info?")
                            || url.startsWith("https://www.youtube.com/get_video_info?"))
                    && Build.VERSION.SDK_INT <= 11) {
                try {
                    String path = url.contains("https://www.youtube.com/get_video_info?")
                            ? url.replace("https://www.youtube.com/get_video_info?", "")
                            : url.replace("http://www.youtube.com/get_video_info?", "");

                    String[] parqamValuePairs = path.split("&");

                    String videoId = null;

                    for (String pair : parqamValuePairs) {
                        if (pair.startsWith("video_id")) {
                            videoId = pair.split("=")[1];
                            break;
                        }
                    }

                    if (videoId != null) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                                .setData(Uri.parse("http://www.youtube.com/watch?v=" + videoId)));

                        alreadyLoaded = !alreadyLoaded;
                    }
                } catch (Exception ex) {
                }
            } else {
                super.onLoadResource(view, url);
            }
        }

        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
            final AlertDialog.Builder builder = new AlertDialog.Builder(ProductDetails.this);
            builder.setMessage(R.string.catalog_notification_error_ssl_cert_invalid);
            builder.setPositiveButton(ProductDetails.this.getResources().getString(R.string.catalog_continue),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.proceed();
                        }
                    });
            builder.setNegativeButton(ProductDetails.this.getResources().getString(R.string.catalog_cancel),
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            handler.cancel();
                        }
                    });
            final AlertDialog dialog = builder.create();
            dialog.show();
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (url.contains("youtube.com/embed")) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                        .setData(Uri.parse(url)));
            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
                startActivity(intent);

                return true;
            } else if (url.startsWith("mailto:")) {
                Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
                startActivity(intent);

                return true;
            } else if (url.contains("youtube.com")) {
                try {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com"))
                            .setData(Uri.parse(url)));

                    return true;
                } catch (Exception ex) {
                    return false;
                }
            } else if (url.contains("goo.gl") || url.contains("maps") || url.contains("maps.yandex")
                    || url.contains("livegpstracks")) {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setData(Uri.parse(url)));
                return true;
            } else {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)).setData(Uri.parse(url)));
                return true;
            }
        }
    });
    productDescription.loadDataWithBaseURL(null, product.description, "text/html", "UTF-8", null);

    productPrice = (TextView) findViewById(R.id.product_price);
    productPrice.setVisibility(
            "0.00".equals(String.format(Locale.US, "%.2f", product.price)) ? View.GONE : View.VISIBLE);
    String result = com.ibuildapp.romanblack.CataloguePlugin.utils.Utils
            .currencyToPosition(Statics.uiConfig.currency, product.price);
    if (result.contains(getResources().getString(R.string.rest_number_pattern)))
        result = result.replace(getResources().getString(R.string.rest_number_pattern), "");
    productPrice.setText(result);

    likeCount = (TextView) findViewById(R.id.like_count);
    likeImage = (ImageView) findViewById(R.id.like_image);

    if (!TextUtils.isEmpty(product.imageURL)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                String token = FacebookAuthorizationActivity.getFbToken(
                        com.appbuilder.sdk.android.Statics.FACEBOOK_APP_ID,
                        com.appbuilder.sdk.android.Statics.FACEBOOK_APP_SECRET);
                if (TextUtils.isEmpty(token))
                    return;

                List<String> urls = new ArrayList<String>();
                urls.add(product.imageURL);
                final Map<String, String> res = FacebookAuthorizationActivity.getLikesForUrls(urls, token);
                if (res != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            likeCount.setText(res.get(product.imageURL));
                        }
                    });
                }
                Log.e("", "");
            }
        }).start();
    }

    shareBtn = (LinearLayout) findViewById(R.id.share_button);
    if (Statics.uiConfig.showShareButton)
        shareBtn.setVisibility(View.VISIBLE);
    else
        shareBtn.setVisibility(View.GONE);

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

            showDialogSharing(new DialogSharing.Configuration.Builder()
                    .setFacebookSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            // checking Internet connection
                            if (!Utils.networkAvailable(ProductDetails.this))
                                Toast.makeText(ProductDetails.this,
                                        getResources().getString(R.string.alert_no_internet),
                                        Toast.LENGTH_SHORT).show();
                            else {
                                if (Authorization
                                        .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_FACEBOOK) != null) {
                                    shareFacebook();
                                } else {
                                    Authorization.authorize(ProductDetails.this,
                                            FACEBOOK_AUTHORIZATION_ACTIVITY,
                                            Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                                }
                            }
                        }
                    }).setTwitterSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            // checking Internet connection
                            if (!Utils.networkAvailable(ProductDetails.this))
                                Toast.makeText(ProductDetails.this,
                                        getResources().getString(R.string.alert_no_internet),
                                        Toast.LENGTH_SHORT).show();
                            else {
                                if (Authorization
                                        .getAuthorizedUser(Authorization.AUTHORIZATION_TYPE_TWITTER) != null) {
                                    shareTwitter();
                                } else {
                                    Authorization.authorize(ProductDetails.this, TWITTER_AUTHORIZATION_ACTIVITY,
                                            Authorization.AUTHORIZATION_TYPE_TWITTER);
                                }
                            }
                        }
                    }).setEmailSharingClickListener(new DialogSharing.Item.OnClickListener() {
                        @Override
                        public void onClick() {
                            Intent intent = chooseEmailClient();
                            intent.setType("text/html");

                            // *************************************************************************************************
                            // preparing sharing message
                            String downloadThe = getString(R.string.directoryplugin_email_download_this);
                            String androidIphoneApp = getString(
                                    R.string.directoryplugin_email_android_iphone_app);
                            String postedVia = getString(R.string.directoryplugin_email_posted_via);
                            String foundThis = getString(R.string.directoryplugin_email_found_this);

                            // prepare content
                            String downloadAppUrl = String.format(
                                    "http://%s/projects.php?action=info&projectid=%s",
                                    com.appbuilder.sdk.android.Statics.BASE_DOMEN, Statics.appId);

                            String adPart = String.format(
                                    downloadThe + " %s " + androidIphoneApp + ": <a href=\"%s\">%s</a><br>%s",
                                    Statics.appName, downloadAppUrl, downloadAppUrl,
                                    postedVia + " <a href=\"http://ibuildapp.com\">www.ibuildapp.com</a>");

                            // content part
                            String contentPath = String.format(
                                    "<!DOCTYPE html><html><body><b>%s</b><br><br>%s<br><br>%s</body></html>",
                                    product.name, product.description,
                                    com.ibuildapp.romanblack.CataloguePlugin.Statics.hasAd ? adPart : "");

                            contentPath = contentPath.replaceAll("\\<img.*?>", "");

                            // prepare image to attach
                            // FROM ASSETS
                            InputStream stream = null;
                            try {
                                if (!TextUtils.isEmpty(product.imageRes)) {
                                    stream = manager.open(product.imageRes);

                                    String fileName = inputStreamToFile(stream);
                                    File copyTo = new File(fileName);
                                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(copyTo));
                                }
                            } catch (IOException e) {
                                // from cache
                                File copyTo = new File(product.imagePath);
                                if (copyTo.exists()) {
                                    intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(copyTo));
                                }
                            }

                            intent.putExtra(Intent.EXTRA_SUBJECT, product.name);
                            intent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(contentPath));
                            startActivity(intent);
                        }
                    }).build());

            //                openOptionsMenu();
        }
    });

    likeBtn = (LinearLayout) findViewById(R.id.like_button);
    if (Statics.uiConfig.showLikeButton)
        likeBtn.setVisibility(View.VISIBLE);
    else
        likeBtn.setVisibility(View.GONE);

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

            if (Utils.networkAvailable(ProductDetails.this)) {
                if (!TextUtils.isEmpty(product.imageURL)) {
                    if (Authorization.isAuthorized(Authorization.AUTHORIZATION_TYPE_FACEBOOK)) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {

                                List<String> userLikes = null;
                                try {
                                    userLikes = FacebookAuthorizationActivity.getUserOgLikes();
                                    for (String likeUrl : userLikes) {
                                        if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) {
                                            likedbyMe = true;
                                            break;
                                        }
                                    }

                                    if (!likedbyMe) {
                                        if (FacebookAuthorizationActivity.like(product.imageURL)) {
                                            String likeCountStr = likeCount.getText().toString();
                                            try {
                                                final int res = Integer.parseInt(likeCountStr);

                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        likeCount.setText(Integer.toString(res + 1));
                                                        enableLikeButton(false);
                                                        Toast.makeText(ProductDetails.this,
                                                                getString(R.string.like_success),
                                                                Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            } catch (NumberFormatException e) {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        Toast.makeText(ProductDetails.this,
                                                                getString(R.string.like_error),
                                                                Toast.LENGTH_SHORT).show();
                                                    }
                                                });
                                            }
                                        }
                                    } else {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                enableLikeButton(false);
                                                Toast.makeText(ProductDetails.this,
                                                        getString(R.string.already_liked), Toast.LENGTH_SHORT)
                                                        .show();
                                            }
                                        });
                                    }
                                } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) {
                                    if (!Utils.networkAvailable(ProductDetails.this)) {
                                        Toast.makeText(ProductDetails.this,
                                                getString(R.string.alert_no_internet), Toast.LENGTH_SHORT)
                                                .show();
                                        return;
                                    }
                                    Authorization.authorize(ProductDetails.this, AUTHORIZATION_FB,
                                            Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                                } catch (FacebookAuthorizationActivity.FacebookAlreadyLiked facebookAlreadyLiked) {
                                    facebookAlreadyLiked.printStackTrace();
                                }

                            }
                        }).start();
                    } else {
                        if (!Utils.networkAvailable(ProductDetails.this)) {
                            Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet),
                                    Toast.LENGTH_SHORT).show();
                            return;
                        }
                        Authorization.authorize(ProductDetails.this, AUTHORIZATION_FB,
                                Authorization.AUTHORIZATION_TYPE_FACEBOOK);
                    }
                } else
                    Toast.makeText(ProductDetails.this, getString(R.string.nothing_to_like), Toast.LENGTH_SHORT)
                            .show();
            } else
                Toast.makeText(ProductDetails.this, getString(R.string.alert_no_internet), Toast.LENGTH_SHORT)
                        .show();
        }
    });

    if (TextUtils.isEmpty(product.imageURL)) {
        enableLikeButton(false);
    } else {
        if (Authorization.isAuthorized(Authorization.AUTHORIZATION_TYPE_FACEBOOK)) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    List<String> userLikes = null;
                    try {
                        userLikes = FacebookAuthorizationActivity.getUserOgLikes();
                        for (String likeUrl : userLikes) {
                            if (likeUrl.compareToIgnoreCase(product.imageURL) == 0) {
                                likedbyMe = true;
                                break;
                            }
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                enableLikeButton(!likedbyMe);
                            }
                        });
                    } catch (FacebookAuthorizationActivity.FacebookNotAuthorizedException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

    // product bitmap rendering
    image = (AlphaImageView) findViewById(R.id.product_image);
    image.setVisibility(View.GONE);
    if (!TextUtils.isEmpty(product.imageRes)) {
        try {
            InputStream input = manager.open(product.imageRes);
            Bitmap btm = BitmapFactory.decodeStream(input);
            if (btm != null) {
                int ratio = btm.getWidth() / btm.getHeight();
                image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, screenWidth / ratio));

                image.setImageBitmapWithAlpha(btm);
                //image.setImageBitmap(btm);
                return;
            }
        } catch (IOException e) {
        }
    }

    if (!TextUtils.isEmpty(product.imagePath)) {
        Bitmap btm = BitmapFactory.decodeFile(product.imagePath);
        if (btm != null) {
            if (btm.getWidth() != 0 && btm.getHeight() != 0) {
                float ratio = (float) btm.getWidth() / (float) btm.getHeight();
                image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth, (int) (screenWidth / ratio)));
                image.setImageBitmapWithAlpha(btm);
                image.setVisibility(View.GONE);
                return;
            }
        }
    }

    if (!TextUtils.isEmpty(product.imageURL)) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                product.imagePath = com.ibuildapp.romanblack.CataloguePlugin.utils.Utils
                        .downloadFile(product.imageURL);
                if (!TextUtils.isEmpty(product.imagePath)) {
                    SqlAdapter.updateProduct(product);
                    final Bitmap btm = BitmapFactory.decodeFile(product.imagePath);

                    if (btm != null) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (btm.getWidth() != 0 && btm.getHeight() != 0) {
                                    float ratio = (float) btm.getWidth() / (float) btm.getHeight();
                                    image.setLayoutParams(new LinearLayout.LayoutParams(screenWidth,
                                            (int) (screenWidth / ratio)));
                                    image.setImageBitmapWithAlpha(btm);
                                    image.setVisibility(View.GONE);
                                }
                            }
                        });
                    }
                }
            }
        }).start();
    }

    image.setVisibility(View.GONE);
}

From source file:com.skyousuke.ivtool.windows.MainWindow.java

@SuppressLint("InflateParams")
public MainWindow(final Context context, WindowManager windowManager, Handler handler) {
    this.context = context;
    this.windowManager = windowManager;
    this.handler = handler;
    inputData.setListener(this);

    layout = (CustomRelativeLayout) LayoutInflater.from(context).inflate(R.layout.tool_window, null);
    pokemonView = (AutoCompleteTextView) layout.findViewById(R.id.pokemon);
    dustView = (AutoCompleteTextView) layout.findViewById(R.id.dust);
    cpView = (AutoCompleteTextView) layout.findViewById(R.id.cp);
    hpView = (AutoCompleteTextView) layout.findViewById(R.id.hp);
    maxIVTextView = (TextView) layout.findViewById(R.id.max_iv);
    minIVTextView = (TextView) layout.findViewById(R.id.min_iv);
    final CheckBox powerUpCheck = (CheckBox) layout.findViewById(R.id.check_powered);
    TextView textCheck = (TextView) layout.findViewById(R.id.powered);
    message = (TextView) layout.findViewById(R.id.message);
    pokemonValidation = (ImageView) layout.findViewById(R.id.image_validation_pokemon);
    dustValidation = (ImageView) layout.findViewById(R.id.image_validation_dust);
    cpValidation = (ImageView) layout.findViewById(R.id.image_validation_cp);
    hpValidation = (ImageView) layout.findViewById(R.id.image_validation_hp);
    powerUpValidation = (ImageView) layout.findViewById(R.id.image_validation_power_up);
    seeResultButton = (Button) layout.findViewById(R.id.button_tool);
    appraisalButton = (Button) layout.findViewById(R.id.button_appraisal);

    appraisalLayout = (LinearLayout) layout.findViewById(R.id.appraisal);
    teamSelectLayout = (LinearLayout) layout.findViewById(R.id.team_select);
    teamSpinner = (Spinner) teamSelectLayout.findViewById(R.id.spinner_team);
    rangePhraseSpinner = (Spinner) layout.findViewById(R.id.spinner_iv_phrase);
    statPhraseSpinner = (Spinner) layout.findViewById(R.id.spinner_stats_phrase);
    appraisalWrong = (TextView) layout.findViewById(R.id.appraisal_wrong);

    layoutParams.gravity = Gravity.TOP | Gravity.CENTER;

    enableBackKey(true);//from  w  ww. j  a  v  a2  s .  c o m
    setTouchListener();

    pokemonView.setAdapter(new ArrayAdapter<>(context, R.layout.simple_dropdown, Pokemon.values));
    pokemonView.addTextChangedListener(new DefaultTextChangedListener() {
        @Override
        public void afterTextChanged(Editable editable) {
            inputData.setPokemon(editable.toString());
            updateValidation();
        }
    });
    pokemonView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> p, View v, int pos, long id) {
            if (inputData.isDustUnset())
                focusDustView();
        }
    });
    pokemonView.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus) {
                pokemonView.setText("");
            }
        }
    });
    pokemonView.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                focusDustView();
                return true;
            }
            return false;
        }
    });
    dustView.setAdapter(new ArrayAdapter<>(context, R.layout.simple_dropdown, IVCalculator.dustList));
    dustView.addTextChangedListener(new DefaultTextChangedListener() {
        @Override
        public void afterTextChanged(Editable editable) {
            inputData.setDust(editable.toString());
            updateValidation();
        }
    });
    dustView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> p, View v, int pos, long id) {
            if (inputData.isCpUnset())
                focusCpView();
        }
    });
    dustView.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus) {
                dustView.setText("");
            }
        }
    });
    dustView.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                focusCpView();
                return true;
            }
            return false;
        }
    });

    cpView.addTextChangedListener(new DefaultTextChangedListener() {
        @Override
        public void afterTextChanged(Editable editable) {
            inputData.setCp(editable.toString());
            updateValidation();
        }
    });
    cpView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> p, View v, int pos, long id) {
            if (inputData.isHpUnset())
                focusHpView();
        }
    });
    cpView.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus) {
                cpView.setText("");
            }
        }
    });
    cpView.setOnEditorActionListener(new OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_NEXT) {
                focusHpView();
                return true;
            }
            return false;
        }
    });
    hpView.addTextChangedListener(new DefaultTextChangedListener() {
        @Override
        public void afterTextChanged(Editable editable) {
            inputData.setHp(editable.toString());
            updateValidation();
        }
    });
    hpView.setOnFocusChangeListener(new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean hasFocus) {
            if (hasFocus) {
                hpView.setText("");
            }
        }
    });
    powerUpCheck.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            inputData.setPoweredUp(isChecked);
            updateValidation();
        }
    });
    textCheck.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            powerUpCheck.toggle();
        }
    });
    seeResultButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            if (resultWindow != null) {
                resultWindow.show();
                enableBackKey(false);
            }
        }
    });

    hideAppraisal();
}

From source file:app.clirnet.com.clirnetapp.activity.LoginActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Fabric.with(this, new Crashlytics());
    setContentView(R.layout.activity_login);

    ButterKnife.inject(this);

    try {//from   w  w  w. j av a 2 s . c  o m
        /*message from fcm service*/
        msg = getIntent().getStringExtra("MSG");
        type = getIntent().getStringExtra("TYPE");
        actionPath = getIntent().getStringExtra("ACTION_PATH");
        headerMsg = getIntent().getStringExtra("HEADER");
        clubbingFlag = getIntent().getStringExtra("CLUBBINGFLAG");
        notificationTreySize = getIntent().getIntExtra("NOTIFITREYSIZE", 0);
        // Log.e("Loginmsg", "  " + msg + "  header " + headerMsg + "  " +type + "  "+actionPath);
        /*Clearing notifications ArrayList from MyFirebaseMessagingService after clicking on it*/

        MyFirebaseMessagingService.notifications.clear();

        // FirebaseCrash.setCrashCollectionEnabled(false);

    } catch (Exception e) {
        appController.appendLog(appController.getDateTime() + "" + "/" + "Navigation Activity" + e
                + " Line Number: " + Thread.currentThread().getStackTrace()[2].getLineNumber());
    }

    TextView btnLinkToForgetScreen = (TextView) findViewById(R.id.btnLinkToForgetScreen);

    DatabaseClass databaseClass = new DatabaseClass(getApplicationContext());
    bannerClass = new BannerClass(getApplicationContext());
    LastnameDatabaseClass lastnameDatabaseClass = new LastnameDatabaseClass(getApplicationContext());
    dbController = SQLiteHandler.getInstance(getApplicationContext());
    appController = new AppController();

    if (md5 == null) {
        md5 = new MD5();
    }

    //getCurrentDob(21);
    //getCurrentDob(10);

    //this will set value to run  asynctask only once per login session

    new CallAsynOnce().setValue("1");//this set value which helps to call asyntask only once while app is running.

    // Progress dialog

    connectionDetector = new ConnectionDetector(getApplicationContext());

    try {
        sInstance = SQLiteHandler.getInstance(getApplicationContext());
        if (sqlController == null) {
            sqlController = new SQLController(getApplicationContext());
            sqlController.open();
        }
        // sInstance = SQLiteHandler.getInstance(getApplicationContext());

        Boolean value = getFirstTimeLoginStatus();

        if (value) {
            phoneNumber = sqlController.getPhoneNumber();

            doctor_membership_number = sqlController.getDoctorMembershipIdNew();
            docId = sqlController.getDoctorId();
        }

    } catch (Exception e) {
        e.printStackTrace();
        appController.appendLog(appController.getDateTimenew() + " " + "/ " + "Login Page" + e
                + " Line Number: " + Thread.currentThread().getStackTrace()[2].getLineNumber());
    }

    try {

        databaseClass.createDataBase();
        bannerClass.createDataBase();

    } catch (Exception ioe) {
        appController.appendLog(appController.getDateTimenew() + "" + "/" + "Login Page" + ioe
                + " Line Number: " + Thread.currentThread().getStackTrace()[2].getLineNumber());

        throw new Error("Unable to create database");
    }

    try {

        databaseClass.openDataBase();
        bannerClass.openDataBase();

        /*This AsyncTask will Insert data from Asset folder file to data 23-03-2016*/
        new InsertDataLocally().execute();

    } catch (Exception e) {
        e.printStackTrace();
        appController.appendLog(appController.getDateTimenew() + "" + "/" + "Login Page" + e + " Line Number: "
                + Thread.currentThread().getStackTrace()[2].getLineNumber());

    } finally {
        databaseClass.close();
    }

    try {

        lastnameDatabaseClass.createDataBase();

    } catch (IOException e) {

        appController.appendLog(appController.getDateTimenew() + "" + "/" + "Login Page" + e + " Line Number: "
                + Thread.currentThread().getStackTrace()[2].getLineNumber());

        throw new Error("Unable to create database");
    }
    try {

        lastnameDatabaseClass.openDataBase();

        getUsernamePasswordFromDatabase();

    } catch (Exception e) {
        e.printStackTrace();
        appController.appendLog(appController.getDateTimenew() + "" + "/" + "Login Page" + e + " Line Number: "
                + Thread.currentThread().getStackTrace()[2].getLineNumber());

    } finally {
        lastnameDatabaseClass.close();
    }
    btnLogin.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_UP) {

                hideKeyBoard();
                btnLogin.setBackground(getResources().getDrawable(R.drawable.rounded_corner_withbackground));
                name = inputEmail.getText().toString().trim();
                strPassword = inputPassword.getText().toString().trim();

                String time = appController.getDateTimenew();
                AppController.getInstance().trackEvent("Login", "Login Pressed");

                //This code used for Remember Me(ie. save login id and password for future ref.)
                rememberMe(name, strPassword, time); //save username only

                //rememberMeCheckbox();//Removed remeber me check box for safety concern 04-11-16

                //to authenticate user credentials
                //Log.e("name",""+name +" savedUserName "+savedUserName+ " phoneNumber "+phoneNumber);
                //if(name.equals(savedUserName) || name.equals(phoneNumber))
                LoginAuthentication();
                // else appController.showToastMsg(getApplicationContext(),"This username is not licensed to log into this device. Please check username");

            } else if (event.getAction() == MotionEvent.ACTION_DOWN) {

                btnLogin.setBackground(
                        getResources().getDrawable(R.drawable.rounded_corner_withbackground_blue));
            }
            return false;
        }

    });

    /*We are updating visit date format*/
    // updateVisitDateFormat(); //Commented on  10-05-2017

    addVitalsIntoInvstigation();

    //Commented on  10-05-2017
    /*  Updateing banner stats flag to 0 build no 1.3+  */
    /*Updating associate master flag from 1 to 0*/
    String bannerUpdateFlag = getupdateBannerClickVisitFlag0();
    if (bannerUpdateFlag == null || bannerUpdateFlag.equals("true")) {
        updateBannerTableDataFlag();
    }

    // Link to Register Screen
    btnLinkToForgetScreen.setOnClickListener(new View.OnClickListener()

    {

        public void onClick(View view) {
            boolean isInternetPresent = connectionDetector.isConnectingToInternet();
            if (isInternetPresent) {
                showChangePassDialog();
            } else {
                appController.showToastMsg(getApplicationContext(),
                        "Please Connect To Internet And Try Again!");
            }

        }
    });

    if (checkAndRequestPermissions()) {
        // carry on the normal flow, as the case of  permissions  granted.
    }

}

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

private void choosePicture() {
    if (cameraDialog == null) {
        LayoutInflater dialogInflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        final View dialogView = dialogInflater.inflate(R.layout.dialog_camera_gallery, null);
        TextView camera = (TextView) dialogView.findViewById(R.id.dialog_camera);
        TextView gallery = (TextView) dialogView.findViewById(R.id.dialog_gallery);
        TFCache.apply(activity, camera, TFCache.TF_SPEAKALL);
        TFCache.apply(activity, gallery, TFCache.TF_SPEAKALL);
        final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity).setView(dialogView)
                .setCancelable(true);/*from  w  ww  .j  a  v a  2  s . c  om*/
        cameraDialog = dialogBuilder.show();
        camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraDialog.dismiss();
                dontClose = true;
                ((MainActivity) activity).dontClose = true;
                hideKeyBoard();
                File imagesFolder = new File(
                        Environment.getExternalStorageDirectory().getAbsolutePath() + "/SpeakOn/Image/Sent");
                imagesFolder.mkdirs();
                menuAdjunt = false;
                adjuntLayout.setVisibility(View.GONE);
                dateToCamera = Calendar.getInstance().getTimeInMillis();
                File image = new File(imagesFolder, dateToCamera + ".png");
                Uri uriSavedImage = Uri.fromFile(image);
                pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                pictureActionIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
                startActivityForResult(pictureActionIntent, 23);
            }
        });
        gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cameraDialog.dismiss();
                dontClose = true;
                ((MainActivity) activity).dontClose = true;
                hideKeyBoard();
                menuAdjunt = false;
                adjuntLayout.setVisibility(View.GONE);
                pictureActionIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(pictureActionIntent, 1);
            }
        });
        cameraDialog.setCanceledOnTouchOutside(true);
    } else {
        cameraDialog.show();
    }
}

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

public void showMensajeMember(int position, Context context, final MsgGroups message, View rowView) {

    final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
    TextView messageDate = (TextView) rowView.findViewById(R.id.message_date);
    TextView messageMember = (TextView) rowView.findViewById(R.id.message_member);

    TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageMember, TFCache.TF_WHITNEY_MEDIUM);

    if (position == 0) {
        if (mensajesTotal > mensajesOffset) {
            prevMessages.setVisibility(View.VISIBLE);
            prevMessages.setOnClickListener(new View.OnClickListener() {
                @Override//from   www  .  ja v a 2s .  c o  m
                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);
            }
        }
    }

    messageMember.setText(message.mensaje);
}

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

public void showMensajeContact(int position, final Context context, final Message message, View rowView,
        TextView icnMessageArrow) {/*from ww w  .j av a2s .  c om*/

    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);
    TextView contactPhoto = (TextView) rowView.findViewById(R.id.contact_photo);
    TextView contactName = (TextView) rowView.findViewById(R.id.contact_name);
    final TextView contactPhone = (TextView) rowView.findViewById(R.id.contact_phone);

    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, contactPhoto, TFCache.TF_SPEAKALL);
    TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, contactName, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, contactPhone, TFCache.TF_WHITNEY_MEDIUM);

    try {
        JSONObject contactData = new JSONObject(message.mensaje);
        contactName.setText(contactData.getString("nombre"));
        contactPhone.setText(Html.fromHtml("<u>" + contactData.getString("telefono") + "</u>"));
        if (contactPhone.length() > 0) {
            contactPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dontClose = true;
                    ((MainActivity) activity).dontClose = true;
                    hideKeyBoard();
                    Intent intent = new Intent(Intent.ACTION_CALL,
                            Uri.parse("tel:" + contactPhone.getText().toString()));
                    context.startActivity(intent);
                }
            });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    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)) {
        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);
            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("message", message.mensaje);
                data.put("delay", message.delay);
                data.put("translation_required", message.translation);
                data.put("target_lang", message.receptorLang);
                data.put("type", message.tipo);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (SpeakSocket.mSocket != null)
                if (SpeakSocket.mSocket.connected()) {
                    message.status = 1;
                    SpeakSocket.mSocket.emit("message", data);
                } else {
                    message.status = -1;
                }
        }
        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();

                    if (mensaje.status != 4) {
                        notifyMessage.put("type", mensaje.tipo);
                        notifyMessage.put("message_id", mensaje.mensajeId);
                        notifyMessage.put("source", mensaje.receptor);
                        notifyMessage.put("target", mensaje.emisor);
                        notifyMessage.put("status", 5);
                        SpeakSocket.mSocket.emit("message-status", notifyMessage);
                    }
                    new Delete().from(Message.class).where("mensajeId = ?", mensaje.mensajeId).execute();
                    Message message = null;
                    if (mensaje.emisor.equals(u.id)) {
                        message = new Select().from(Message.class)
                                .where("emisor = ? or receptor = ?", mensaje.receptor, mensaje.receptor)
                                .orderBy("emitedAt DESC").executeSingle();
                    } else {
                        message = new Select().from(Message.class)
                                .where("emisor = ? or receptor = ?", mensaje.emisor, mensaje.emisor)
                                .orderBy("emitedAt DESC").executeSingle();
                    }
                    if (message != null) {
                        Chats chat = null;
                        if (mensaje.emisor.equals(u.id)) {
                            chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.receptor)
                                    .executeSingle();
                        } else {
                            chat = new Select().from(Chats.class).where("idContacto = ?", mensaje.emisor)
                                    .executeSingle();
                        }
                        if (chat != null) {
                            chat.mensajeId = message.mensajeId;
                            chat.lastStatus = message.status;
                            chat.emitedAt = message.emitedAt;
                            chat.lang = message.emisorLang;
                            chat.notRead = 0;
                            if (chat.idContacto.equals(message.emisor))
                                chat.lastMessage = message.mensajeTrad;
                            else
                                chat.lastMessage = message.mensaje;
                            chat.save();
                        }
                    } else {
                        if (mensaje.emisor.equals(u.id)) {
                            new Delete().from(Chats.class).where("idContacto = ?", mensaje.receptor).execute();
                        } else {
                            new Delete().from(Chats.class).where("idContacto = ?", mensaje.emisor).execute();
                        }
                    }

                    View delete = messagesList.findViewWithTag(mensaje.mensajeId);
                    if (delete != null)
                        messagesList.removeView(delete);
                    messageSelected = null;
                    ((MainActivity) activity).setOnBackPressedListener(null);
                } 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_TEXT))) {
            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) {
                    longclick = true;
                    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();
                longclick = true;
                return false;
            }
        });
        icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
            boolean translation = true;

            @Override
            public void onClick(View v) {
                translation = !translation;
                if (translation) {
                    icnMesajeTempo.setTextColor(getResources().getColor(R.color.speak_all_red));
                } else {
                    icnMesajeTempo.setTextColor(getResources().getColor(R.color.speak_all_white));
                }
            }
        });
    }

    /*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)) {
                    longclick = true;
                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                    ((MainActivity) activity).setOnBackPressedListener(null);
                    messageSelected = null;
                }
            }
            Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                    .executeSingle();
            if (mensaje.status == -1) {
                String message = mensaje.mensaje;
                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("message", mensaje.mensaje);
                    data.put("delay", mensaje.delay);
                    data.put("type", mensaje.tipo);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                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);
            }
            if (!mensaje.emisor.equals(u.id)) {
                if (!longclick) {
                    showDialogAddContact(mensaje.mensaje);
                }
                longclick = false;
            }
        }
    });
}

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

public void showMensajeContact(int position, final Context context, final MsgGroups message, View rowView,
        TextView icnMessageArrow) {//from   ww w  .j a  va2s .  c  o m

    final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
    TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
    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);
    TextView contactPhoto = (TextView) rowView.findViewById(R.id.contact_photo);
    final TextView contactName = (TextView) rowView.findViewById(R.id.contact_name);
    final TextView contactPhone = (TextView) rowView.findViewById(R.id.contact_phone);
    final CircleImageView imageUser = (CircleImageView) rowView.findViewById(R.id.chat_row_user_pic);
    final TextView userName = (TextView) rowView.findViewById(R.id.username_text);

    TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, icnMesajeCopy, TFCache.TF_SPEAKALL);
    TFCache.apply(context, icnMesajeBack, TFCache.TF_SPEAKALL);
    TFCache.apply(context, messageStatus, TFCache.TF_SPEAKALL);
    TFCache.apply(context, contactPhoto, TFCache.TF_SPEAKALL);
    TFCache.apply(context, prevMessages, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageDate, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, contactName, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, contactPhone, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, userName, TFCache.TF_WHITNEY_MEDIUM);

    try {
        JSONObject contactData = new JSONObject(message.mensaje);
        contactName.setText(contactData.getString("nombre"));
        contactPhone.setText(Html.fromHtml("<u>" + contactData.getString("telefono") + "</u>"));
        if (contactPhone.length() > 0) {
            contactPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((MainActivity) activity).dontClose = true;
                    hideKeyBoard();
                    Intent intent = new Intent(Intent.ACTION_CALL,
                            Uri.parse("tel:" + contactPhone.getText().toString()));
                    context.startActivity(intent);
                }
            });
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    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)) {
        int status = 0;
        try {
            JSONArray contactos = new JSONArray(message.receptores);
            for (int i = 0; i < contactos.length(); i++) {
                JSONObject contacto = contactos.getJSONObject(i);
                if (status == 0 || contacto.getInt("status") <= status) {
                    status = contacto.getInt("status");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (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);
                    MsgGroups mensaje = new Select().from(MsgGroups.class)
                            .where("mensajeId = ?", message.mensajeId).executeSingle();
                    int status = 0;
                    try {
                        JSONArray contactos = new JSONArray(message.receptores);
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            if (status == 0 || contacto.getInt("status") <= status) {
                                status = contacto.getInt("status");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (status != 4) {
                        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();
                    } 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 (status == 1) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
            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);
            JSONObject data = new JSONObject();
            try {
                data.put("type", message.tipo);
                data.put("group_id", message.grupoId);
                data.put("group_name", grupo.nombreGrupo);
                data.put("source", message.emisor);
                data.put("source_email", message.emisorEmail);
                data.put("message", message.mensaje);
                data.put("source_lang", message.emisorLang);
                data.put("translation_required", message.translation);
                data.put("message_id", message.mensajeId);
                data.put("delay", message.delay);
                JSONArray targets = new JSONArray();
                JSONArray contactos = new JSONArray(grupo.targets);
                if (SpeakSocket.mSocket != null) {
                    if (SpeakSocket.mSocket.connected()) {
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            JSONObject newContact = new JSONObject();
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", contacto.getString("name")).executeSingle();
                            if (contact != null) {
                                if (!contact.idContacto.equals(u.id)) {
                                    if (message.translation)
                                        newContact.put("lang", contact.lang);
                                    else
                                        newContact.put("lang", u.lang);
                                    newContact.put("name", contact.idContacto);
                                    newContact.put("screen_name", contact.screenName);
                                    newContact.put("status", 1);
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                        data.put("targets", targets);
                        message.receptores = targets.toString();
                        message.save();
                        SpeakSocket.mSocket.emit("message", data);
                    } else {
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            JSONObject newContact = new JSONObject();
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", contacto.getString("name")).executeSingle();
                            if (contact != null) {
                                if (!contact.idContacto.equals(u.id)) {
                                    if (message.translation)
                                        newContact.put("lang", contact.lang);
                                    else
                                        newContact.put("lang", u.lang);
                                    newContact.put("name", contact.idContacto);
                                    newContact.put("screen_name", contact.screenName);
                                    newContact.put("status", -1);
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                        message.receptores = targets.toString();
                        message.save();
                    }
                    changeStatus(message.mensajeId);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (status == -1) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_errorout_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
        }
        if (status == 2) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
        }
        if (status == 3) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
        }
        if (status == 4) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
        }

    } else {
        final Contact contacto = new Select().from(Contact.class).where(" id_contact= ?", message.emisor)
                .executeSingle();
        if (contacto != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (contacto.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(contacto.photo, 0,
                                        contacto.photo.length);
                                imageUser.setImageBitmap(bmp);
                                userName.setText(contacto.fullName);
                            }
                        }
                    });
                }
            }).start();
        }
        rowView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                if (messageSelected != null) {
                    longclick = true;
                    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);
                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;
            }
        });
    }

    icnMesajeBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (message.emisor.equals(u.id)) {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container3, ForwarForFragment.newInstance(message.mensaje))
                        .addToBackStack(null).commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            } else {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container3, 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)) {
                    longclick = true;
                    vista.findViewById(messageMenu.getId()).setVisibility(View.INVISIBLE);
                    ((MainActivity) activity).setOnBackPressedListener(null);
                    messageSelected = null;
                }
            }

            MsgGroups mensaje = new Select().from(MsgGroups.class).where("mensajeId = ?", message.mensajeId)
                    .executeSingle();

            int status = 0;
            try {
                JSONArray contactos = new JSONArray(mensaje.receptores);
                for (int i = 0; i < contactos.length(); i++) {
                    JSONObject contacto = contactos.getJSONObject(i);
                    if (status == 0 || contacto.getInt("status") <= status) {
                        status = contacto.getInt("status");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (status == -1) {
                JSONObject data = new JSONObject();
                try {
                    data.put("type", mensaje.tipo);
                    data.put("group_id", mensaje.grupoId);
                    data.put("group_name", grupo.nombreGrupo);
                    data.put("source", mensaje.emisor);
                    data.put("source_email", mensaje.emisorEmail);
                    data.put("source_lang", mensaje.emisorLang);
                    data.put("message", mensaje.mensaje);
                    data.put("translation_required", mensaje.translation);
                    data.put("message_id", mensaje.mensajeId);
                    data.put("delay", mensaje.delay);
                    JSONArray targets = new JSONArray();
                    JSONArray contactos = new JSONArray(grupo.targets);
                    if (SpeakSocket.mSocket != null) {
                        if (SpeakSocket.mSocket.connected()) {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (mensaje.translation)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", 1);
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                            data.put("targets", targets);
                            mensaje.receptores = targets.toString();
                            mensaje.save();
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (mensaje.translation)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", -1);
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                            mensaje.receptores = targets.toString();
                            mensaje.save();
                        }
                        changeStatus(mensaje.mensajeId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (!mensaje.emisor.equals(u.id)) {
                    if (!longclick) {
                        showDialogAddContact(mensaje.mensaje);
                    }
                    longclick = false;
                }
            }
        }
    });

}

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

public void showMensajeText(int position, Context context, final MsgGroups message, View rowView,
        TextView icnMessageArrow) {/* w w  w .  j a v  a2  s  .c  om*/

    final TextView prevMessages = (TextView) rowView.findViewById(R.id.showprev_messages);
    TextView messageTime = (TextView) rowView.findViewById(R.id.message_time);
    final TextView icnMesajeCopy = (TextView) rowView.findViewById(R.id.icn_message_copy);
    final TextView icnMesajeBack = (TextView) rowView.findViewById(R.id.icn_message_back);
    final TextView messageContent = (TextView) rowView.findViewById(R.id.message_content);
    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 CircleImageView imageUser = (CircleImageView) rowView.findViewById(R.id.chat_row_user_pic);
    final TextView userName = (TextView) rowView.findViewById(R.id.username_text);

    TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageContent, TFCache.TF_WHITNEY_MEDIUM);
    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, userName, TFCache.TF_WHITNEY_MEDIUM);

    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)) {
        messageContent.setText(message.mensaje);
        int status = 0;
        try {
            JSONArray contactos = new JSONArray(message.receptores);
            for (int i = 0; i < contactos.length(); i++) {
                JSONObject contacto = contactos.getJSONObject(i);
                Log.w("STATUS", contacto.getInt("status") + contacto.getString("name"));
                if (status == 0 || contacto.getInt("status") <= status) {
                    status = contacto.getInt("status");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (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() {
                                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);
                    MsgGroups mensaje = new Select().from(MsgGroups.class)
                            .where("mensajeId = ?", message.mensajeId).executeSingle();
                    int status = 0;
                    try {
                        JSONArray contactos = new JSONArray(mensaje.receptores);
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            if (status == 0 || contacto.getInt("status") <= status) {
                                status = contacto.getInt("status");
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (status != 4) {
                        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();
                    } 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 (status == 1) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
            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);
            JSONObject data = new JSONObject();
            try {
                data.put("type", message.tipo);
                data.put("group_id", message.grupoId);
                data.put("group_name", grupo.nombreGrupo);
                data.put("source", message.emisor);
                data.put("source_lang", message.emisorLang);
                data.put("source_email", message.emisorEmail);
                data.put("message", message.mensaje);
                data.put("translation_required", message.translation);
                data.put("message_id", message.mensajeId);
                data.put("delay", message.delay);
                JSONArray targets = new JSONArray();
                JSONArray contactos = new JSONArray(grupo.targets);
                if (SpeakSocket.mSocket != null) {
                    if (SpeakSocket.mSocket.connected()) {
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            JSONObject newContact = new JSONObject();
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", contacto.getString("name")).executeSingle();
                            if (contact != null) {
                                if (!contact.idContacto.equals(u.id)) {
                                    if (message.translation)
                                        newContact.put("lang", contact.lang);
                                    else
                                        newContact.put("lang", u.lang);
                                    newContact.put("name", contact.idContacto);
                                    newContact.put("screen_name", contact.screenName);
                                    newContact.put("status", 1);
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                        data.put("targets", targets);
                        message.receptores = targets.toString();
                        message.save();
                        SpeakSocket.mSocket.emit("message", data);
                    } else {
                        for (int i = 0; i < contactos.length(); i++) {
                            JSONObject contacto = contactos.getJSONObject(i);
                            JSONObject newContact = new JSONObject();
                            Contact contact = new Select().from(Contact.class)
                                    .where("id_contact = ?", contacto.getString("name")).executeSingle();
                            if (contact != null) {
                                if (!contact.idContacto.equals(u.id)) {
                                    if (message.translation)
                                        newContact.put("lang", contact.lang);
                                    else
                                        newContact.put("lang", u.lang);
                                    newContact.put("name", contact.idContacto);
                                    newContact.put("screen_name", contact.screenName);
                                    newContact.put("status", -1);
                                    targets.put(targets.length(), newContact);
                                }
                            }
                        }
                        message.receptores = targets.toString();
                        message.save();
                    }
                    changeStatus(message.mensajeId);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if (status == -1) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_errorout_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_disable_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_ERROR.toString());
        }
        if (status == 2) {
            messageStatus.setTextSize(16);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_SEND.toString());
        }
        if (status == 3) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_CLOSED.toString());
        }
        if (status == 4) {
            messageStatus.setTextSize(11);
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            icnMessageArrow.setTextColor(getResources().getColor(R.color.speak_all_red));
            messageStatus.setText(Finder.STRING.ICN_MSJ_OPENED.toString());
        }

    } else {
        final Contact contacto = new Select().from(Contact.class).where(" id_contact= ?", message.emisor)
                .executeSingle();
        if (contacto != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (contacto.photo != null) {
                                Bitmap bmp = BitmapFactory.decodeByteArray(contacto.photo, 0,
                                        contacto.photo.length);
                                imageUser.setImageBitmap(bmp);
                                userName.setText(contacto.fullName);
                            }
                        }
                    });
                }
            }).start();
        }
        messageContent.setText(message.mensajeTrad);
        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);
                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;
            }
        });
    }

    if (message.orientation == 0) {
        messageContent.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (messageContent.getLineCount() > 1) {
                            mensajeLayout.setOrientation(LinearLayout.VERTICAL);
                            messageContent.setPadding(0, messageContent.getPaddingTop(), 0, 0);
                            new Update(Message.class).set("orientation = ?", 2)
                                    .where("mensajeId = ?", message.mensajeId).execute();
                            messageContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        } else {
                            new Update(Message.class).set("orientation = ?", 1)
                                    .where("mensajeId = ?", message.mensajeId).execute();
                            messageContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                    }
                });
    } else {
        if (message.orientation == 2) {
            mensajeLayout.setOrientation(LinearLayout.VERTICAL);
            messageContent.setPadding(0, messageContent.getPaddingTop(), 0, 0);
        }
    }

    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.container3, ForwarForFragment.newInstance(message.mensaje))
                        .addToBackStack(null).commit();
                ((MainActivity) activity).setOnBackPressedListener(null);
            } else {
                getFragmentManager().beginTransaction()
                        .replace(R.id.container3, 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;
                }
            }

            MsgGroups mensaje = new Select().from(MsgGroups.class).where("mensajeId = ?", message.mensajeId)
                    .executeSingle();

            int status = 0;
            try {
                JSONArray contactos = new JSONArray(mensaje.receptores);
                for (int i = 0; i < contactos.length(); i++) {
                    JSONObject contacto = contactos.getJSONObject(i);
                    if (status == 0 || contacto.getInt("status") <= status) {
                        status = contacto.getInt("status");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            if (status == -1) {
                JSONObject data = new JSONObject();
                try {
                    data.put("type", mensaje.tipo);
                    data.put("group_id", mensaje.grupoId);
                    data.put("group_name", grupo.nombreGrupo);
                    data.put("source", mensaje.emisor);
                    data.put("source_lang", mensaje.emisorLang);
                    data.put("message", mensaje.mensaje);
                    data.put("translation_required", mensaje.translation);
                    data.put("message_id", mensaje.mensajeId);
                    data.put("source_email", message.emisorEmail);
                    data.put("targets", new JSONArray(mensaje.receptores));
                    data.put("delay", mensaje.delay);
                    JSONArray targets = new JSONArray();
                    JSONArray contactos = new JSONArray(grupo.targets);
                    if (SpeakSocket.mSocket != null) {
                        if (SpeakSocket.mSocket.connected()) {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (mensaje.translation)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", 1);
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                            data.put("targets", targets);
                            mensaje.receptores = targets.toString();
                            mensaje.save();
                            SpeakSocket.mSocket.emit("message", data);
                        } else {
                            for (int i = 0; i < contactos.length(); i++) {
                                JSONObject contacto = contactos.getJSONObject(i);
                                JSONObject newContact = new JSONObject();
                                Contact contact = new Select().from(Contact.class)
                                        .where("id_contact = ?", contacto.getString("name")).executeSingle();
                                if (contact != null) {
                                    if (!contact.idContacto.equals(u.id)) {
                                        if (mensaje.translation)
                                            newContact.put("lang", contact.lang);
                                        else
                                            newContact.put("lang", u.lang);
                                        newContact.put("name", contact.idContacto);
                                        newContact.put("screen_name", contact.screenName);
                                        newContact.put("status", -1);
                                        targets.put(targets.length(), newContact);
                                    }
                                }
                            }
                            mensaje.receptores = targets.toString();
                            mensaje.save();
                        }
                        changeStatus(mensaje.mensajeId);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    });

}

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

public void showMensajeText(int position, Context context, final Message message, View rowView,
        TextView icnMessageArrow) {//from   ww  w  . ja va2s  . c  om

    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);
    final TextView messageContent = (TextView) rowView.findViewById(R.id.message_content);
    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);

    TFCache.apply(context, messageTime, TFCache.TF_WHITNEY_MEDIUM);
    TFCache.apply(context, messageContent, 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);

    SharedPreferences pref = getActivity().getSharedPreferences(Finder.STRING.APP_PREF.toString(),
            Context.MODE_PRIVATE);

    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)) {

        messageContent.setText(message.mensaje);

        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();
                        set.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {

                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                    } 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();
                        set.addListener(new Animator.AnimatorListener() {
                            @Override
                            public void onAnimationStart(Animator animation) {

                            }

                            @Override
                            public void onAnimationEnd(Animator animation) {

                            }

                            @Override
                            public void onAnimationCancel(Animator animation) {

                            }

                            @Override
                            public void onAnimationRepeat(Animator animation) {

                            }
                        });
                    }

                    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);
            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("message", message.mensaje);
                data.put("source_lang", message.emisorLang);
                data.put("delay", message.delay);
                data.put("translation_required", message.translation);
                data.put("target_lang", message.receptorLang);
                data.put("type", message.tipo);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (SpeakSocket.mSocket != null)
                if (SpeakSocket.mSocket.connected()) {
                    message.status = 1;
                    SpeakSocket.mSocket.emit("message", data);
                } else {
                    message.status = -1;
                }
        }
        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 {
            mensajeLayout.setBackgroundResource(R.drawable.message_out_background);
            GradientDrawable drawable = (GradientDrawable) mensajeLayout.getBackground();
            drawable.setCornerRadius(radius);
            drawable.setColor(BalloonFragment.getBackgroundColor(activity));
            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);
        if (message.tipo == 21)
            drawable.setColor(getResources().getColor(R.color.speakall_autoresponse));
        else
            drawable.setColor(BalloonFragment.getFriendBalloon(activity));

        if (message.tipo == Integer.parseInt(getString(R.string.MSG_TYPE_BROADCAST_TEXT))) {
            messageStatus.setTextSize(15);
            messageStatus.setText(Finder.STRING.ICN_BROADCAST_FILL.toString());
        }
        if (message.tipo == 21) {
            messageStatus.setTextSize(15);
            messageStatus.setTextColor(getResources().getColor(R.color.speak_all_white));
            TFCache.apply(activity, messageStatus, TFCache.TF_SPEAKON);
            messageStatus.setText(getResources().getString(R.string.icon_SpeakAll_rayo));
        }
        messageContent.setText(message.mensajeTrad);
        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);
                if (!message.emisorLang.equals(message.receptorLang)) {
                    icnMesajeTempo.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", -100, 0),
                            ObjectAnimator.ofFloat(icnMesajeCopy, "translationX", -100, 0),
                            ObjectAnimator.ofFloat(icnMesajeBack, "translationX", -150, 0));
                    set.setDuration(200).start();
                    set.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {

                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                } else {
                    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();
                    set.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {

                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                }
                return false;
            }
        });
        icnMesajeTempo.setOnClickListener(new View.OnClickListener() {
            boolean translation = true;

            @Override
            public void onClick(View v) {
                translation = !translation;
                if (translation) {
                    icnMesajeTempo.setTextColor(getResources().getColor(R.color.speak_all_red));
                    messageContent.setText(message.mensajeTrad);
                } else {
                    icnMesajeTempo.setTextColor(getResources().getColor(R.color.speak_all_white));
                    messageContent.setText(message.mensaje);
                }
            }
        });
    }

    if (message.orientation == 0) {
        messageContent.getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        if (messageContent.getLineCount() > 1) {
                            mensajeLayout.setOrientation(LinearLayout.VERTICAL);
                            messageContent.setPadding(0, messageContent.getPaddingTop(), 0, 0);
                            new Update(Message.class).set("orientation = ?", 2)
                                    .where("mensajeId = ?", message.mensajeId).execute();
                            messageContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        } else {
                            new Update(Message.class).set("orientation = ?", 1)
                                    .where("mensajeId = ?", message.mensajeId).execute();
                            messageContent.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                        }
                    }
                });
    } else {
        if (message.orientation == 2) {
            mensajeLayout.setOrientation(LinearLayout.VERTICAL);
            messageContent.setPadding(0, messageContent.getPaddingTop(), 0, 0);
        }
    }

    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;
                }
            }
            Message mensaje = new Select().from(Message.class).where("mensajeId = ?", message.mensajeId)
                    .executeSingle();
            if (mensaje.status == -1) {
                String message = mensaje.mensaje;
                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("message", message);
                    data.put("source_lang", mensaje.emisorLang);
                    data.put("delay", mensaje.delay);
                    data.put("translation_required", mensaje.translation);
                    data.put("target_lang", mensaje.receptorLang);
                    data.put("type", mensaje.tipo);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (SpeakSocket.mSocket != null)
                    if (SpeakSocket.mSocket.connected()) {
                        mensaje.status = 1;
                        SpeakSocket.mSocket.emit("message", data);
                    } else {
                        mensaje.status = -1;
                    }
                changeStatus(mensaje.mensajeId, mensaje.status);
            }
        }
    });
}