Example usage for android.widget ImageView setOnClickListener

List of usage examples for android.widget ImageView setOnClickListener

Introduction

In this page you can find the example usage for android.widget ImageView 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:com.saarang.samples.apps.iosched.ui.SessionDetailActivity.java

private void onSpeakersQueryComplete(Cursor cursor) {
    mSpeakersCursor = true;//  w w w .  j av a2  s  .  co m
    final ViewGroup speakersGroup = (ViewGroup) findViewById(
            com.saarang.samples.apps.iosched.R.id.session_speakers_block);

    // Remove all existing speakers (everything but first child, which is the header)
    for (int i = speakersGroup.getChildCount() - 1; i >= 1; i--) {
        speakersGroup.removeViewAt(i);
    }

    final LayoutInflater inflater = getLayoutInflater();

    boolean hasSpeakers = false;

    cursor.moveToPosition(-1); // move to just before first record
    while (cursor.moveToNext()) {
        final String speakerName = cursor.getString(SpeakersQuery.SPEAKER_NAME);
        if (TextUtils.isEmpty(speakerName)) {
            continue;
        }

        final String speakerImageUrl = cursor.getString(SpeakersQuery.SPEAKER_IMAGE_URL);
        final String speakerCompany = cursor.getString(SpeakersQuery.SPEAKER_COMPANY);
        final String speakerUrl = cursor.getString(SpeakersQuery.SPEAKER_URL);
        final String speakerAbstract = cursor.getString(SpeakersQuery.SPEAKER_ABSTRACT);

        String speakerHeader = speakerName;
        if (!TextUtils.isEmpty(speakerCompany)) {
            speakerHeader += ", " + speakerCompany;
        }

        final View speakerView = inflater.inflate(com.saarang.samples.apps.iosched.R.layout.speaker_detail,
                speakersGroup, false);
        final TextView speakerHeaderView = (TextView) speakerView
                .findViewById(com.saarang.samples.apps.iosched.R.id.speaker_header);
        final ImageView speakerImageView = (ImageView) speakerView
                .findViewById(com.saarang.samples.apps.iosched.R.id.speaker_image);
        final TextView speakerAbstractView = (TextView) speakerView
                .findViewById(com.saarang.samples.apps.iosched.R.id.speaker_abstract);

        if (!TextUtils.isEmpty(speakerImageUrl) && mSpeakersImageLoader != null) {
            mSpeakersImageLoader.loadImage(speakerImageUrl, speakerImageView);
        }

        speakerHeaderView.setText(speakerHeader);
        speakerImageView.setContentDescription(
                getString(com.saarang.samples.apps.iosched.R.string.speaker_googleplus_profile, speakerHeader));
        UIUtils.setTextMaybeHtml(speakerAbstractView, speakerAbstract);

        if (!TextUtils.isEmpty(speakerUrl)) {
            speakerImageView.setEnabled(true);
            speakerImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String number = "tel:" + speakerUrl.trim();
                    Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(number));
                    startActivity(callIntent);
                    /*Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(speakerUrl));
                    speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    UIUtils.preferPackageForIntent(SessionDetailActivity.this,
                        speakerProfileIntent,
                        UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
                    startActivity(speakerProfileIntent);*/
                }
            });
        } else {
            speakerImageView.setEnabled(true);
            speakerImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Toast.makeText(SessionDetailActivity.this,
                            "Sorry, No number found for this person. Call the other coordinator",
                            Toast.LENGTH_SHORT).show();

                    /*Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(speakerUrl));
                    speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    UIUtils.preferPackageForIntent(SessionDetailActivity.this,
                        speakerProfileIntent,
                        UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
                    startActivity(speakerProfileIntent);*/
                }
            });

        }

        speakersGroup.addView(speakerView);
        hasSpeakers = true;
        mHasSummaryContent = true;
    }

    speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE);
    updateEmptyView();
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

private void addMediaToQueue(@Nullable String id, QueuedMedia.Type type, Bitmap preview, Uri uri,
        long mediaSize, QueuedMedia.ReadyStage readyStage, @Nullable String description) {
    final QueuedMedia item = new QueuedMedia(type, uri, new ProgressImageView(this), mediaSize, description);
    item.id = id;//from  w ww  . ja v  a2s . c o  m
    item.readyStage = readyStage;
    ImageView view = item.preview;
    Resources resources = getResources();
    int margin = resources.getDimensionPixelSize(R.dimen.compose_media_preview_margin);
    int marginBottom = resources.getDimensionPixelSize(R.dimen.compose_media_preview_margin_bottom);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(thumbnailViewSize,
            thumbnailViewSize);
    layoutParams.setMargins(margin, 0, margin, marginBottom);
    view.setLayoutParams(layoutParams);
    view.setScaleType(ImageView.ScaleType.CENTER_CROP);
    view.setImageBitmap(preview);
    view.setOnClickListener(v -> onMediaClick(item, v));
    view.setContentDescription(getString(R.string.action_delete));
    mediaPreviewBar.addView(view);
    mediaQueued.add(item);
    int queuedCount = mediaQueued.size();
    if (queuedCount == 1) {
        // If there's one video in the queue it is full, so disable the button to queue more.
        if (item.type == QueuedMedia.Type.VIDEO) {
            enableButton(pickButton, false, false);
        }
    } else if (queuedCount >= Status.MAX_MEDIA_ATTACHMENTS) {
        // Limit the total media attachments, also.
        enableButton(pickButton, false, false);
    }

    updateHideMediaToggle();

    if (item.readyStage != QueuedMedia.ReadyStage.UPLOADED) {
        waitForMediaLatch.countUp();

        try {
            if (type == QueuedMedia.Type.IMAGE && (mediaSize > STATUS_MEDIA_SIZE_LIMIT || MediaUtils
                    .getImageSquarePixels(getContentResolver(), item.uri) > STATUS_MEDIA_PIXEL_SIZE_LIMIT)) {
                downsizeMedia(item);
            } else {
                uploadMedia(item);
            }
        } catch (FileNotFoundException e) {
            onUploadFailure(item, false);
        }
    }
}

From source file:com.xiaoyu.DoctorHelp.chat.chatuidemo.adapter.MessageAdapter.java

/**
 * load image into image view/* w ww .ja v a2  s. co m*/
 *
 * @param thumbernailPath
 * @param iv
 * @param
 * @return the image exists or not
 */
private boolean showImageView(final String thumbernailPath, final ImageView iv, final String localFullSizePath,
        String remoteDir, final EMMessage message) {
    // String imagename =
    // localFullSizePath.substring(localFullSizePath.lastIndexOf("/") + 1,
    // localFullSizePath.length());
    // final String remote = remoteDir != null ? remoteDir+imagename :
    // imagename;
    final String remote = remoteDir;
    EMLog.d("###", "local = " + localFullSizePath + " remote: " + remote);
    // first check if the thumbnail image already loaded into cache
    Bitmap bitmap = ImageCache.getInstance().get(thumbernailPath);
    if (bitmap != null) {
        // thumbnail image is already loaded, reuse the drawable
        iv.setImageBitmap(bitmap);
        iv.setClickable(true);
        iv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                EMLog.d(TAG, "image view on click");
                Intent intent = new Intent(activity, ShowBigImage.class);
                File file = new File(localFullSizePath);
                if (file.exists()) {
                    Uri uri = Uri.fromFile(file);
                    intent.putExtra("uri", uri);
                    EMLog.d(TAG, "here need to check why download everytime");
                } else {
                    // The local full size pic does not exist yet.
                    // ShowBigImage needs to download it from the server
                    // first
                    // intent.putExtra("", message.get);
                    ImageMessageBody body = (ImageMessageBody) message.getBody();
                    intent.putExtra("secret", body.getSecret());
                    intent.putExtra("remotepath", remote);
                }
                if (message != null && message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
                        && message.getChatType() != ChatType.GroupChat
                        && message.getChatType() != ChatType.ChatRoom) {
                    try {
                        EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                        message.isAcked = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                activity.startActivity(intent);
            }
        });
        return true;
    } else {

        new LoadImageTask().execute(thumbernailPath, localFullSizePath, remote, message.getChatType(), iv,
                activity, message);
        return true;
    }

}

From source file:maimeng.yodian.app.client.android.chat.adapter.MessageAdapter.java

/**
 * start image into image view//from   ww  w .  j ava  2s .c  om
 *
 * @param thumbernailPath
 * @param iv
 * @return the image exists or not
 */
private boolean showImageView(final String thumbernailPath, final ImageView iv, final String localFullSizePath,
        String remoteDir, final EMMessage message) {
    // String imagename =
    // localFullSizePath.substring(localFullSizePath.lastIndexOf("/") + 1,
    // localFullSizePath.length());
    // final String remote = remoteDir != null ? remoteDir+imagename :
    // imagename;
    final String remote = remoteDir;
    EMLog.d("###", "local = " + localFullSizePath + " remote: " + remote);
    // first check if the thumbnail image already loaded into cache
    Bitmap bitmap = ImageCache.getInstance().get(thumbernailPath);
    if (bitmap != null && false) {
        // thumbnail image is already loaded, reuse the drawable
        iv.setImageBitmap(bitmap);
        iv.setClickable(true);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EMLog.d(TAG, "image view on click");
                Intent intent = new Intent(activity, ShowBigImage.class);
                File file = new File(localFullSizePath);
                if (file.exists()) {
                    Uri uri = Uri.fromFile(file);
                    intent.putExtra("uri", uri);
                    EMLog.d(TAG, "here need to check why download everytime");
                } else {
                    // The local full size pic does not exist yet.
                    // ShowBigImage needs to download it from the server
                    // first
                    // intent.putExtra("", message.get);
                    ImageMessageBody body = (ImageMessageBody) message.getBody();
                    intent.putExtra("secret", body.getSecret());
                    intent.putExtra("remotepath", remote);
                }
                if (message != null && message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
                        && message.getChatType() != ChatType.GroupChat
                        && message.getChatType() != ChatType.ChatRoom) {
                    try {
                        EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                        message.isAcked = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Bundle options = ActivityOptionsCompat.makeSceneTransitionAnimation(activity, iv, "img")
                        .toBundle();
                ActivityCompat.startActivity(activity, intent, options);
            }
        });
        return true;
    } else {
        new LoadImageTask().execute(thumbernailPath, localFullSizePath, remote, message.getChatType(), iv,
                activity, message, iv.getContext());
        return true;
    }

}

From source file:de.sourcestream.movieDB.MainActivity.java

/**
 * First configure the Universal Image Downloader,
 * then we set the main layout to be activity_main.xml
 * and we add the slide menu items.//from w  w w  .j ava2  s.  c  o m
 *
 * @param savedInstanceState If non-null, this activity is being re-constructed from a previous saved state as given here.
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();

    // load slide menu items
    navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
    ViewGroup header = (ViewGroup) getLayoutInflater().inflate(R.layout.drawer_header, null, false);
    ImageView drawerBackButton = (ImageView) header.findViewById(R.id.drawerBackButton);
    drawerBackButton.setOnClickListener(onDrawerBackButton);
    mDrawerList.addHeaderView(header);
    mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
    // setting the nav drawer list adapter
    mDrawerList.setAdapter(new ArrayAdapter<>(this, R.layout.drawer_list_item, R.id.title, navMenuTitles));

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if (toolbar != null) {
        setSupportActionBar(toolbar);
        toolbar.bringToFront();
    }

    mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
            mDrawerLayout, /* DrawerLayout object */
            toolbar, R.string.app_name, // nav drawer open - description for accessibility
            R.string.app_name // nav drawer close - description for accessibility
    ) {
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
            // calling onPrepareOptionsMenu() to show search view
            invalidateOptionsMenu();
            syncState();
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // calling onPrepareOptionsMenu() to hide search view
            invalidateOptionsMenu();
            syncState();
        }

        // updates the title, toolbar transparency and search view
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
            if (slideOffset > .55 && !isDrawerOpen) {
                // opening drawer
                // mDrawerTitle is app title
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu();
                isDrawerOpen = true;
            } else if (slideOffset < .45 && isDrawerOpen) {
                // closing drawer
                // mTitle is title of the current view, can be movies, tv shows or movie title
                getSupportActionBar().setTitle(mTitle);
                invalidateOptionsMenu();
                isDrawerOpen = false;
            }
        }

    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);

    // Get the action bar title to set padding
    TextView titleTextView = null;

    try {
        Field f = toolbar.getClass().getDeclaredField("mTitleTextView");
        f.setAccessible(true);
        titleTextView = (TextView) f.get(toolbar);
    } catch (NoSuchFieldException e) {

    } catch (IllegalAccessException e) {

    }
    if (titleTextView != null) {
        float scale = getResources().getDisplayMetrics().density;
        titleTextView.setPadding((int) scale * 15, 0, 0, 0);
    }

    phone = getResources().getBoolean(R.bool.portrait_only);

    searchDB = new SearchDB(getApplicationContext());

    if (savedInstanceState == null) {
        // Check orientation and lock to portrait if we are on phone
        if (phone) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }

        // on first time display view for first nav item
        displayView(1);

        // Use hockey module to check for updates
        checkForUpdates();

        // Universal Loader options and configuration.
        DisplayImageOptions options = new DisplayImageOptions.Builder()
                // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
                .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
                .showImageOnLoading(R.drawable.placeholder_default)
                .showImageForEmptyUri(R.drawable.placeholder_default)
                .showImageOnFail(R.drawable.placeholder_default).cacheOnDisk(true).build();
        Context context = this;
        File cacheDir = StorageUtils.getCacheDirectory(context);
        // Create global configuration and initialize ImageLoader with this config
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
                .diskCache(new UnlimitedDiscCache(cacheDir)) // default
                .defaultDisplayImageOptions(options).build();
        ImageLoader.getInstance().init(config);

        // Check cache size
        long size = 0;
        File[] filesCache = cacheDir.listFiles();
        for (File file : filesCache) {
            size += file.length();
        }
        if (cacheDir.getUsableSpace() < MinFreeSpace || size > CacheSize) {
            ImageLoader.getInstance().getDiskCache().clear();
            searchDB.cleanSuggestionRecords();
        }

    } else {
        oldPos = savedInstanceState.getInt("oldPos");
        currentMovViewPagerPos = savedInstanceState.getInt("currentMovViewPagerPos");
        currentTVViewPagerPos = savedInstanceState.getInt("currentTVViewPagerPos");
        restoreMovieDetailsState = savedInstanceState.getBoolean("restoreMovieDetailsState");
        restoreMovieDetailsAdapterState = savedInstanceState.getBoolean("restoreMovieDetailsAdapterState");
        movieDetailsBundle = savedInstanceState.getParcelableArrayList("movieDetailsBundle");
        castDetailsBundle = savedInstanceState.getParcelableArrayList("castDetailsBundle");
        tvDetailsBundle = savedInstanceState.getParcelableArrayList("tvDetailsBundle");
        currOrientation = savedInstanceState.getInt("currOrientation");
        lastVisitedSimMovie = savedInstanceState.getInt("lastVisitedSimMovie");
        lastVisitedSimTV = savedInstanceState.getInt("lastVisitedSimTV");
        lastVisitedMovieInCredits = savedInstanceState.getInt("lastVisitedMovieInCredits");
        saveInMovieDetailsSimFragment = savedInstanceState.getBoolean("saveInMovieDetailsSimFragment");

        FragmentManager fm = getFragmentManager();
        // prevent the following bug: go to gallery preview -> swap orientation ->
        // go to movies list -> swap orientation -> action bar bugged
        // so if we are not on gallery preview we show toolbar
        if (fm.getBackStackEntryCount() == 0
                || !fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1).getName().equals("galleryList")) {
            new Handler().post(new Runnable() {
                @Override
                public void run() {
                    if (getSupportActionBar() != null && !getSupportActionBar().isShowing())
                        getSupportActionBar().show();
                }
            });
        }
    }

    // Get reference for the imageLoader
    imageLoader = ImageLoader.getInstance();

    // Options used for the backdrop image in movie and tv details and gallery
    optionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false).showImageOnLoading(R.color.black)
            .showImageForEmptyUri(R.color.black).showImageOnFail(R.color.black).cacheOnDisk(true).build();
    optionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.color.black).showImageForEmptyUri(R.color.black)
            .showImageOnFail(R.color.black).cacheOnDisk(true).build();

    // Options used for the backdrop image in movie and tv details and gallery
    backdropOptionsWithFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).displayer(new FadeInBitmapDisplayer(500))
            .imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();
    backdropOptionsWithoutFade = new DisplayImageOptions.Builder()
            // Bitmaps in RGB_565 consume 2 times less memory than in ARGB_8888.
            .bitmapConfig(Bitmap.Config.RGB_565).imageScaleType(ImageScaleType.EXACTLY).cacheInMemory(false)
            .showImageOnLoading(R.drawable.placeholder_backdrop)
            .showImageForEmptyUri(R.drawable.placeholder_backdrop)
            .showImageOnFail(R.drawable.placeholder_backdrop).cacheOnDisk(true).build();

    trailerListView = new TrailerList();
    galleryListView = new GalleryList();

    if (currOrientation != getResources().getConfiguration().orientation)
        orientationChanged = true;

    currOrientation = getResources().getConfiguration().orientation;

    iconConstantSpecialCase = 0;
    if (phone) {
        iconMarginConstant = 0;
        iconMarginLandscape = 0;
        DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
        int width = displayMetrics.widthPixels;
        int height = displayMetrics.heightPixels;
        if (width <= 480 && height <= 800)
            iconConstantSpecialCase = -70;

        // used in MovieDetails, CastDetails, TVDetails onMoreIconClick
        // to check whether the animation should be in up or down direction
        threeIcons = 128;
        threeIconsToolbar = 72;
        twoIcons = 183;
        twoIconsToolbar = 127;
        oneIcon = 238;
        oneIconToolbar = 182;
    } else {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
            iconMarginConstant = 232;
            iconMarginLandscape = 300;

            threeIcons = 361;
            threeIconsToolbar = 295;
            twoIcons = 416;
            twoIconsToolbar = 351;
            oneIcon = 469;
            oneIconToolbar = 407;
        } else {
            iconMarginConstant = 82;
            iconMarginLandscape = 0;

            threeIcons = 209;
            threeIconsToolbar = 146;
            twoIcons = 264;
            twoIconsToolbar = 200;
            oneIcon = 319;
            oneIconToolbar = 256;
        }

    }

    dateFormat = android.text.format.DateFormat.getDateFormat(this);
}

From source file:com.fullteem.yueba.app.adapter.MessageAdapter.java

/**
 * load image into image view//from   w  w w  .ja  v  a 2s. co  m
 * 
 * @param thumbernailPath
 * @param iv
 * @param position
 * @return the image exists or not
 */
private boolean showImageView(final String thumbernailPath, final ImageView iv, final String localFullSizePath,
        String remoteDir, final EMMessage message) {
    // String imagename =
    // localFullSizePath.substring(localFullSizePath.lastIndexOf("/") + 1,
    // localFullSizePath.length());
    // final String remote = remoteDir != null ? remoteDir+imagename :
    // imagename;
    final String remote = remoteDir;
    EMLog.d("###", "local = " + localFullSizePath + " remote: " + remote);
    // first check if the thumbnail image already loaded into cache
    Bitmap bitmap = ImageCache.getInstance().get(thumbernailPath);
    if (bitmap != null) {
        // thumbnail image is already loaded, reuse the drawable
        iv.setImageBitmap(bitmap);
        iv.setClickable(true);
        iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                System.err.println("image view on click");
                Intent intent = new Intent(activity, ShowBigImage.class);
                File file = new File(localFullSizePath);
                if (file.exists()) {
                    Uri uri = Uri.fromFile(file);
                    intent.putExtra("uri", uri);
                    System.err.println("here need to check why download everytime");
                } else {
                    // The local full size pic does not exist yet.
                    // ShowBigImage needs to download it from the server
                    // first
                    // intent.putExtra("", message.get);
                    ImageMessageBody body = (ImageMessageBody) message.getBody();
                    intent.putExtra("secret", body.getSecret());
                    intent.putExtra("remotepath", remote);
                }
                if (message != null && message.direct == EMMessage.Direct.RECEIVE && !message.isAcked
                        && message.getChatType() != ChatType.GroupChat) {
                    try {
                        EMChatManager.getInstance().ackMessageRead(message.getFrom(), message.getMsgId());
                        message.isAcked = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                activity.startActivity(intent);
            }
        });
        return true;
    } else {
        new LoadImageTask().execute(thumbernailPath, localFullSizePath, remote, message.getChatType(), iv,
                activity, message);
        return true;
    }

}

From source file:org.alfresco.mobile.android.application.fragments.properties.DetailsFragment.java

/**
 * Display a drawable associated to the node type on a specific imageview.
 * //from  ww  w  .  j a v  a  2s.  c o m
 * @param node
 * @param defaultIconId
 * @param iv
 * @param isLarge
 */
private void displayIcon(Node node, int defaultIconId, ImageView iv, boolean isLarge) {
    if (iv == null) {
        return;
    }

    int iconId = defaultIconId;
    if (node.isDocument()) {
        MimeType mime = MimeTypeManager.getMimetype(getActivity(), node.getName());
        iconId = MimeTypeManager.getIcon(getActivity(), node.getName(), isLarge);
        if (((Document) node).isLatestVersion()) {
            if (isLarge) {
                renditionManager.preview(iv, node, iconId, DisplayUtils.getWidth(getActivity()));
            } else {
                renditionManager.display(iv, node, iconId);
            }
        } else {
            iv.setImageResource(iconId);
        }
        AccessibilityHelper.addContentDescription(iv,
                mime != null ? mime.getDescription() : ((Document) node).getContentStreamMimeType());

        if (!isRestrictable && !AccessibilityHelper.isEnabled(getActivity())) {
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    openin();
                }
            });
        }
    } else {
        iv.setImageResource(defaultIconId);
        AccessibilityHelper.addContentDescription(iv, R.string.mime_folder);
    }
}

From source file:fiskinfoo.no.sintef.fiskinfoo.Implementation.UtilityOnClickListeners.java

public OnClickListener getToolEntryEditDialogOnClickListener(final Activity activity,
        final FragmentManager fragmentManager, final GpsLocationTracker locationTracker,
        final ToolEntry toolEntry, final User user) {
    return new OnClickListener() {
        @Override//from   w  w w  .ja  v  a2s.  co  m
        public void onClick(final View editButton) {
            final DialogInterface dialogInterface = new UtilityDialogs();
            final Dialog dialog = dialogInterface.getDialog(editButton.getContext(),
                    R.layout.dialog_register_new_tool, R.string.edit_tool);
            ((Button) dialog.findViewById(R.id.dialog_register_tool_create_tool_button))
                    .setText(editButton.getContext().getString(R.string.save));

            final Button updateButton = (Button) dialog
                    .findViewById(R.id.dialog_register_tool_create_tool_button);
            final Button cancelButton = (Button) dialog.findViewById(R.id.dialog_register_tool_cancel_button);
            final LinearLayout fieldContainer = (LinearLayout) dialog
                    .findViewById(R.id.dialog_register_tool_main_container);
            final DatePickerRow setupDateRow = new DatePickerRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.tool_set_date_colon), fragmentManager);
            final TimePickerRow setupTimeRow = new TimePickerRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.tool_set_time_colon), fragmentManager, false);
            final CoordinatesRow coordinatesRow = new CoordinatesRow(activity, locationTracker);
            final SpinnerRow toolRow = new SpinnerRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.tool_type), ToolType.getValues());
            final CheckBoxRow toolRemovedRow = new CheckBoxRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.tool_removed_row_text), true);
            final EditTextRow commentRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.comment_field_header),
                    editButton.getContext().getString(R.string.comment_field_hint));

            final EditTextRow contactPersonNameRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.contact_person_name),
                    editButton.getContext().getString(R.string.contact_person_name));
            final EditTextRow contactPersonPhoneRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.contact_person_phone),
                    editButton.getContext().getString(R.string.contact_person_phone));
            final EditTextRow contactPersonEmailRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.contact_person_email),
                    editButton.getContext().getString(R.string.contact_person_email));
            final EditTextRow vesselNameRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.vessel_name),
                    editButton.getContext().getString(R.string.vessel_name));
            final EditTextRow vesselPhoneNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.vessel_phone_number),
                    editButton.getContext().getString(R.string.vessel_phone_number));
            final EditTextRow vesselIrcsNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.ircs_number),
                    editButton.getContext().getString(R.string.ircs_number));
            final EditTextRow vesselMmsiNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.mmsi_number),
                    editButton.getContext().getString(R.string.mmsi_number));
            final EditTextRow vesselImoNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.imo_number),
                    editButton.getContext().getString(R.string.imo_number));
            final EditTextRow vesselRegistrationNumberRow = new EditTextRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.registration_number),
                    editButton.getContext().getString(R.string.registration_number));
            final ErrorRow errorRow = new ErrorRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.error_minimum_identification_factors_not_met),
                    false);

            final SimpleDateFormat sdfMilliSeconds = new SimpleDateFormat(
                    editButton.getContext().getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss_sss),
                    Locale.getDefault());
            final SimpleDateFormat sdf = new SimpleDateFormat(
                    editButton.getContext().getString(R.string.datetime_format_yyyy_mm_dd_t_hh_mm_ss),
                    Locale.getDefault());

            View.OnClickListener deleteButtonRowOnClickListener = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String confirmationText;

                    switch (toolEntry.getToolStatus()) {
                    case STATUS_RECEIVED:
                    case STATUS_SENT_UNCONFIRMED:
                        confirmationText = v.getContext()
                                .getString(R.string.confirm_registered_tool_deletion_text);
                        break;
                    case STATUS_UNSENT:
                    case STATUS_UNREPORTED:
                        confirmationText = v.getContext().getString(R.string.confirm_tool_deletion_text);
                        break;
                    case STATUS_REMOVED_UNCONFIRMED:
                        confirmationText = v.getContext()
                                .getString(R.string.confirm_registered_tool_with_local_changes_deletion_text);
                        break;
                    default:
                        confirmationText = v.getContext()
                                .getString(R.string.confirm_tool_deletion_text_general);
                        break;
                    }

                    final Dialog deleteToolDialog = dialogInterface.getConfirmationDialog(v.getContext(),
                            v.getContext().getString(R.string.delete_tool), confirmationText,
                            v.getContext().getString(R.string.delete));
                    Button confirmToolDeletionButton = (Button) deleteToolDialog
                            .findViewById(R.id.dialog_bottom_confirm_bottom);

                    confirmToolDeletionButton.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            View parentView = (View) ((editButton.getParent()).getParent());
                            ((LinearLayout) parentView).removeView(((View) (editButton.getParent())));
                            Toast.makeText(v.getContext(), v.getContext().getString(R.string.tool_deleted),
                                    Toast.LENGTH_LONG).show();

                            user.getToolLog().removeTool(toolEntry.getSetupDate(), toolEntry.getToolLogId());
                            user.writeToSharedPref(v.getContext());

                            deleteToolDialog.dismiss();
                            dialog.dismiss();
                        }
                    });

                    deleteToolDialog.show();
                }
            };

            View.OnClickListener archiveToolOnClickListener = new OnClickListener() {
                @Override
                public void onClick(View v) {
                    String confirmationText;

                    switch (toolEntry.getToolStatus()) {
                    case STATUS_RECEIVED:
                        confirmationText = v.getContext().getString(R.string.confirm_registered_tool_archiving);
                        break;
                    case STATUS_UNSENT:
                        if (!toolEntry.getId().isEmpty()) {
                            confirmationText = v.getContext().getString(R.string.confirm_tool_archiving_text);
                        } else {
                            confirmationText = v.getContext().getString(
                                    R.string.confirm_registered_tool_with_local_changes_archiving_text);
                        }
                        break;
                    default:
                        confirmationText = v.getContext()
                                .getString(R.string.confirm_tool_archiving_text_general);
                        break;
                    }

                    final Dialog archiveDialog = dialogInterface.getConfirmationDialog(v.getContext(),
                            v.getContext().getString(R.string.archive_tool), confirmationText,
                            v.getContext().getString(R.string.archive));
                    Button confirmToolArchiveButton = (Button) archiveDialog
                            .findViewById(R.id.dialog_bottom_confirm_bottom);

                    confirmToolArchiveButton.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            View parentView = (View) ((editButton.getParent()).getParent()).getParent();
                            ((LinearLayout) parentView)
                                    .removeView(((View) (editButton.getParent()).getParent()));
                            Toast.makeText(v.getContext(), v.getContext().getString(R.string.tool_archived),
                                    Toast.LENGTH_LONG).show();

                            toolEntry.setToolStatus(ToolEntryStatus.STATUS_REMOVED);
                            user.writeToSharedPref(v.getContext());

                            archiveDialog.dismiss();
                            dialog.dismiss();
                        }
                    });

                    archiveDialog.show();
                }
            };

            ActionRow archiveRow = new ActionRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.archive_tool), R.drawable.ic_archive_black_24dp,
                    archiveToolOnClickListener);
            ActionRow deleteRow = new ActionRow(editButton.getContext(),
                    editButton.getContext().getString(R.string.delete_tool), R.drawable.ic_delete_black_24dp,
                    deleteButtonRowOnClickListener);

            commentRow.setInputType(InputType.TYPE_CLASS_TEXT);
            commentRow.setHelpText(editButton.getContext().getString(R.string.comment_help_description));
            vesselNameRow.setInputType(InputType.TYPE_CLASS_TEXT);
            contactPersonPhoneRow
                    .setHelpText(editButton.getContext().getString(R.string.vessel_name_help_description));
            vesselPhoneNumberRow.setInputType(InputType.TYPE_CLASS_PHONE);
            vesselIrcsNumberRow.setInputType(InputType.TYPE_CLASS_TEXT);
            vesselIrcsNumberRow.setInputFilters(new InputFilter[] {
                    new InputFilter.LengthFilter(
                            editButton.getContext().getResources().getInteger(R.integer.input_length_ircs)),
                    new InputFilter.AllCaps() });
            vesselIrcsNumberRow.setHelpText(editButton.getContext().getString(R.string.ircs_help_description));
            vesselMmsiNumberRow.setInputType(InputType.TYPE_CLASS_NUMBER);
            vesselMmsiNumberRow.setInputFilters(new InputFilter[] { new InputFilter.LengthFilter(
                    editButton.getContext().getResources().getInteger(R.integer.input_length_mmsi)) });
            vesselMmsiNumberRow.setHelpText(editButton.getContext().getString(R.string.mmsi_help_description));
            vesselImoNumberRow.setInputType(InputType.TYPE_CLASS_NUMBER);
            vesselImoNumberRow.setInputFilters(new InputFilter[] { new InputFilter.LengthFilter(
                    editButton.getContext().getResources().getInteger(R.integer.input_length_imo)) });
            vesselImoNumberRow.setHelpText(editButton.getContext().getString(R.string.imo_help_description));
            vesselRegistrationNumberRow.setInputType(InputType.TYPE_CLASS_TEXT);
            vesselRegistrationNumberRow.setInputFilters(new InputFilter[] {
                    new InputFilter.LengthFilter(editButton.getContext().getResources()
                            .getInteger(R.integer.input_length_registration_number)),
                    new InputFilter.AllCaps() });
            vesselRegistrationNumberRow.setHelpText(
                    editButton.getContext().getString(R.string.registration_number_help_description));
            contactPersonNameRow.setInputType(InputType.TYPE_TEXT_VARIATION_PERSON_NAME);
            contactPersonPhoneRow.setInputType(InputType.TYPE_CLASS_PHONE);
            contactPersonEmailRow.setInputType(InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
            contactPersonNameRow.setHelpText(
                    editButton.getContext().getString(R.string.contact_person_name_help_description));
            contactPersonPhoneRow.setHelpText(
                    editButton.getContext().getString(R.string.contact_person_phone_help_description));
            contactPersonEmailRow.setHelpText(
                    editButton.getContext().getString(R.string.contact_person_email_help_description));
            coordinatesRow.setCoordinates(activity, toolEntry.getCoordinates());

            setupDateRow.setEnabled(false);

            /* Should these fields be editable after tools are reported? */
            //                vesselRegistrationNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);
            //                vesselImoNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);
            //                vesselMmsiNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);
            //                vesselNameRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);
            //                vesselIrcsNumberRow.setEnabled(toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED);

            ArrayAdapter<String> currentAdapter = toolRow.getAdapter();
            toolRow.setSelectedSpinnerItem(currentAdapter.getPosition(toolEntry.getToolType().toString()));
            toolRemovedRow.setChecked(!toolEntry.getRemovedTime().isEmpty());
            commentRow.setText(toolEntry.getComment());
            contactPersonNameRow.setText(toolEntry.getContactPersonName());
            contactPersonPhoneRow
                    .setText(!toolEntry.getContactPersonPhone().equals("") ? toolEntry.getContactPersonPhone()
                            : toolEntry.getVesselPhone());
            contactPersonEmailRow
                    .setText(!toolEntry.getContactPersonEmail().equals("") ? toolEntry.getContactPersonEmail()
                            : toolEntry.getVesselEmail());
            vesselNameRow.setText(toolEntry.getVesselName());
            vesselPhoneNumberRow.setText(toolEntry.getVesselPhone());
            vesselIrcsNumberRow.setText(toolEntry.getIRCS());
            vesselMmsiNumberRow.setText(toolEntry.getMMSI());
            vesselImoNumberRow.setText(toolEntry.getIMO());
            vesselRegistrationNumberRow.setText(toolEntry.getRegNum());

            sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date setupDate = null;
            String toolSetupDateTime;

            try {
                setupDate = sdf.parse(toolEntry.getSetupDateTime());
            } catch (ParseException e) {
                e.printStackTrace();
            }

            sdfMilliSeconds.setTimeZone(TimeZone.getDefault());
            toolSetupDateTime = sdfMilliSeconds.format(setupDate);
            setupDateRow.setDate(toolSetupDateTime.substring(0, 10));
            setupTimeRow.setTime(toolSetupDateTime.substring(toolEntry.getSetupDateTime().indexOf('T') + 1,
                    toolEntry.getSetupDateTime().indexOf('T') + 6));

            fieldContainer.addView(coordinatesRow.getView());
            fieldContainer.addView(setupDateRow.getView());
            fieldContainer.addView(setupTimeRow.getView());
            fieldContainer.addView(toolRow.getView());
            fieldContainer.addView(toolRemovedRow.getView());
            fieldContainer.addView(commentRow.getView());
            fieldContainer.addView(contactPersonNameRow.getView());
            fieldContainer.addView(contactPersonPhoneRow.getView());
            fieldContainer.addView(contactPersonEmailRow.getView());
            fieldContainer.addView(vesselNameRow.getView());
            fieldContainer.addView(vesselPhoneNumberRow.getView());
            fieldContainer.addView(vesselIrcsNumberRow.getView());
            fieldContainer.addView(vesselMmsiNumberRow.getView());
            fieldContainer.addView(vesselImoNumberRow.getView());
            fieldContainer.addView(vesselRegistrationNumberRow.getView());
            fieldContainer.addView(errorRow.getView());

            if (toolEntry.getToolStatus() != ToolEntryStatus.STATUS_UNREPORTED) {
                fieldContainer.addView(archiveRow.getView());
            }

            fieldContainer.addView(deleteRow.getView());

            updateButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View updateButton) {
                    List<Point> coordinates = coordinatesRow.getCoordinates();
                    ToolType toolType = ToolType.createFromValue(toolRow.getCurrentSpinnerItem());
                    boolean toolRemoved = toolRemovedRow.isChecked();
                    String vesselName = vesselNameRow.getFieldText();
                    String vesselPhoneNumber = vesselPhoneNumberRow.getFieldText();
                    String toolSetupDate = setupDateRow.getDate();
                    String toolSetupTime = setupTimeRow.getTime();
                    String toolSetupDateTime;
                    String commentString = commentRow.getFieldText();
                    String vesselIrcsNumber = vesselIrcsNumberRow.getFieldText();
                    String vesselMmsiNumber = vesselMmsiNumberRow.getFieldText();
                    String vesselImoNumber = vesselImoNumberRow.getFieldText();
                    String registrationNumber = vesselRegistrationNumberRow.getFieldText();
                    String contactPersonName = contactPersonNameRow.getFieldText();
                    String contactPersonPhone = contactPersonPhoneRow.getFieldText();
                    String contactPersonEmail = contactPersonEmailRow.getFieldText();
                    FiskInfoUtility utility = new FiskInfoUtility();
                    boolean validated;
                    boolean edited = false;
                    boolean ircsValidated;
                    boolean mmsiValidated;
                    boolean imoValidated;
                    boolean regNumValidated;
                    boolean minimumIdentificationFactorsMet;

                    validated = coordinates != null;
                    if (!validated) {
                        return;
                    }

                    validated = utility.validateName(contactPersonNameRow.getFieldText().trim());
                    contactPersonNameRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_name));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        contactPersonNameRow.getView().getBottom());
                                contactPersonNameRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = utility.validatePhoneNumber(contactPersonPhoneRow.getFieldText().trim());
                    contactPersonPhoneRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_phone_number));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        contactPersonPhoneRow.getView().getBottom());
                                contactPersonPhoneRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = utility.isEmailValid(contactPersonEmailRow.getFieldText().trim());
                    contactPersonEmailRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_email));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        contactPersonEmailRow.getView().getBottom());
                                contactPersonEmailRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = vesselNameRow.getFieldText().trim() != null
                            && !vesselNameRow.getFieldText().isEmpty();
                    vesselNameRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_vessel_name));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselNameRow.getView().getBottom());
                                vesselNameRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = vesselPhoneNumberRow.getFieldText().trim() != null
                            && !vesselPhoneNumberRow.getFieldText().isEmpty();
                    vesselPhoneNumberRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_phone_number));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselPhoneNumberRow.getView().getBottom());
                                vesselPhoneNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = (ircsValidated = utility.validateIRCS(vesselIrcsNumber))
                            || vesselIrcsNumber.isEmpty();
                    vesselIrcsNumberRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_ircs));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselIrcsNumberRow.getView().getBottom());
                                vesselIrcsNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = (mmsiValidated = utility.validateMMSI(vesselMmsiNumber))
                            || vesselMmsiNumber.isEmpty();
                    vesselMmsiNumberRow.setError(validated ? null
                            : updateButton.getContext().getString(R.string.error_invalid_mmsi));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselMmsiNumberRow.getView().getBottom());
                                vesselMmsiNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = (imoValidated = utility.validateIMO(vesselImoNumber))
                            || vesselImoNumber.isEmpty();
                    vesselImoNumberRow.setError(
                            validated ? null : updateButton.getContext().getString(R.string.error_invalid_imo));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent()).scrollTo(0,
                                        vesselImoNumberRow.getView().getBottom());
                                vesselImoNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    validated = (regNumValidated = utility.validateRegistrationNumber(registrationNumber))
                            || registrationNumber.isEmpty();
                    vesselRegistrationNumberRow.setError(validated ? null
                            : editButton.getContext().getString(R.string.error_invalid_registration_number));
                    if (!validated) {
                        ((ScrollView) fieldContainer.getParent().getParent()).post(new Runnable() {
                            @Override
                            public void run() {
                                ((ScrollView) fieldContainer.getParent().getParent()).scrollTo(0,
                                        vesselRegistrationNumberRow.getView().getBottom());
                                vesselRegistrationNumberRow.requestFocus();
                            }
                        });

                        return;
                    }

                    sdf.setTimeZone(TimeZone.getDefault());
                    Date setupDate = null;
                    String setupDateString = toolSetupDate + "T" + toolSetupTime + ":00Z";

                    try {
                        setupDate = sdf.parse(setupDateString);
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }

                    sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("UTC"));
                    setupDateString = sdfMilliSeconds.format(setupDate);
                    toolSetupDateTime = setupDateString.substring(0, setupDateString.indexOf('.')).concat("Z");

                    minimumIdentificationFactorsMet = !vesselName.isEmpty()
                            && (ircsValidated || mmsiValidated || imoValidated || regNumValidated);

                    if ((coordinates != null && coordinates.size() != toolEntry.getCoordinates().size())
                            || toolType != toolEntry.getToolType()
                            || (toolRemoved) == (toolEntry.getRemovedTime().isEmpty())
                            || (vesselName != null && !vesselName.equals(toolEntry.getVesselName()))
                            || (vesselPhoneNumber != null
                                    && !vesselPhoneNumber.equals(toolEntry.getVesselPhone()))
                            || (toolSetupDateTime != null
                                    && !toolSetupDateTime.equals(toolEntry.getSetupDateTime()))
                            || (vesselIrcsNumber != null && !vesselIrcsNumber.equals(toolEntry.getIRCS()))
                            || (vesselMmsiNumber != null && !vesselMmsiNumber.equals(toolEntry.getMMSI()))
                            || (vesselImoNumber != null && !vesselImoNumber.equals(toolEntry.getIMO()))
                            || (registrationNumber != null && !registrationNumber.equals(toolEntry.getRegNum()))
                            || (contactPersonName != null
                                    && !contactPersonName.equals(toolEntry.getContactPersonName()))
                            || (contactPersonPhone != null
                                    && !contactPersonPhone.equals(toolEntry.getContactPersonPhone()))
                            || (contactPersonEmail != null
                                    && !contactPersonEmail.equals(toolEntry.getContactPersonEmail()))
                            || (commentString != null && !commentString.equals(toolEntry.getComment()))) {
                        edited = true;
                    } else {
                        List<Point> points = toolEntry.getCoordinates();
                        for (int i = 0; i < coordinates.size(); i++) {
                            if (coordinates.get(i).getLatitude() != points.get(i).getLatitude()
                                    || coordinates.get(i).getLongitude() != points.get(i).getLongitude()) {
                                edited = true;
                                break;
                            }
                        }
                    }

                    if (edited) {
                        if (!minimumIdentificationFactorsMet) {
                            errorRow.setVisibility(!minimumIdentificationFactorsMet);
                            return;
                        }

                        Date lastChangedDate = new Date();
                        Date previousSetupDate = null;
                        SimpleDateFormat sdfSetupCompare = new SimpleDateFormat("yyyyMMdd",
                                Locale.getDefault());

                        String lastChangedDateString = sdfMilliSeconds.format(lastChangedDate).concat("Z");
                        sdfSetupCompare.setTimeZone(TimeZone.getTimeZone("UTC"));

                        try {
                            previousSetupDate = sdf.parse(toolEntry.getSetupDateTime()
                                    .substring(0, toolEntry.getSetupDateTime().length() - 1).concat(".000"));
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        if (!sdfSetupCompare.format(previousSetupDate)
                                .equals(sdfSetupCompare.format(setupDate))) {
                            // TODO: setup date is changed, tool needs to be moved in log so the app does not crash when trying to delete tool.
                            //                                user.getToolLog().removeTool(toolEntry.getSetupDate(), toolEntry.getToolLogId());
                            //                                user.getToolLog().addTool(toolEntry, toolEntry.getSetupDateTime().substring(0, 10));
                            //                                user.writeToSharedPref(editButton.getContext());
                        }

                        ToolEntryStatus toolStatus = (toolRemoved ? ToolEntryStatus.STATUS_REMOVED_UNCONFIRMED
                                : (toolEntry.getToolStatus() == ToolEntryStatus.STATUS_UNREPORTED
                                        ? ToolEntryStatus.STATUS_UNREPORTED
                                        : ToolEntryStatus.STATUS_UNSENT));

                        toolEntry.setToolStatus(toolStatus);
                        toolEntry.setCoordinates(coordinates);
                        toolEntry.setToolType(toolType);
                        toolEntry.setVesselName(vesselName);
                        toolEntry.setVesselPhone(vesselPhoneNumber);
                        toolEntry.setSetupDateTime(toolSetupDateTime);
                        toolEntry.setRemovedTime(toolRemoved ? lastChangedDateString : null);
                        toolEntry.setComment(commentString);
                        toolEntry.setIRCS(vesselIrcsNumber);
                        toolEntry.setMMSI(vesselMmsiNumber);
                        toolEntry.setIMO(vesselImoNumber);
                        toolEntry.setRegNum(registrationNumber);
                        toolEntry.setLastChangedDateTime(lastChangedDateString);
                        toolEntry.setLastChangedBySource(lastChangedDateString);
                        toolEntry.setContactPersonName(contactPersonName);
                        toolEntry.setContactPersonPhone(contactPersonPhone);
                        toolEntry.setContactPersonEmail(contactPersonEmail);

                        try {
                            ImageView notificationView = (ImageView) ((View) editButton.getParent())
                                    .findViewById(R.id.tool_log_row_reported_image_view);

                            if (notificationView != null) {
                                notificationView.setVisibility(View.VISIBLE);
                                notificationView.setOnClickListener(new OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Toast.makeText(v.getContext(),
                                                R.string.notification_tool_unreported_changes,
                                                Toast.LENGTH_LONG).show();
                                    }
                                });
                            }

                            TextView dateTimeTextView = (TextView) ((View) editButton.getParent())
                                    .findViewById(R.id.tool_log_row_latest_date_text_view);
                            TextView toolTypeTextView = (TextView) ((View) editButton.getParent())
                                    .findViewById(R.id.tool_log_row_tool_type_text_view);
                            TextView positionTextView = (TextView) ((View) editButton.getParent())
                                    .findViewById(R.id.tool_log_row_tool_position_text_view);
                            StringBuilder sb = new StringBuilder();

                            sb.append(FiskInfoUtility
                                    .decimalToDMS((toolEntry.getCoordinates().get(0).getLatitude())));
                            sb.append(", ");
                            sb.append(FiskInfoUtility
                                    .decimalToDMS((toolEntry.getCoordinates().get(0).getLongitude())));

                            String coordinateString = sb.toString();
                            coordinateString = toolEntry.getCoordinates().size() < 2 ? coordinateString
                                    : coordinateString + "\n..";

                            sdfMilliSeconds.setTimeZone(TimeZone.getTimeZone("GMT+1"));
                            setupDateString = sdfMilliSeconds.format(setupDate);

                            dateTimeTextView.setText(setupDateString.substring(0, 16).replace("T", " "));
                            toolTypeTextView.setText(toolEntry.getToolType().toString());
                            positionTextView.setText(coordinateString);

                            Date toolDate;
                            Date currentDate = new Date();
                            try {
                                toolDate = sdf.parse(toolEntry.getSetupDateTime()
                                        .substring(0, toolEntry.getSetupDateTime().length() - 1)
                                        .concat(".000"));

                                long diff = currentDate.getTime() - toolDate.getTime();
                                double days = diff / updateButton.getContext().getResources()
                                        .getInteger(R.integer.milliseconds_in_a_day);

                                if (days > 14) {
                                    dateTimeTextView.setTextColor(ContextCompat
                                            .getColor(updateButton.getContext(), (R.color.error_red)));
                                } else {
                                    dateTimeTextView.setTextColor(toolTypeTextView.getCurrentTextColor());
                                }
                            } catch (ParseException e) {
                                e.printStackTrace();
                                return;
                            }
                        } catch (ClassCastException e) {
                            e.printStackTrace();
                        }

                        user.writeToSharedPref(updateButton.getContext());
                    } else {
                        Toast.makeText(editButton.getContext(), R.string.no_changes_made, Toast.LENGTH_LONG)
                                .show();
                    }

                    dialog.dismiss();
                }
            });

            cancelButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                }
            });

            dialog.show();
        }
    };
}

From source file:org.alfresco.mobile.android.application.fragments.person.PersonProfileFragment.java

private void display() {
    TextView tv = null;/* w ww  .ja  v a  2s .  c o  m*/
    ImageView bIm = null;

    // HEADER
    tv = (TextView) vRoot.findViewById(R.id.name);
    tv.setText(person.getFullName());

    // JOB TITLE
    tv = (TextView) vRoot.findViewById(R.id.jobTitle);
    if (person.getJobTitle() != null && !person.getJobTitle().isEmpty() && person.getCompany() != null
            && person.getCompany().getName() != null && !person.getCompany().getName().isEmpty()) {
        tv.setText(String.format(getString(R.string.work_at), person.getJobTitle(),
                person.getCompany().getName()));
    } else if (person.getJobTitle() != null) {
        tv.setText(person.getJobTitle());
    } else {
        tv.setText(person.getCompany().getName());
    }

    // Location
    tv = (TextView) vRoot.findViewById(R.id.location);
    tv.setText(person.getLocation());

    // Summary
    displayOrHide(R.id.description, person.getSummary(), R.id.summary_group);

    // Email
    displayOrHide(R.id.email_value, person.getEmail(), R.id.email_group);

    // Telephone
    displayOrHide(R.id.telephone_value, person.getTelephoneNumber(), R.id.telephone_group);

    // Mobile
    displayOrHide(R.id.mobile_value, person.getMobileNumber(), R.id.mobile_group);

    if (person.getTelephoneNumber() != null || person.getMobileNumber() != null
            || person.getCompany().getTelephoneNumber() != null) {
        bIm = (ImageView) vRoot.findViewById(R.id.action_call);
        bIm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(getActivity(), v);
                getMenu(popup.getMenu(), MODE_CALL);
                popup.setOnMenuItemClickListener(PersonProfileFragment.this);
                popup.show();
            }
        });
    } else {
        vRoot.findViewById(R.id.action_call).setVisibility(View.GONE);
    }

    // SKype
    if (person.getSkypeId() != null && !person.getSkypeId().isEmpty()) {
        displayGroup();
        tv = (TextView) vRoot.findViewById(R.id.skypeId_value);
        tv.setText(person.getSkypeId());
        bIm = (ImageView) vRoot.findViewById(R.id.action_skype);
        bIm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(getActivity(), v);
                getMenu(popup.getMenu(), MODE_SKYPE);
                popup.setOnMenuItemClickListener(PersonProfileFragment.this);
                popup.show();
            }
        });
    } else {
        vRoot.findViewById(R.id.action_skype).setVisibility(View.GONE);
        vRoot.findViewById(R.id.skypeId_group).setVisibility(View.GONE);
    }

    // IM
    if (person.getInstantMessageId() != null && !person.getInstantMessageId().isEmpty()) {
        displayGroup();
        tv = (TextView) vRoot.findViewById(R.id.instantMessagingId_value);
        tv.setText(person.getInstantMessageId());
    } else {
        vRoot.findViewById(R.id.instantMessagingId_group).setVisibility(View.GONE);
    }

    // Google
    if (person.getGoogleId() != null && !person.getGoogleId().isEmpty()) {
        displayGroup();
        tv = (TextView) vRoot.findViewById(R.id.googleId_value);
        tv.setText(person.getGoogleId());
        bIm = (ImageView) vRoot.findViewById(R.id.action_im);
        bIm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                actionStartIm(getActivity(), person.getGoogleId());
            }
        });
    } else {
        vRoot.findViewById(R.id.action_im).setVisibility(View.GONE);
        vRoot.findViewById(R.id.googleId_group).setVisibility(View.GONE);
    }

    if (!displayContactDetails) {
        vRoot.findViewById(R.id.contactInfo_group).setVisibility(View.GONE);
        displayContactDetails = false;
    }

    // Company
    Company cp = person.getCompany();
    displayCompanyOrHide(R.id.companyName_value, cp.getName(), R.id.companyName_group);
    displayCompanyOrHide(R.id.companyAdress1_value, cp.getAddress1(), R.id.companyAdress1_group);
    displayCompanyOrHide(R.id.companyAdress2_value, cp.getAddress2(), R.id.companyAdress2_group);
    displayCompanyOrHide(R.id.companyAdress3_value, cp.getAddress3(), R.id.companyAdress3_group);
    displayCompanyOrHide(R.id.companyPostcode_value, cp.getPostCode(), R.id.companyPostcode_group);
    displayCompanyOrHide(R.id.companyTelephone_value, cp.getTelephoneNumber(), R.id.companyTelephone_group);
    displayCompanyOrHide(R.id.companyFax_value, cp.getFaxNumber(), R.id.companyFax_group);
    displayCompanyOrHide(R.id.companyEmail_value, cp.getEmail(), R.id.companyEmail_group);

    // Add Contact
    bIm = (ImageView) vRoot.findViewById(R.id.action_addcontact);
    bIm.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            actionAddContact(getActivity(), person);
        }
    });

    // Add Contact
    if (person.getEmail() != null || person.getCompany().getEmail() != null) {
        bIm = (ImageView) vRoot.findViewById(R.id.action_email);
        bIm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(getActivity(), v);
                getMenu(popup.getMenu(), MODE_EMAIL);
                popup.setOnMenuItemClickListener(PersonProfileFragment.this);
                popup.show();
            }
        });
    } else {
        vRoot.findViewById(R.id.action_email).setVisibility(View.GONE);
    }

    // Geolocalisation
    if (person.getCompany().getFullAddress() != null) {
        displayGroup();
        bIm = (ImageView) vRoot.findViewById(R.id.action_geolocation);
        bIm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                actionGeolocalisation(getActivity(), person.getCompany().getFullAddress(),
                        person.getCompany().getName());
            }
        });
    } else {
        vRoot.findViewById(R.id.action_geolocation).setVisibility(View.GONE);
    }

    if (!displayCompanyDetails) {
        vRoot.findViewById(R.id.company_group).setVisibility(View.GONE);
    }
}

From source file:com.arkami.myidkey.activity.KeyCardEditActivity.java

/**
 * Adds view to linear layout//from   w  w w  .jav a  2  s  .  co  m
 */
private void addFileToList(final FileObject fileObject) {
    if (fileObject == null) {
        return;
    }
    if (fileObject.getId() == null) {
        fileObject.setId(fileDataSource.insert(fileObject));
        long[] fileIds = Arrays.copyOf(keyCard.getFileIds(), keyCard.getFileIds().length + 1);
        fileIds[fileIds.length - 1] = fileObject.getId();
        keyCard.setFileIds(fileIds);
    }
    // long[] newIds = Arrays.copyOf(keyCard.getFileIds(),
    // keyCard.getFileIds().length + 1);
    // long newId = fileObject.getId();
    // newIds[newIds.length - 1] = newId;
    // Toast.makeText(this, newId + "", Toast.LENGTH_SHORT).show();
    // keyCard.setFileIds(newIds);
    // keyCardDataSource.update(keyCard);
    final View view = View.inflate(this, R.layout.photo_audio_list_item, null);

    TextView fileName = (TextView) view.findViewById(R.id.photo_audio_list_item_file_name);
    TextView fileSize = (TextView) view.findViewById(R.id.photo_audio_list_item_file_size);
    ImageView thumb = (ImageView) view.findViewById(R.id.photo_audio_list_item_thumb);
    ImageButton close = (ImageButton) view.findViewById(R.id.photo_audio_list_item_close_button);
    fileName.setText(fileObject.getName());
    fileSize.setText(fileObject.getSize() + " bytes");
    view.setVisibility(View.VISIBLE);

    switch (Cache.getInstance(this).getFileTypeEnum(fileObject.getFileType())) {
    case audio:
        // add audio

        close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                audioLinearLayout.removeView(view);
                if (audioLinearLayout.getChildCount() == 0) {
                    audioListRelativeLayout.setVisibility(View.GONE);
                }
                keyCard = removeFileID(fileObject.getId(), keyCard);
                // KeyCardEditActivity.this.keyCardDataSource.update(keyCard);

            }
        });
        thumb.setImageResource(R.drawable.speaker);
        thumb.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(android.content.Intent.ACTION_VIEW);
                File file = new File(fileObject.getPathToFile());
                intent.setDataAndType(Uri.fromFile(file), "audio/3gp");
                Log.w("Uri.fromFile(file) = ", fileObject.getPathToFile());
                startActivity(intent);
            }
        });
        audioLinearLayout.addView(view);
        audioListRelativeLayout.setVisibility(View.VISIBLE);
        break;
    case photo:
        // add photo
        // for photo file
        close.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                photosLinearLayout.removeView(view);

                if (photosLinearLayout.getChildCount() == 0) {
                    photosListRelativeLayout.setVisibility(View.GONE);
                }
                if (fileObject.getId() != null) {
                    keyCard = removeFileID(fileObject.getId(), keyCard);
                }
            }
        });

        thumb.setImageBitmap(Common.getImageFromIntent(fileObject.getPathToFile(), true));
        thumb.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent viewImageIntent = new Intent(KeyCardEditActivity.this, ViewImageIActivity.class);
                viewImageIntent.putExtra(ViewImageIActivity.IMAGE_KEY, fileObject);
                startActivity(viewImageIntent);
            }
        });
        photosLinearLayout.addView(view);
        photosListRelativeLayout.setVisibility(View.VISIBLE);
        // end for photo file
        break;
    default:
        break;
    }
}