Example usage for android.widget RelativeLayout setVisibility

List of usage examples for android.widget RelativeLayout setVisibility

Introduction

In this page you can find the example usage for android.widget RelativeLayout setVisibility.

Prototype

@RemotableViewMethod
public void setVisibility(@Visibility int visibility) 

Source Link

Document

Set the visibility state of this view.

Usage

From source file:org.schabi.newpipe.detail.VideoItemDetailFragment.java

private void updateInfo(final StreamInfo info) {
    Activity a = getActivity();//from   w w w  .j  a  v a2s  .  co  m

    RelativeLayout textContentLayout = (RelativeLayout) activity.findViewById(R.id.detail_text_content_layout);
    final TextView videoTitleView = (TextView) activity.findViewById(R.id.detail_video_title_view);
    TextView uploaderView = (TextView) activity.findViewById(R.id.detail_uploader_view);
    TextView viewCountView = (TextView) activity.findViewById(R.id.detail_view_count_view);
    TextView thumbsUpView = (TextView) activity.findViewById(R.id.detail_thumbs_up_count_view);
    TextView thumbsDownView = (TextView) activity.findViewById(R.id.detail_thumbs_down_count_view);
    TextView uploadDateView = (TextView) activity.findViewById(R.id.detail_upload_date_view);
    TextView descriptionView = (TextView) activity.findViewById(R.id.detail_description_view);
    RecyclerView nextStreamView = (RecyclerView) activity.findViewById(R.id.detail_next_stream_content);
    RelativeLayout nextVideoRootFrame = (RelativeLayout) activity
            .findViewById(R.id.detail_next_stream_root_layout);
    TextView similarTitle = (TextView) activity.findViewById(R.id.detail_similar_title);
    Button backgroundButton = (Button) activity
            .findViewById(R.id.detail_stream_thumbnail_window_background_button);
    View topView = activity.findViewById(R.id.detailTopView);
    Button channelButton = (Button) activity.findViewById(R.id.channel_button);

    // prevents a crash if the activity/fragment was already left when the response came
    if (channelButton != null) {

        progressBar.setVisibility(View.GONE);
        if (info.next_video != null) {
            // todo: activate this function or remove it
            nextStreamView.setVisibility(View.GONE);
        } else {
            nextStreamView.setVisibility(View.GONE);
            activity.findViewById(R.id.detail_similar_title).setVisibility(View.GONE);
        }

        textContentLayout.setVisibility(View.VISIBLE);
        if (android.os.Build.VERSION.SDK_INT < 18) {
            playVideoButton.setVisibility(View.VISIBLE);
        } else {
            ImageView playArrowView = (ImageView) activity.findViewById(R.id.play_arrow_view);
            playArrowView.setVisibility(View.VISIBLE);
        }

        if (!showNextStreamItem) {
            nextVideoRootFrame.setVisibility(View.GONE);
            similarTitle.setVisibility(View.GONE);
        }

        videoTitleView.setText(info.title);

        topView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                    ImageView arrow = (ImageView) activity.findViewById(R.id.toggle_description_view);
                    View extra = activity.findViewById(R.id.detailExtraView);
                    if (extra.getVisibility() == View.VISIBLE) {
                        extra.setVisibility(View.GONE);
                        arrow.setImageResource(R.drawable.arrow_down);
                    } else {
                        extra.setVisibility(View.VISIBLE);
                        arrow.setImageResource(R.drawable.arrow_up);
                    }
                }
                return true;
            }
        });

        // Since newpipe is designed to work even if certain information is not available,
        // the UI has to react on missing information.
        videoTitleView.setText(info.title);
        if (!info.uploader.isEmpty()) {
            uploaderView.setText(info.uploader);
        } else {
            activity.findViewById(R.id.detail_uploader_view).setVisibility(View.GONE);
        }
        if (info.view_count >= 0) {
            viewCountView.setText(Localization.localizeViewCount(info.view_count, a));
        } else {
            viewCountView.setVisibility(View.GONE);
        }
        if (info.dislike_count >= 0) {
            thumbsDownView.setText(Localization.localizeNumber(info.dislike_count, a));
        } else {
            thumbsDownView.setVisibility(View.INVISIBLE);
            activity.findViewById(R.id.detail_thumbs_down_count_view).setVisibility(View.GONE);
        }
        if (info.like_count >= 0) {
            thumbsUpView.setText(Localization.localizeNumber(info.like_count, a));
        } else {
            thumbsUpView.setVisibility(View.GONE);
            activity.findViewById(R.id.detail_thumbs_up_img_view).setVisibility(View.GONE);
            thumbsDownView.setVisibility(View.GONE);
            activity.findViewById(R.id.detail_thumbs_down_img_view).setVisibility(View.GONE);
        }
        if (!info.upload_date.isEmpty()) {
            uploadDateView.setText(Localization.localizeDate(info.upload_date, a));
        } else {
            uploadDateView.setVisibility(View.GONE);
        }
        if (!info.description.isEmpty()) {
            descriptionView.setText(Html.fromHtml(info.description));
        } else {
            descriptionView.setVisibility(View.GONE);
        }

        descriptionView.setMovementMethod(LinkMovementMethod.getInstance());

        // parse streams
        Vector<VideoStream> streamsToUse = new Vector<>();
        for (VideoStream i : info.video_streams) {
            if (useStream(i, streamsToUse)) {
                streamsToUse.add(i);
            }
        }

        textContentLayout.setVisibility(View.VISIBLE);

        if (info.next_video == null) {
            activity.findViewById(R.id.detail_next_stream_title).setVisibility(View.GONE);
        }

        if (info.related_streams != null && !info.related_streams.isEmpty()) {
            initSimilarVideos(info);
        } else {
            activity.findViewById(R.id.detail_similar_title).setVisibility(View.GONE);
            activity.findViewById(R.id.similar_streams_view).setVisibility(View.GONE);
        }

        setupActionBarHandler(info);

        if (autoPlayEnabled) {
            playVideo(info);
        }

        if (android.os.Build.VERSION.SDK_INT < 18) {
            playVideoButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    playVideo(info);
                }
            });
        }

        backgroundButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playVideo(info);
            }
        });

        if (info.channel_url != null && info.channel_url != "") {
            channelButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i = new Intent(activity, ChannelActivity.class);
                    i.putExtra(ChannelActivity.CHANNEL_URL, info.channel_url);
                    i.putExtra(ChannelActivity.SERVICE_ID, info.service_id);
                    startActivity(i);
                }
            });
        } else {
            channelButton.setVisibility(Button.GONE);
        }

        initThumbnailViews(info);
    }
}

From source file:org.schabi.newpipe.VideoItemDetailFragment.java

private void updateInfo(final StreamInfo info) {
    try {//from  ww  w.  j a va2  s .  c  om
        Context c = getContext();
        VideoInfoItemViewCreator videoItemViewCreator = new VideoInfoItemViewCreator(
                LayoutInflater.from(getActivity()));

        RelativeLayout textContentLayout = (RelativeLayout) activity.findViewById(R.id.detailTextContentLayout);
        final TextView videoTitleView = (TextView) activity.findViewById(R.id.detailVideoTitleView);
        TextView uploaderView = (TextView) activity.findViewById(R.id.detailUploaderView);
        TextView viewCountView = (TextView) activity.findViewById(R.id.detailViewCountView);
        TextView thumbsUpView = (TextView) activity.findViewById(R.id.detailThumbsUpCountView);
        TextView thumbsDownView = (TextView) activity.findViewById(R.id.detailThumbsDownCountView);
        TextView uploadDateView = (TextView) activity.findViewById(R.id.detailUploadDateView);
        TextView descriptionView = (TextView) activity.findViewById(R.id.detailDescriptionView);
        FrameLayout nextVideoFrame = (FrameLayout) activity.findViewById(R.id.detailNextVideoFrame);
        RelativeLayout nextVideoRootFrame = (RelativeLayout) activity
                .findViewById(R.id.detailNextVideoRootLayout);
        Button nextVideoButton = (Button) activity.findViewById(R.id.detailNextVideoButton);
        TextView similarTitle = (TextView) activity.findViewById(R.id.detailSimilarTitle);
        Button backgroundButton = (Button) activity
                .findViewById(R.id.detailVideoThumbnailWindowBackgroundButton);
        View topView = activity.findViewById(R.id.detailTopView);
        View nextVideoView = null;
        if (info.next_video != null) {
            nextVideoView = videoItemViewCreator.getViewFromVideoInfoItem(null, nextVideoFrame,
                    info.next_video);
        } else {
            activity.findViewById(R.id.detailNextVidButtonAndContentLayout).setVisibility(View.GONE);
            activity.findViewById(R.id.detailNextVideoTitle).setVisibility(View.GONE);
            activity.findViewById(R.id.detailNextVideoButton).setVisibility(View.GONE);
        }

        progressBar.setVisibility(View.GONE);
        if (nextVideoView != null) {
            nextVideoFrame.addView(nextVideoView);
        }

        initThumbnailViews(info, nextVideoFrame);

        textContentLayout.setVisibility(View.VISIBLE);
        if (android.os.Build.VERSION.SDK_INT < 18) {
            playVideoButton.setVisibility(View.VISIBLE);
        } else {
            ImageView playArrowView = (ImageView) activity.findViewById(R.id.playArrowView);
            playArrowView.setVisibility(View.VISIBLE);
        }

        if (!showNextVideoItem) {
            nextVideoRootFrame.setVisibility(View.GONE);
            similarTitle.setVisibility(View.GONE);
        }

        videoTitleView.setText(info.title);

        topView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                    ImageView arrow = (ImageView) activity.findViewById(R.id.toggleDescriptionView);
                    View extra = activity.findViewById(R.id.detailExtraView);
                    if (extra.getVisibility() == View.VISIBLE) {
                        extra.setVisibility(View.GONE);
                        arrow.setImageResource(R.drawable.arrow_down);
                    } else {
                        extra.setVisibility(View.VISIBLE);
                        arrow.setImageResource(R.drawable.arrow_up);
                    }
                }
                return true;
            }
        });

        // Since newpipe is designed to work even if certain information is not available,
        // the UI has to react on missing information.
        videoTitleView.setText(info.title);
        if (!info.uploader.isEmpty()) {
            uploaderView.setText(info.uploader);
        } else {
            activity.findViewById(R.id.detailUploaderWrapView).setVisibility(View.GONE);
        }
        if (info.view_count >= 0) {
            viewCountView.setText(Localization.localizeViewCount(info.view_count, c));
        } else {
            viewCountView.setVisibility(View.GONE);
        }
        if (info.dislike_count >= 0) {
            thumbsDownView.setText(Localization.localizeNumber(info.dislike_count, c));
        } else {
            thumbsDownView.setVisibility(View.INVISIBLE);
            activity.findViewById(R.id.detailThumbsDownImgView).setVisibility(View.GONE);
        }
        if (info.like_count >= 0) {
            thumbsUpView.setText(Localization.localizeNumber(info.like_count, c));
        } else {
            thumbsUpView.setVisibility(View.GONE);
            activity.findViewById(R.id.detailThumbsUpImgView).setVisibility(View.GONE);
            thumbsDownView.setVisibility(View.GONE);
            activity.findViewById(R.id.detailThumbsDownImgView).setVisibility(View.GONE);
        }
        if (!info.upload_date.isEmpty()) {
            uploadDateView.setText(Localization.localizeDate(info.upload_date, c));
        } else {
            uploadDateView.setVisibility(View.GONE);
        }
        if (!info.description.isEmpty()) {
            descriptionView.setText(Html.fromHtml(info.description));
        } else {
            descriptionView.setVisibility(View.GONE);
        }

        descriptionView.setMovementMethod(LinkMovementMethod.getInstance());

        // parse streams
        Vector<VideoStream> streamsToUse = new Vector<>();
        for (VideoStream i : info.video_streams) {
            if (useStream(i, streamsToUse)) {
                streamsToUse.add(i);
            }
        }

        nextVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent detailIntent = new Intent(getActivity(), VideoItemDetailActivity.class);
                /*detailIntent.putExtra(
                        VideoItemDetailFragment.ARG_ITEM_ID, currentVideoInfo.nextVideo.id); */
                detailIntent.putExtra(VideoItemDetailFragment.VIDEO_URL, info.next_video.webpage_url);
                detailIntent.putExtra(VideoItemDetailFragment.STREAMING_SERVICE, streamingServiceId);
                startActivity(detailIntent);
            }
        });
        textContentLayout.setVisibility(View.VISIBLE);

        if (info.related_videos != null && !info.related_videos.isEmpty()) {
            initSimilarVideos(info, videoItemViewCreator);
        } else {
            activity.findViewById(R.id.detailSimilarTitle).setVisibility(View.GONE);
            activity.findViewById(R.id.similarVideosView).setVisibility(View.GONE);
        }

        setupActionBarHandler(info);

        if (autoPlayEnabled) {
            playVideo(info);
        }

        if (android.os.Build.VERSION.SDK_INT < 18) {
            playVideoButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    playVideo(info);
                }
            });
        }

        backgroundButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playVideo(info);
            }
        });

    } catch (java.lang.NullPointerException e) {
        Log.w(TAG, "updateInfo(): Fragment closed before thread ended work... or else");
        e.printStackTrace();
    }
}

From source file:com.geecko.QuickLyric.fragment.LyricsViewFragment.java

@SuppressLint("SetTextI18n")
public void update(Lyrics lyrics, View layout, boolean animation) {
    File musicFile = null;/*from   w w  w. ja  v  a2s .c o  m*/
    Bitmap cover = null;
    if (PermissionsChecker.hasPermission(getActivity(), "android.permission.READ_EXTERNAL_STORAGE")) {
        musicFile = Id3Reader.getFile(getActivity(), lyrics.getOriginalArtist(), lyrics.getOriginalTrack());
        cover = Id3Reader.getCover(getActivity(), lyrics.getArtist(), lyrics.getTitle());
    }
    setCoverArt(cover, null);
    boolean artCellDownload = Integer.valueOf(
            PreferenceManager.getDefaultSharedPreferences(getActivity()).getString("pref_artworks", "0")) == 0;
    if (cover == null)
        new CoverArtLoader().execute(lyrics, this.getActivity(),
                artCellDownload || OnlineAccessVerifier.isConnectedWifi(getActivity()));
    getActivity().findViewById(R.id.edit_tags_btn).setEnabled(true);
    getActivity().findViewById(R.id.edit_tags_btn)
            .setVisibility(musicFile == null || !musicFile.canWrite() || lyrics.isLRC()
                    || Id3Reader.getLyrics(getActivity(), lyrics.getArtist(), lyrics.getTitle()) == null
                            ? View.GONE
                            : View.VISIBLE);
    TextSwitcher textSwitcher = ((TextSwitcher) layout.findViewById(R.id.switcher));
    LrcView lrcView = (LrcView) layout.findViewById(R.id.lrc_view);
    View v = getActivity().findViewById(R.id.tracks_msg);
    if (v != null)
        ((ViewGroup) v.getParent()).removeView(v);
    TextView artistTV = (TextView) getActivity().findViewById(R.id.artist);
    TextView songTV = (TextView) getActivity().findViewById(R.id.song);
    final TextView id3TV = (TextView) layout.findViewById(R.id.source_tv);
    TextView writerTV = (TextView) layout.findViewById(R.id.writer_tv);
    TextView copyrightTV = (TextView) layout.findViewById(R.id.copyright_tv);
    RelativeLayout bugLayout = (RelativeLayout) layout.findViewById(R.id.error_msg);
    this.mLyrics = lyrics;
    if (SDK_INT >= ICE_CREAM_SANDWICH)
        beamLyrics(lyrics, this.getActivity());
    new PresenceChecker().execute(this, new String[] { lyrics.getArtist(), lyrics.getTitle(),
            lyrics.getOriginalArtist(), lyrics.getOriginalTrack() });

    if (lyrics.getArtist() != null)
        artistTV.setText(lyrics.getArtist());
    else
        artistTV.setText("");
    if (lyrics.getTitle() != null)
        songTV.setText(lyrics.getTitle());
    else
        songTV.setText("");
    if (lyrics.getCopyright() != null) {
        copyrightTV.setText("Copyright: " + lyrics.getCopyright());
        copyrightTV.setVisibility(View.VISIBLE);
    } else {
        copyrightTV.setText("");
        copyrightTV.setVisibility(View.GONE);
    }
    if (lyrics.getWriter() != null) {
        if (lyrics.getWriter().contains(","))
            writerTV.setText("Writers:\n" + lyrics.getWriter());
        else
            writerTV.setText("Writer:" + lyrics.getWriter());
        writerTV.setVisibility(View.VISIBLE);
    } else {
        writerTV.setText("");
        writerTV.setVisibility(View.GONE);
    }
    if (isActiveFragment)
        ((RefreshIcon) getActivity().findViewById(R.id.refresh_fab)).show();
    EditText newLyrics = (EditText) getActivity().findViewById(R.id.edit_lyrics);
    if (newLyrics != null)
        newLyrics.setText("");

    if (lyrics.getFlag() == Lyrics.POSITIVE_RESULT) {
        if (!lyrics.isLRC()) {
            textSwitcher.setVisibility(View.VISIBLE);
            lrcView.setVisibility(View.GONE);
            if (animation)
                textSwitcher.setText(Html.fromHtml(lyrics.getText()));
            else
                textSwitcher.setCurrentText(Html.fromHtml(lyrics.getText()));
        } else {
            textSwitcher.setVisibility(View.GONE);
            lrcView.setVisibility(View.VISIBLE);
            lrcView.setOriginalLyrics(lyrics);
            lrcView.setSourceLrc(lyrics.getText());
            if (isActiveFragment)
                ((ControllableAppBarLayout) getActivity().findViewById(R.id.appbar)).expandToolbar(true);
            updateLRC();
        }

        bugLayout.setVisibility(View.INVISIBLE);
        id3TV.setMovementMethod(LinkMovementMethod.getInstance());
        if ("Storage".equals(lyrics.getSource())) {
            id3TV.setVisibility(View.VISIBLE);
            SpannableString text = new SpannableString(getString(R.string.from_id3));
            text.setSpan(new UnderlineSpan(), 1, text.length() - 1, 0);
            id3TV.setText(text);
            id3TV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    ((MainActivity) getActivity()).id3PopUp(id3TV);
                }
            });
        } else {
            id3TV.setOnClickListener(null);
            id3TV.setVisibility(View.GONE);
        }
        mScrollView.post(new Runnable() {
            @Override
            public void run() {
                mScrollView.scrollTo(0, 0); //only useful when coming from localLyricsFragment
                mScrollView.smoothScrollTo(0, 0);
            }
        });
    } else {
        textSwitcher.setText("");
        textSwitcher.setVisibility(View.INVISIBLE);
        lrcView.setVisibility(View.INVISIBLE);
        bugLayout.setVisibility(View.VISIBLE);
        int message;
        int whyVisibility;
        if (lyrics.getFlag() == Lyrics.ERROR || !OnlineAccessVerifier.check(getActivity())) {
            message = R.string.connection_error;
            whyVisibility = TextView.GONE;
        } else {
            message = R.string.no_results;
            whyVisibility = TextView.VISIBLE;
            updateSearchView(false, lyrics.getTitle(), false);
        }
        TextView whyTextView = ((TextView) bugLayout.findViewById(R.id.bugtext_why));
        ((TextView) bugLayout.findViewById(R.id.bugtext)).setText(message);
        whyTextView.setVisibility(whyVisibility);
        whyTextView.setPaintFlags(whyTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
        id3TV.setVisibility(View.GONE);
    }
    stopRefreshAnimation();
    getActivity().getIntent().setAction("");
    getActivity().invalidateOptionsMenu();
}

From source file:com.equinox.prodriver.Activities.RegisterDriverActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register_driver);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);/*from  w  w w.j a  v a 2  s.  c o  m*/
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    context = this;
    appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
    appBarLayout.setExpanded(false, true);
    mainScrollView = (NestedScrollView) findViewById(R.id.content_register_driver);
    mainScrollView.setSmoothScrollingEnabled(true);
    selectorsLayouts = new ArrayList<>();

    editDriver = new Driver();
    preferredPlace = new PrologixPlace();
    if (currentDriver == null) {
        getSupportActionBar().setTitle(getString(R.string.title_activity_register_driver));
        if (savedInstanceState != null && savedInstanceState.getBoolean("EDITING")) {
            editDriver = tempDriver;
            if (editDriver == null)
                editDriver = new Driver();
        }
        vehiclesList = new ArrayList<>();
    } else {
        getSupportActionBar().setTitle(getString(R.string.title_activity_update_driver));
        editDriver = currentDriver.clone();
        if (editDriver.getPreferredAddress() != null) {
            preferredPlace.setAddress(
                    driverGson.fromJson(driverGson.toJson(editDriver.getPreferredAddress()), GeoAddress.class));
            preferredPlace.setLocation(
                    driverGson.fromJson(driverGson.toJson(editDriver.getPreferredLocation()), LatLng.class));
        }
    }

    storagePermission = new PermissionManager(this);
    if (!storagePermission.checkReadStoragePermission())
        storagePermission.getReadStoragePermission();
    registerEmailHeaderFragment = RegisterEmailHeaderFragment.newInstance(editDriver);

    vehicleIndicator = (ImageView) findViewById(R.id.driver_vehicle_indicator);
    if (editDriver.getVehicles() == null)
        editDriver.setVehicles(new ArrayList<Vehicle>());
    vehicleRecyclerAdapter = new VehicleRecyclerAdapter(context, editDriver.getVehicles(), false);
    if (!editDriver.getVehicles().isEmpty())
        setIndicator(context, vehicleIndicator, true);
    if (!editDriver.getVehicles().contains(createVehicle)) {
        editDriver.getVehicles().add(new Vehicle());
        //TODO remove this.. just for testing only
        /*String vehicleId = "SA-3184VLB";
        DriverTask driverTask = new DriverTask(vehicleFetcher, "en");
        driverTask.getVehicle.execute(vehicleId);*/
    }
    vehicleListView = (RecyclerView) findViewById(R.id.vehicle_list_view);
    vehicleListView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
    vehicleListView.setHasFixedSize(true);
    vehicleListView.setAdapter(vehicleRecyclerAdapter);
    vehicleListView.setNestedScrollingEnabled(false);

    licenseIndicator = (ImageView) findViewById(R.id.license_info_indicator);
    licenseValueNumber = (TextView) findViewById(R.id.license_info_number);
    licenseValueExpiry = (TextView) findViewById(R.id.license_info_expiry);
    licenseImage = (ImageView) findViewById(R.id.license_image);
    licenseImageLoaded = (NetworkImageView) findViewById(R.id.license_image_loaded);
    licenseInfoLayout = (RelativeLayout) findViewById(R.id.license_info_layout);
    if (editDriver.getLicenseNumber() != null) {
        setIndicator(context, licenseIndicator, true);
        licenseValueNumber.setText(editDriver.getLicenseNumber());
        licenseValueExpiry.setText(StringManipulation.getFormattedDate(editDriver.getLicenseExpiry()));
        if (editDriver.getLicenseImage() != null)
            licenseImageLoaded.setImageUrl(editDriver.getLicenseImage(),
                    DataHolder.getInstance().getImageLoader());
    }
    if (photo1 != null)
        licenseImage.setImageBitmap(photo1);
    licenseInfoLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent scanIdIntent = new Intent(context, CameraVisionActivity.class);
            scanIdIntent.putExtra("source", REQUEST_DRIVER_LICENSE);
            startActivity(scanIdIntent);
        }
    });

    residenceIndicator = (ImageView) findViewById(R.id.residence_info_indicator);
    residenceValueNumber = (TextView) findViewById(R.id.residence_info_number);
    residenceValueExpiry = (TextView) findViewById(R.id.residence_info_expiry);
    residenceValueLegalName = (TextView) findViewById(R.id.residence_info_legal_name);
    residenceImage = (ImageView) findViewById(R.id.residence_image);
    residenceImageLoaded = (NetworkImageView) findViewById(R.id.residence_image_loaded);
    residenceInfoLayout = (RelativeLayout) findViewById(R.id.residence_info_layout);
    if (editDriver.getResidenceNumber() != null) {
        setIndicator(context, residenceIndicator, true);
        residenceValueNumber.setText(editDriver.getResidenceNumber());
        residenceValueLegalName.setText(editDriver.getLegalName());
        if (editDriver.getResidenceImage() != null)
            residenceImageLoaded.setImageUrl(editDriver.getResidenceImage(),
                    DataHolder.getInstance().getImageLoader());
    }
    if (photo2 != null)
        residenceImage.setImageBitmap(photo2);
    residenceInfoLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent scanIdIntent = new Intent(context, CameraVisionActivity.class);
            scanIdIntent.putExtra(SOURCE, REQUEST_RESIDENCE_ID);
            startActivity(scanIdIntent);
        }
    });

    nationalityIndicator = (ImageView) findViewById(R.id.nationality_indicator);
    nationalityValue = (TextView) findViewById(R.id.nationality_value);
    nationalityLayout = (RelativeLayout) findViewById(R.id.nationality_layout);
    nationalityProgressLayout = (LinearLayout) findViewById(R.id.nationality_progress_layout);
    final RelativeLayout nationalitySelector = (RelativeLayout) findViewById(R.id.nationality_selector);
    selectorsLayouts.add(nationalitySelector);
    nationalitySelectorContent = (LinearLayout) findViewById(R.id.nationality_selector_content);
    countryTask = new CountryTask(countryListHandler, "en");
    countryTask.getCountryList.execute("en");
    if (editDriver.getNationality() != null) {
        setIndicator(context, nationalityIndicator, true);
        nationalityValue.setText(editDriver.getNationality().getCountryName());
    }
    nationalityAuto = (InstantAutoComplete) findViewById(R.id.nationality_auto);
    nationalityLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hideKeyboard(context);
            if (nationalitySelector.getVisibility() == View.GONE) {
                closeInactiveLayouts(appBarLayout, selectorsLayouts, nationalitySelector);
                mainScrollView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mainScrollView.smoothScrollTo(0, nationalityLayout.getTop());
                        nationalityAuto.showDropDown();
                    }
                }, 1000);
            }
            if (countryTask.getCountryList.getStatus().equals(AsyncTask.Status.RUNNING)) {
                nationalityProgressLayout.setVisibility(View.VISIBLE);
                nationalitySelectorContent.setVisibility(View.GONE);
            }
            LinearLayout okayButton = (LinearLayout) findViewById(R.id.nationality_okay_button);
            okayButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (editDriver.getNationality() != null) {
                        setIndicator(context, nationalityIndicator, true);
                        nationalityValue.setText(editDriver.getNationality().getCountryName());
                        addressLayout.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                addressLayout.performClick();
                            }
                        }, 1000);
                    } else {
                        setIndicator(context, nationalityIndicator, false);
                        nationalitySelector.setVisibility(View.GONE);
                    }
                }
            });
            LinearLayout cancelButton = (LinearLayout) findViewById(R.id.nationality_cancel_button);
            cancelButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    nationalitySelector.setVisibility(View.GONE);
                }
            });
        }
    });

    addressIndicator = (ImageView) findViewById(R.id.preferred_address_indicator);
    addressValue = (TextView) findViewById(R.id.preferred_address_value);
    addressLayout = (RelativeLayout) findViewById(R.id.preferred_address_layout);
    if (editDriver.getPreferredAddress() != null) {
        setIndicator(context, addressIndicator, true);
        preferredPlace.setAddress(transform(editDriver.getPreferredAddress()));
        preferredPlace.setLocation(transform(editDriver.getPreferredLocation()));
        addressValue.setText(preferredPlace.getAddress().getFullAddress());
    }
    addressChooser = (FrameLayout) findViewById(R.id.preferred_address_chooser);
    selectorsLayouts.add(addressChooser);
    addressLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hideKeyboard(context);
            try {
                if (addressChooser.getVisibility() == View.GONE) {
                    closeInactiveLayouts(appBarLayout, selectorsLayouts, addressChooser);
                    getSupportFragmentManager().beginTransaction()
                            .replace(R.id.preferred_address_chooser,
                                    PlaceChooserFragment.newInstance(preferredPlace, placeChooseHandler))
                            .commit();
                    mainScrollView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mainScrollView.smoothScrollTo(0, addressLayout.getTop());
                        }
                    }, 1500);
                } else {
                    addressChooser.setVisibility(View.GONE);
                    getSupportFragmentManager().popBackStack();
                }
            } catch (Resources.NotFoundException | OutOfMemoryError ignored) {
            }
        }
    });

    final ImageView phoneIndicator = (ImageView) findViewById(R.id.driver_phone_indicator);
    final TextView phoneValue = (TextView) findViewById(R.id.driver_phone_value);
    if (editDriver.getPhoneNumber() != null) {
        setIndicator(context, phoneIndicator, true);
        phoneValue.setText(editDriver.getPhoneNumber().replace(currentCountry.getPhoneCode(), ""));
    }
    final LinearLayout phoneSelector = (LinearLayout) findViewById(R.id.driver_phone_selector);
    selectorsLayouts.add(phoneSelector);
    phoneLayout = (RelativeLayout) findViewById(R.id.driver_phone_layout);
    phoneLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hideKeyboard(context);
            if (phoneSelector.getVisibility() == View.GONE) {
                closeInactiveLayouts(appBarLayout, selectorsLayouts, phoneSelector);
                mainScrollView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mainScrollView.smoothScrollTo(0, phoneLayout.getTop());
                    }
                }, 1000);
            }
            final EditText input = (EditText) findViewById(R.id.phone_number);
            if (editDriver.getPhoneNumber() != null)
                input.setText(editDriver.getPhoneNumber().replace(currentCountry.getPhoneCode(), ""));
            TextView phoneCode = (TextView) findViewById(R.id.country_code);
            phoneCode.setText(currentCountry.getPhoneCode());
            NetworkImageView countryFlag = (NetworkImageView) findViewById(R.id.country_flag);
            countryFlag.setImageUrl(currentCountry.getFlag(), DataHolder.getInstance().getImageLoader());
            LinearLayout okayButton = (LinearLayout) findViewById(R.id.driver_phone_okay_button);
            okayButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!input.getText().toString().isEmpty()) {
                        String phoneNumberEdit = currentCountry.getPhoneCode()
                                + input.getText().toString().replaceAll(" ", "");
                        editDriver.setPhoneNumber(phoneNumberEdit);
                        phoneValue.setText(phoneNumberEdit);
                        setIndicator(context, phoneIndicator, true);
                        mainScrollView.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mainScrollView.smoothScrollTo(0, dobLayout.getTop());
                            }
                        }, 1000);
                    } else {
                        phoneValue.setText(getString(R.string.driver_phone_hint));
                        setIndicator(context, phoneIndicator, false);
                    }
                    phoneSelector.setVisibility(View.GONE);
                }
            });
            LinearLayout cancelButton = (LinearLayout) findViewById(R.id.driver_phone_cancel_button);
            cancelButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    phoneSelector.setVisibility(View.GONE);
                }
            });
        }
    });

    dobValue = (TextView) findViewById(R.id.driver_dob_value);
    if (editDriver.getDob() != null)
        dobValue.setText(StringManipulation.getFormattedDate(editDriver.getDob()));
    dobLayout = (RelativeLayout) findViewById(R.id.driver_dob_layout);
    dobLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Calendar calendar = Calendar.getInstance();
            if (editDriver.getDob() != null) {
                dobValue.setText(StringManipulation.getFormattedDate(editDriver.getDob()));
                calendar.setTimeInMillis(editDriver.getDob());
            }
            DatePickerDialog datePickerDialog = DatePickerDialog
                    .newInstance(new DatePickerDialog.OnDateSetListener() {
                        @Override
                        public void onDateSet(DatePickerDialog view, int year, int monthOfYear,
                                int dayOfMonth) {
                            calendar.set(Calendar.YEAR, year);
                            calendar.set(Calendar.MONTH, monthOfYear);
                            calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                            editDriver.setDob(calendar.getTimeInMillis());
                            dobValue.setText(StringManipulation.getFormattedDate(editDriver.getDob()));
                        }
                    }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
                            calendar.get(Calendar.DAY_OF_MONTH));
            datePickerDialog.show(getFragmentManager(), "Datepickerdialog");
        }
    });

    final TextView genderValue = (TextView) findViewById(R.id.driver_gender_value);
    if (editDriver.getGender() != null)
        genderValue.setText(
                editDriver.getGender() ? getString(R.string.male_option) : getString(R.string.female_option));
    final LinearLayout genderSelector = (LinearLayout) findViewById(R.id.driver_gender_selector);
    selectorsLayouts.add(genderSelector);
    final RelativeLayout genderLayout = (RelativeLayout) findViewById(R.id.driver_gender_layout);
    genderLayout.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            hideKeyboard(context);
            if (genderSelector.getVisibility() == View.GONE) {
                closeInactiveLayouts(appBarLayout, selectorsLayouts, genderSelector);
                mainScrollView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mainScrollView.smoothScrollTo(0, genderLayout.getTop());
                    }
                }, 1000);
            } else
                genderSelector.setVisibility(View.GONE);
            final int checkedPos = editDriver.getGender() == null ? -1
                    : (editDriver.getGender() ? R.id.driver_gender_male : R.id.driver_gender_female);
            final RadioGroup insuranceRadioGroup = (RadioGroup) findViewById(R.id.driver_gender_radio_group);
            if (checkedPos != -1)
                insuranceRadioGroup.check(checkedPos);
            LinearLayout okayButton = (LinearLayout) findViewById(R.id.driver_gender_okay_button);
            okayButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    switch (insuranceRadioGroup.getCheckedRadioButtonId()) {
                    case R.id.driver_gender_male:
                        editDriver.setGender(true);
                        genderValue.setText(getString(R.string.male_option));
                        break;
                    case R.id.driver_gender_female:
                        editDriver.setGender(false);
                        genderValue.setText(getString(R.string.female_option));
                        break;
                    default:
                        break;
                    }
                    mainScrollView.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mainScrollView.smoothScrollTo(0, 0);
                        }
                    }, 500);
                    appBarLayout.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            appBarLayout.setExpanded(true, true);
                        }
                    }, 1500);
                }
            });
            LinearLayout cancelButton = (LinearLayout) findViewById(R.id.driver_gender_cancel_button);
            cancelButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    genderSelector.setVisibility(View.GONE);
                }
            });
        }
    });

    //TODO image analyis on IDs (license) and cross check with profile photo1, or maybe selfie

    uploadCount = new AtomicInteger(0);
    saveDriverAction = (FloatingActionButton) findViewById(R.id.fab_save_id);
    saveDriverAction.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            boolean error = false;
            hideKeyboard(context);
            if (editDriver.getVehicles().size() == 1) {
                setIndicator(context, vehicleIndicator, false);
                error = true;
            }
            if (licenseImage.getDrawable() == null || editDriver.getLicenseExpiry() == null
                    || editDriver.getLicenseNumber() == null) {
                setIndicator(context, licenseIndicator, false);
                error = true;
            }
            if (residenceImage.getDrawable() == null || editDriver.getResidenceNumber() == null) {
                setIndicator(context, residenceIndicator, false);
                error = true;
            }
            if (editDriver.getNationality() == null) {
                setIndicator(context, nationalityIndicator, false);
                error = true;
            }
            if (editDriver.getPreferredAddress() == null) {
                setIndicator(context, addressIndicator, false);
                error = true;
            }
            if (editDriver.getPhoneNumber() == null || editDriver.getPhoneNumber().isEmpty()) {
                setIndicator(context, phoneIndicator, false);
                error = true;
            }
            if (user == null && !registerEmailHeaderFragment.setCustomerValues())
                error = true;
            if (error)
                Snackbar.make(view, getString(R.string.incorrect_driver_data_message), Snackbar.LENGTH_LONG)
                        .show();
            else if (user != null) {
                signUpAnalytics(user.getProviderId());
                editDriver.getVehicles().remove(editDriver.getVehicles().size() - 1);
                uploadImage("driver_license_snapshot",
                        "image_" + editDriver.getPhoneNumber().replace(currentCountry.getPhoneCode(), "") + "_"
                                + editDriver.getLicenseNumber() + ".jpg",
                        ((BitmapDrawable) licenseImage.getDrawable()).getBitmap(), REQUEST_DRIVER_LICENSE);
                uploadImage("driver_residence_snapshot",
                        "image_" + editDriver.getPhoneNumber().replace(currentCountry.getPhoneCode(), "") + "_"
                                + editDriver.getResidenceNumber() + ".jpg",
                        ((BitmapDrawable) residenceImage.getDrawable()).getBitmap(), REQUEST_RESIDENCE_ID);
                crossFade(context, findViewById(R.id.driver_progress_layout),
                        findViewById(R.id.driver_main_layout), null);
                //TODO verify registration details for duplicate, correctness, etc
            }
        }
    });

    imageUploadStatus = (TextSwitcher) findViewById(R.id.image_upload_status);
    imageUploadStatus.setFactory(new ViewSwitcher.ViewFactory() {
        @Override
        public View makeView() {
            TextView switcherTextView = new TextView(getApplicationContext());
            switcherTextView.setTextSize(16);
            switcherTextView.setTypeface(null, Typeface.BOLD);
            switcherTextView.setText(getString(R.string.uploading_images));
            switcherTextView.setTextColor(getResources().getColor(R.color.colorAccent));
            return switcherTextView;
        }
    });
    Animation animationOut = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
    Animation animationIn = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
    imageUploadStatus.setOutAnimation(animationOut);
    imageUploadStatus.setInAnimation(animationIn);
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetAdapter.java

@SuppressWarnings("deprecation")
@Override/*  w ww  .  j a  v a2  s  .  c o  m*/
public View getView(int position, View convertView, ViewGroup parent) {
    /* TODO: This definitely needs some huge refactoring */
    final RelativeLayout widgetView;
    TextView labelTextView;
    TextView valueTextView;
    int widgetLayout;
    String[] splitString;
    OpenHABWidget openHABWidget = getItem(position);
    int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
            .getDefaultDisplay().getWidth();
    switch (this.getItemViewType(position)) {
    case TYPE_FRAME:
        widgetLayout = R.layout.openhabwidgetlist_frameitem;
        break;
    case TYPE_GROUP:
        widgetLayout = R.layout.openhabwidgetlist_groupitem;
        break;
    case TYPE_SECTIONSWITCH:
        widgetLayout = R.layout.openhabwidgetlist_sectionswitchitem;
        break;
    case TYPE_SWITCH:
        widgetLayout = R.layout.openhabwidgetlist_switchitem;
        break;
    case TYPE_ROLLERSHUTTER:
        widgetLayout = R.layout.openhabwidgetlist_rollershutteritem;
        break;
    case TYPE_TEXT:
        widgetLayout = R.layout.openhabwidgetlist_textitem;
        break;
    case TYPE_SLIDER:
        widgetLayout = R.layout.openhabwidgetlist_slideritem;
        break;
    case TYPE_IMAGE:
        widgetLayout = R.layout.openhabwidgetlist_imageitem;
        break;
    case TYPE_SELECTION:
        widgetLayout = R.layout.openhabwidgetlist_selectionitem;
        break;
    case TYPE_SETPOINT:
        widgetLayout = R.layout.openhabwidgetlist_setpointitem;
        break;
    case TYPE_CHART:
        widgetLayout = R.layout.openhabwidgetlist_chartitem;
        break;
    case TYPE_VIDEO:
        widgetLayout = R.layout.openhabwidgetlist_videoitem;
        break;
    case TYPE_VIDEO_MJPEG:
        widgetLayout = R.layout.openhabwidgetlist_videomjpegitem;
        break;
    case TYPE_WEB:
        widgetLayout = R.layout.openhabwidgetlist_webitem;
        break;
    case TYPE_COLOR:
        widgetLayout = R.layout.openhabwidgetlist_coloritem;
        break;
    default:
        widgetLayout = R.layout.openhabwidgetlist_genericitem;
        break;
    }
    if (convertView == null) {
        widgetView = new RelativeLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater) getContext().getSystemService(inflater);
        vi.inflate(widgetLayout, widgetView, true);
    } else {
        widgetView = (RelativeLayout) convertView;
    }

    // Process the colour attributes
    Integer iconColor = openHABWidget.getIconColor();
    Integer labelColor = openHABWidget.getLabelColor();
    Integer valueColor = openHABWidget.getValueColor();

    // Process widgets icon image
    MySmartImageView widgetImage = (MySmartImageView) widgetView.findViewById(R.id.widgetimage);
    // Some of widgets, for example Frame doesnt' have an icon, so...
    if (widgetImage != null) {
        if (openHABWidget.getIcon() != null) {
            // This is needed to escape possible spaces and everything according to rfc2396
            String iconUrl = openHABBaseUrl + "images/" + Uri.encode(openHABWidget.getIcon() + ".png");
            //                Log.d(TAG, "Will try to load icon from " + iconUrl);
            // Now set image URL
            widgetImage.setImageUrl(iconUrl, R.drawable.blank_icon, openHABUsername, openHABPassword);
            if (iconColor != null)
                widgetImage.setColorFilter(iconColor);
            else
                widgetImage.clearColorFilter();
        }
    }
    TextView defaultTextView = new TextView(widgetView.getContext());
    // Get TextView for widget label and set it's color
    labelTextView = (TextView) widgetView.findViewById(R.id.widgetlabel);
    // Change label color only for non-frame widgets
    if (labelColor != null && labelTextView != null && this.getItemViewType(position) != TYPE_FRAME) {
        Log.d(TAG, String.format("Setting label color to %d", labelColor));
        labelTextView.setTextColor(labelColor);
    } else if (labelTextView != null && this.getItemViewType(position) != TYPE_FRAME)
        labelTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    // Get TextView for widget value and set it's color
    valueTextView = (TextView) widgetView.findViewById(R.id.widgetvalue);
    if (valueColor != null && valueTextView != null) {
        Log.d(TAG, String.format("Setting value color to %d", valueColor));
        valueTextView.setTextColor(valueColor);
    } else if (valueTextView != null)
        valueTextView.setTextColor(defaultTextView.getTextColors().getDefaultColor());
    defaultTextView = null;
    switch (getItemViewType(position)) {
    case TYPE_FRAME:
        if (labelTextView != null) {
            labelTextView.setText(openHABWidget.getLabel());
            if (valueColor != null)
                labelTextView.setTextColor(valueColor);
        }
        widgetView.setClickable(false);
        if (openHABWidget.getLabel().length() > 0) { // hide empty frames
            widgetView.setVisibility(View.VISIBLE);
            labelTextView.setVisibility(View.VISIBLE);
        } else {
            widgetView.setVisibility(View.GONE);
            labelTextView.setVisibility(View.GONE);
        }
        break;
    case TYPE_GROUP:
        if (labelTextView != null && valueTextView != null) {
            splitString = openHABWidget.getLabel().split("\\[|\\]");
            labelTextView.setText(splitString[0]);
            if (splitString.length > 1) { // We have some value
                valueTextView.setText(splitString[1]);
            } else {
                // This is needed to clean up cached TextViews
                valueTextView.setText("");
            }
        }
        break;
    case TYPE_SECTIONSWITCH:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (splitString.length > 1 && valueTextView != null) { // We have some value
            valueTextView.setText(splitString[1]);
        } else {
            // This is needed to clean up cached TextViews
            valueTextView.setText("");
        }
        RadioGroup sectionSwitchRadioGroup = (RadioGroup) widgetView.findViewById(R.id.sectionswitchradiogroup);
        // As we create buttons in this radio in runtime, we need to remove all
        // exiting buttons first
        sectionSwitchRadioGroup.removeAllViews();
        sectionSwitchRadioGroup.setTag(openHABWidget);
        Iterator<OpenHABWidgetMapping> sectionMappingIterator = openHABWidget.getMappings().iterator();
        while (sectionMappingIterator.hasNext()) {
            OpenHABWidgetMapping widgetMapping = sectionMappingIterator.next();
            SegmentedControlButton segmentedControlButton = (SegmentedControlButton) LayoutInflater
                    .from(sectionSwitchRadioGroup.getContext())
                    .inflate(R.layout.openhabwidgetlist_sectionswitchitem_button, sectionSwitchRadioGroup,
                            false);
            segmentedControlButton.setText(widgetMapping.getLabel());
            segmentedControlButton.setTag(widgetMapping.getCommand());
            if (openHABWidget.getItem() != null && widgetMapping.getCommand() != null) {
                if (widgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    segmentedControlButton.setChecked(true);
                } else {
                    segmentedControlButton.setChecked(false);
                }
            } else {
                segmentedControlButton.setChecked(false);
            }
            segmentedControlButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    Log.i(TAG, "Button clicked");
                    RadioGroup group = (RadioGroup) view.getParent();
                    if (group.getTag() != null) {
                        OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                        SegmentedControlButton selectedButton = (SegmentedControlButton) view;
                        if (selectedButton.getTag() != null) {
                            sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                        }
                    }
                }
            });
            sectionSwitchRadioGroup.addView(segmentedControlButton);
        }

        sectionSwitchRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                OpenHABWidget radioWidget = (OpenHABWidget) group.getTag();
                SegmentedControlButton selectedButton = (SegmentedControlButton) group.findViewById(checkedId);
                if (selectedButton != null) {
                    Log.d(TAG, "Selected " + selectedButton.getText());
                    Log.d(TAG, "Command = " + (String) selectedButton.getTag());
                    //                  radioWidget.getItem().sendCommand((String)selectedButton.getTag());
                    sendItemCommand(radioWidget.getItem(), (String) selectedButton.getTag());
                }
            }
        });
        break;
    case TYPE_SWITCH:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        SwitchCompat switchSwitch = (SwitchCompat) widgetView.findViewById(R.id.switchswitch);
        if (openHABWidget.hasItem()) {
            if (openHABWidget.getItem().getStateAsBoolean()) {
                switchSwitch.setChecked(true);
            } else {
                switchSwitch.setChecked(false);
            }
        }
        switchSwitch.setTag(openHABWidget.getItem());
        switchSwitch.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                SwitchCompat switchSwitch = (SwitchCompat) v;
                OpenHABItem linkedItem = (OpenHABItem) switchSwitch.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    if (!switchSwitch.isChecked()) {
                        sendItemCommand(linkedItem, "ON");
                    } else {
                        sendItemCommand(linkedItem, "OFF");
                    }
                return false;
            }
        });
        break;
    case TYPE_COLOR:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton colorUpButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_up);
        ImageButton colorDownButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_down);
        ImageButton colorColorButton = (ImageButton) widgetView.findViewById(R.id.colorbutton_color);
        colorUpButton.setTag(openHABWidget.getItem());
        colorDownButton.setTag(openHABWidget.getItem());
        colorColorButton.setTag(openHABWidget.getItem());
        colorUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "ON");
                return false;
            }
        });
        colorDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(colorItem, "OFF");
                return false;
            }
        });
        colorColorButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton colorButton = (ImageButton) v;
                OpenHABItem colorItem = (OpenHABItem) colorButton.getTag();
                if (colorItem != null) {
                    if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP) {
                        Log.d(TAG, "Time to launch color picker!");
                        ColorPickerDialog colorDialog = new ColorPickerDialog(widgetView.getContext(),
                                new OnColorChangedListener() {
                                    public void colorChanged(float[] hsv, View v) {
                                        Log.d(TAG, "New color HSV = " + hsv[0] + ", " + hsv[1] + ", " + hsv[2]);
                                        String newColor = String.valueOf(hsv[0]) + ","
                                                + String.valueOf(hsv[1] * 100) + ","
                                                + String.valueOf(hsv[2] * 100);
                                        OpenHABItem colorItem = (OpenHABItem) v.getTag();
                                        sendItemCommand(colorItem, newColor);
                                    }
                                }, colorItem.getStateAsHSV());
                        colorDialog.setTag(colorItem);
                        colorDialog.show();
                    }
                }
                return false;
            }
        });
        break;
    case TYPE_ROLLERSHUTTER:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        ImageButton rollershutterUpButton = (ImageButton) widgetView.findViewById(R.id.rollershutterbutton_up);
        ImageButton rollershutterStopButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_stop);
        ImageButton rollershutterDownButton = (ImageButton) widgetView
                .findViewById(R.id.rollershutterbutton_down);
        rollershutterUpButton.setTag(openHABWidget.getItem());
        rollershutterStopButton.setTag(openHABWidget.getItem());
        rollershutterDownButton.setTag(openHABWidget.getItem());
        rollershutterUpButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "UP");
                return false;
            }
        });
        rollershutterStopButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "STOP");
                return false;
            }
        });
        rollershutterDownButton.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent motionEvent) {
                ImageButton rollershutterButton = (ImageButton) v;
                OpenHABItem rollershutterItem = (OpenHABItem) rollershutterButton.getTag();
                if (motionEvent.getActionMasked() == MotionEvent.ACTION_UP)
                    sendItemCommand(rollershutterItem, "DOWN");
                return false;
            }
        });
        break;
    case TYPE_TEXT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            if (splitString.length > 0) {
                labelTextView.setText(splitString[0]);
            } else {
                labelTextView.setText(openHABWidget.getLabel());
            }
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            } else {
                // If value is empty, hide TextView to fix vertical alignment of label
                valueTextView.setVisibility(View.GONE);
                valueTextView.setText("");
            }
        break;
    case TYPE_SLIDER:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        SeekBar sliderSeekBar = (SeekBar) widgetView.findViewById(R.id.sliderseekbar);
        if (openHABWidget.hasItem()) {
            sliderSeekBar.setTag(openHABWidget.getItem());
            sliderSeekBar.setProgress(openHABWidget.getItem().getStateAsFloat().intValue());
            sliderSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                }

                public void onStartTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStartTrackingTouch position = " + seekBar.getProgress());
                }

                public void onStopTrackingTouch(SeekBar seekBar) {
                    Log.d(TAG, "onStopTrackingTouch position = " + seekBar.getProgress());
                    OpenHABItem sliderItem = (OpenHABItem) seekBar.getTag();
                    //                     sliderItem.sendCommand(String.valueOf(seekBar.getProgress()));
                    if (sliderItem != null && seekBar != null)
                        sendItemCommand(sliderItem, String.valueOf(seekBar.getProgress()));
                }
            });
            if (volumeUpWidget == null) {
                volumeUpWidget = sliderSeekBar;
                volumeDownWidget = sliderSeekBar;
            }
        }
        break;
    case TYPE_IMAGE:
        MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage);
        imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false,
                openHABUsername, openHABPassword);
        //          ViewGroup.LayoutParams imageLayoutParams = imageImage.getLayoutParams();
        //          float imageRatio = imageImage.getDrawable().getIntrinsicWidth()/imageImage.getDrawable().getIntrinsicHeight();
        //          imageLayoutParams.height = (int) (screenWidth/imageRatio);
        //          imageImage.setLayoutParams(imageLayoutParams);
        if (openHABWidget.getRefresh() > 0) {
            imageImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(imageImage);
        }
        break;
    case TYPE_CHART:
        MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage);
        //Always clear the drawable so no images from recycled views appear
        chartImage.setImageDrawable(null);
        OpenHABItem chartItem = openHABWidget.getItem();
        Random random = new Random();
        String chartUrl = "";
        if (chartItem != null) {
            if (chartItem.getType().equals("GroupItem")) {
                chartUrl = openHABBaseUrl + "chart?groups=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            } else {
                chartUrl = openHABBaseUrl + "chart?items=" + chartItem.getName() + "&period="
                        + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
            }
            if (openHABWidget.getService() != null && openHABWidget.getService().length() > 0) {
                chartUrl += "&service=" + openHABWidget.getService();
            }
        }
        Log.d(TAG, "Chart url = " + chartUrl);
        if (chartImage == null)
            Log.e(TAG, "chartImage == null !!!");
        ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams();
        chartLayoutParams.height = (int) (screenWidth / 2);
        chartImage.setLayoutParams(chartLayoutParams);
        chartUrl += "&w=" + String.valueOf(screenWidth);
        chartUrl += "&h=" + String.valueOf(screenWidth / 2);
        chartImage.setImageUrl(chartUrl, false, openHABUsername, openHABPassword);
        // TODO: This is quite dirty fix to make charts look full screen width on all displays
        if (openHABWidget.getRefresh() > 0) {
            chartImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(chartImage);
        }
        Log.d(TAG, "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height);
        break;
    case TYPE_VIDEO:
        VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo);
        Log.d(TAG, "Opening video at " + openHABWidget.getUrl());
        // TODO: This is quite dirty fix to make video look maximum available size on all screens
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams();
        videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77);
        videoVideo.setLayoutParams(videoLayoutParams);
        // We don't have any event handler to know if the VideoView is on the screen
        // so we manage an array of all videos to stop them when user leaves the page
        if (!videoWidgetList.contains(videoVideo))
            videoWidgetList.add(videoVideo);
        // Start video
        if (!videoVideo.isPlaying()) {
            videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl()));
            videoVideo.start();
        }
        Log.d(TAG, "Video height is " + videoVideo.getHeight());
        break;
    case TYPE_VIDEO_MJPEG:
        Log.d(TAG, "Video is mjpeg");
        ImageView mjpegImage = (ImageView) widgetView.findViewById(R.id.mjpegimage);
        MjpegStreamer mjpegStreamer = new MjpegStreamer(openHABWidget.getUrl(), this.openHABUsername,
                this.openHABPassword, this.getContext());
        mjpegStreamer.setTargetImageView(mjpegImage);
        mjpegStreamer.start();
        if (!mjpegWidgetList.contains(mjpegStreamer))
            mjpegWidgetList.add(mjpegStreamer);
        break;
    case TYPE_WEB:
        WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb);
        if (openHABWidget.getHeight() > 0) {
            ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams();
            webLayoutParams.height = openHABWidget.getHeight() * 80;
            webWeb.setLayoutParams(webLayoutParams);
        }
        webWeb.setWebViewClient(
                new AnchorWebViewClient(openHABWidget.getUrl(), this.openHABUsername, this.openHABPassword));
        webWeb.getSettings().setJavaScriptEnabled(true);
        webWeb.loadUrl(openHABWidget.getUrl());
        break;
    case TYPE_SELECTION:
        int spinnerSelectedIndex = -1;
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        final Spinner selectionSpinner = (Spinner) widgetView.findViewById(R.id.selectionspinner);
        selectionSpinner.setOnItemSelectedListener(null);
        ArrayList<String> spinnerArray = new ArrayList<String>();
        Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings().iterator();
        while (mappingIterator.hasNext()) {
            OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
            spinnerArray.add(openHABWidgetMapping.getLabel());
            if (openHABWidgetMapping.getCommand() != null && openHABWidget.getItem() != null)
                if (openHABWidgetMapping.getCommand().equals(openHABWidget.getItem().getState())) {
                    spinnerSelectedIndex = spinnerArray.size() - 1;
                }
        }
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this.getContext(),
                android.R.layout.simple_spinner_item, spinnerArray);
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        selectionSpinner.setAdapter(spinnerAdapter);
        selectionSpinner.setTag(openHABWidget);
        if (spinnerSelectedIndex >= 0) {
            Log.d(TAG, "Setting spinner selected index to " + String.valueOf(spinnerSelectedIndex));
            selectionSpinner.setSelection(spinnerSelectedIndex);
        } else {
            Log.d(TAG, "Not setting spinner selected index");
        }
        selectionSpinner.post(new Runnable() {
            @Override
            public void run() {
                selectionSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                    public void onItemSelected(AdapterView<?> parent, View view, int index, long id) {
                        Log.d(TAG, "Spinner item click on index " + index);
                        Spinner spinner = (Spinner) parent;
                        String selectedLabel = (String) spinner.getAdapter().getItem(index);
                        Log.d(TAG, "Spinner onItemSelected selected label = " + selectedLabel);
                        OpenHABWidget openHABWidget = (OpenHABWidget) parent.getTag();
                        if (openHABWidget != null) {
                            Log.d(TAG, "Label selected = " + openHABWidget.getMapping(index).getLabel());
                            Iterator<OpenHABWidgetMapping> mappingIterator = openHABWidget.getMappings()
                                    .iterator();
                            while (mappingIterator.hasNext()) {
                                OpenHABWidgetMapping openHABWidgetMapping = mappingIterator.next();
                                if (openHABWidgetMapping.getLabel().equals(selectedLabel)) {
                                    Log.d(TAG, "Spinner onItemSelected found match with "
                                            + openHABWidgetMapping.getCommand());
                                    if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() != null) {
                                        // Only send the command for selection of selected command will change the state
                                        if (!openHABWidget.getItem().getState()
                                                .equals(openHABWidgetMapping.getCommand())) {
                                            Log.d(TAG,
                                                    "Spinner onItemSelected selected label command != current item state");
                                            sendItemCommand(openHABWidget.getItem(),
                                                    openHABWidgetMapping.getCommand());
                                        }
                                    } else if (openHABWidget.getItem() != null
                                            && openHABWidget.getItem().getState() == null) {
                                        Log.d(TAG,
                                                "Spinner onItemSelected selected label command and state == null");
                                        sendItemCommand(openHABWidget.getItem(),
                                                openHABWidgetMapping.getCommand());
                                    }
                                }
                            }
                        }
                        //               if (!openHABWidget.getItem().getState().equals(openHABWidget.getMapping(index).getCommand()))
                        //                  sendItemCommand(openHABWidget.getItem(),
                        //                        openHABWidget.getMapping(index).getCommand());
                    }

                    public void onNothingSelected(AdapterView<?> arg0) {
                    }
                });
            }
        });
        break;
    case TYPE_SETPOINT:
        splitString = openHABWidget.getLabel().split("\\[|\\]");
        if (labelTextView != null)
            labelTextView.setText(splitString[0]);
        if (valueTextView != null)
            if (splitString.length > 1) {
                // If value is not empty, show TextView
                valueTextView.setVisibility(View.VISIBLE);
                valueTextView.setText(splitString[1]);
            }
        Button setPointMinusButton = (Button) widgetView.findViewById(R.id.setpointbutton_minus);
        Button setPointPlusButton = (Button) widgetView.findViewById(R.id.setpointbutton_plus);
        setPointMinusButton.setTag(openHABWidget);
        setPointPlusButton.setTag(openHABWidget);
        setPointMinusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Minus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue - setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));

            }
        });
        setPointPlusButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "Plus");
                OpenHABWidget setPointWidget = (OpenHABWidget) v.getTag();
                float currentValue = setPointWidget.getItem().getStateAsFloat();
                currentValue = currentValue + setPointWidget.getStep();
                if (currentValue < setPointWidget.getMinValue())
                    currentValue = setPointWidget.getMinValue();
                if (currentValue > setPointWidget.getMaxValue())
                    currentValue = setPointWidget.getMaxValue();
                sendItemCommand(setPointWidget.getItem(), String.valueOf(currentValue));
            }
        });
        if (volumeUpWidget == null) {
            volumeUpWidget = setPointPlusButton;
            volumeDownWidget = setPointMinusButton;
        }
        break;
    default:
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        break;
    }
    LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider);
    if (dividerLayout != null) {
        if (position < this.getCount() - 1) {
            if (this.getItemViewType(position + 1) == TYPE_FRAME) {
                dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets
            } else {
                dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others
            }
        } else { // last widget in the list, hide divider
            dividerLayout.setVisibility(View.GONE);
        }
    }
    return widgetView;
}

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

private void uploadAudioToServer(String file, final Message menssage, final JSONObject dataSend,
        final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText) {
    try {/*  w w w  .  java2s . co m*/
        RequestParams p = new RequestParams();
        File archivo = new File(file);
        p.put("audio", archivo);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressText.setText("0%");
            }
        });

        SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/audio", p,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            final JSONObject dataResponse = response.getJSONObject("data_response");
                            Log.e("Respuesta", dataResponse.toString());
                            JSONArray photoArray = new JSONArray();
                            photoArray.put(0, dataResponse.getString("file_name"));
                            dataSend.put("audios", photoArray);
                            menssage.fileName = photoArray.toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                menssage.status = 1;
                                SpeakSocket.mSocket.emit("message", dataSend);
                            } else {
                                menssage.status = -1;
                            }
                        menssage.fileUploaded = true;
                        menssage.save();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                progressLayout.setVisibility(View.GONE);
                                System.gc();
                            }
                        });
                    }

                    @Override
                    public void onProgress(final long bytesWritten, final long totalSize) {
                        if (bytesWritten != totalSize) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                    progressBar.setProgress((int) Math.round(prog));
                                    progressText.setText((int) Math.round(prog) + "%");
                                    Log.e("PROGRESO", (int) Math.round(prog) + "");
                                }
                            });
                        }
                    }

                    @Override
                    public void onFinish() {
                        System.gc();
                    }
                }, activity);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:android.melbournehistorymap.MapsActivity.java

/**
 * Manipulates the map once available./* w  w w . ja  va2s. c  o  m*/
 * This callback is triggered when the map is ready to be used.
 * This is where we can add markers or lines, add listeners or move the camera. In this case,
 * we just add a marker near Sydney, Australia.
 * If Google Play services is not installed on the device, the user will be prompted to install
 * it inside the SupportMapFragment. This method will only be triggered once the user has
 * installed Google Play services and returned to the app.
 */
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    spinner = (ProgressBar) findViewById(R.id.prograssSpinner);
    //check if permission has been granted
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // Permission has already been granted
        return;
    }
    mMap.setMyLocationEnabled(true);
    mMap.getUiSettings().setZoomControlsEnabled(false);

    double lat;
    double lng;
    final int radius;
    int zoom;

    lat = Double.parseDouble(CurrLat);
    lng = Double.parseDouble(CurrLong);

    //build current location
    LatLng currentLocation = new LatLng(lat, lng);
    final LatLng realLocation = currentLocation;

    if (MELBOURNE.contains(currentLocation)) {
        mMap.getUiSettings().setMyLocationButtonEnabled(true);
        zoom = 17;
    } else {
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        lat = -37.81161508043379;
        lng = 144.9647320434451;
        zoom = 15;
        currentLocation = new LatLng(lat, lng);
    }

    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLocation, 13));

    CameraPosition cameraPosition = new CameraPosition.Builder().target(currentLocation) // Sets the center of the map to location user
            .zoom(zoom) // Sets the zoom
            .bearing(0) // Sets the orientation of the camera to east
            .tilt(25) // Sets the tilt of the camera to 30 degrees
            .build(); // Creates a CameraPosition from the builder

    //Animate user to map location, if in Melbourne or outside of Melbourne bounds
    mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition),
            new GoogleMap.CancelableCallback() {
                @Override
                public void onFinish() {
                    updateMap();
                }

                @Override
                public void onCancel() {

                }
            });

    final TextView placeTitle = (TextView) findViewById(R.id.placeTitle);
    final TextView placeVic = (TextView) findViewById(R.id.placeVic);
    final TextView expPlaceTitle = (TextView) findViewById(R.id.expPlaceTitle);
    final TextView expPlaceVic = (TextView) findViewById(R.id.expPlaceVic);
    final TextView expPlaceDescription = (TextView) findViewById(R.id.placeDescription);
    final TextView wikiLicense = (TextView) findViewById(R.id.wikiLicense);
    final TextView expPlaceDistance = (TextView) findViewById(R.id.expPlaceDistance);
    final RelativeLayout tile = (RelativeLayout) findViewById(R.id.tile);
    final TextView fab = (TextView) findViewById(R.id.fab);
    final RelativeLayout distanceCont = (RelativeLayout) findViewById(R.id.distanceContainer);

    //        String license = "Text is available under the <a rel=\"license\" href=\"//en.wikipedia.org/wiki/Wikipedia:Text_of_Creative_Commons_Attribution-ShareAlike_3.0_Unported_License\">Creative Commons Attribution-ShareAlike License</a><a rel=\"license\" href=\"//creativecommons.org/licenses/by-sa/3.0/\" style=\"display:none;\"></a>;\n" +
    //                "additional terms may apply.";
    //        wikiLicense.setText(Html.fromHtml(license));
    //        wikiLicense.setMovementMethod(LinkMovementMethod.getInstance());
    //Marker click
    mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {

        @Override
        public boolean onMarkerClick(Marker marker) {
            String title = marker.getTitle();
            mMap.setPadding(0, 0, 0, 620);
            //set clicked marker to full opacity
            marker.setAlpha(1f);
            //set previous marker back to partial opac (if there is a prevMarker
            if (dirtyMarker == 1) {
                prevMarker.setAlpha(0.6f);
            }
            prevMarker = marker;
            dirtyMarker = 1;

            //Set DB helper
            DBHelper myDBHelper = new DBHelper(MapsActivity.this, WikiAPI.DB_NAME, null, WikiAPI.VERSION);

            //Only search for Wiki API requests if no place article returned.
            // **
            //Open DB as readable only.
            SQLiteDatabase db = myDBHelper.getReadableDatabase();
            //Set the query
            String dbFriendlyName = title.replace("\'", "\'\'");
            //Limit by 1 rows
            Cursor cursor = db.query(DBHelper.TABLE_NAME, null, "PLACE_NAME = '" + dbFriendlyName + "'", null,
                    null, null, null, "1");

            //move through each row returned in the query results
            while (cursor.moveToNext()) {

                String place_ID = cursor.getString(cursor.getColumnIndex("PLACE_ID"));
                String placeName = cursor.getString(cursor.getColumnIndex("PLACE_NAME"));
                String placeLoc = cursor.getString(cursor.getColumnIndex("PLACE_LOCATION"));
                String placeArticle = cursor.getString(cursor.getColumnIndex("ARTICLE"));
                String placeLat = cursor.getString(cursor.getColumnIndex("LAT"));
                String placeLng = cursor.getString(cursor.getColumnIndex("LNG"));

                //Get Google Place photos
                //Source: https://developers.google.com/places/android-api/photos
                final String placeId = place_ID;
                Places.GeoDataApi.getPlacePhotos(mGoogleApiClient, placeId)
                        .setResultCallback(new ResultCallback<PlacePhotoMetadataResult>() {
                            @Override
                            public void onResult(PlacePhotoMetadataResult photos) {
                                if (!photos.getStatus().isSuccess()) {
                                    return;
                                }
                                ImageView mImageView = (ImageView) findViewById(R.id.imageView);
                                ImageView mImageViewExpanded = (ImageView) findViewById(R.id.headerImage);
                                TextView txtAttribute = (TextView) findViewById(R.id.photoAttribute);
                                TextView expTxtAttribute = (TextView) findViewById(R.id.expPhotoAttribute);
                                PlacePhotoMetadataBuffer photoMetadataBuffer = photos.getPhotoMetadata();
                                if (photoMetadataBuffer.getCount() > 0) {
                                    // Display the first bitmap in an ImageView in the size of the view
                                    photoMetadataBuffer.get(0).getScaledPhoto(mGoogleApiClient, 600, 200)
                                            .setResultCallback(mDisplayPhotoResultCallback);
                                    //get photo attributions
                                    PlacePhotoMetadata photo = photoMetadataBuffer.get(0);
                                    CharSequence attribution = photo.getAttributions();
                                    if (attribution != null) {
                                        txtAttribute.setText(Html.fromHtml(String.valueOf(attribution)));
                                        expTxtAttribute.setText(Html.fromHtml(String.valueOf(attribution)));
                                        //http://stackoverflow.com/questions/4303160/how-can-i-make-links-in-fromhtml-clickable-android
                                        txtAttribute.setMovementMethod(LinkMovementMethod.getInstance());
                                        expTxtAttribute.setMovementMethod(LinkMovementMethod.getInstance());
                                    } else {
                                        txtAttribute.setText(" ");
                                        expTxtAttribute.setText(" ");
                                    }
                                } else {
                                    //Reset image view as no photo was identified
                                    mImageView.setImageResource(android.R.color.transparent);
                                    mImageViewExpanded.setImageResource(android.R.color.transparent);
                                    txtAttribute.setText(R.string.no_photos);
                                    expTxtAttribute.setText(R.string.no_photos);
                                }
                                photoMetadataBuffer.release();
                            }
                        });

                LatLng destLocation = new LatLng(Double.parseDouble(placeLat), Double.parseDouble(placeLng));
                //Work out distance between current location and place location
                //Source Library: https://github.com/googlemaps/android-maps-utils
                double distance = SphericalUtil.computeDistanceBetween(realLocation, destLocation);
                distance = Math.round(distance);
                distance = distance * 0.001;
                String strDistance = String.valueOf(distance);
                String[] arrDistance = strDistance.split("\\.");
                String unit = "km";
                if (arrDistance[0] == "0") {
                    unit = "m";
                    strDistance = arrDistance[1];
                } else {
                    strDistance = arrDistance[0] + "." + arrDistance[1].substring(0, 1);
                }

                placeArticle = placeArticle
                        .replaceAll("(<div class=\"thumb t).*\\s.*\\s.*\\s.*\\s.*\\s<\\/div>\\s<\\/div>", " ");

                Spannable noUnderlineMessage = new SpannableString(Html.fromHtml(placeArticle));

                //http://stackoverflow.com/questions/4096851/remove-underline-from-links-in-textview-android
                for (URLSpan u : noUnderlineMessage.getSpans(0, noUnderlineMessage.length(), URLSpan.class)) {
                    noUnderlineMessage.setSpan(new UnderlineSpan() {
                        public void updateDrawState(TextPaint tp) {
                            tp.setUnderlineText(false);
                        }
                    }, noUnderlineMessage.getSpanStart(u), noUnderlineMessage.getSpanEnd(u), 0);
                }

                placeArticle = String.valueOf(noUnderlineMessage);
                placeArticle = placeArticle.replaceAll("(\\[\\d\\])", " ");

                placeTitle.setText(placeName);
                expPlaceTitle.setText(placeName);
                placeVic.setText(placeLoc);
                expPlaceVic.setText(placeLoc);
                expPlaceDescription.setText(placeArticle);
                if (MELBOURNE.contains(realLocation)) {
                    expPlaceDistance.setText("Distance: " + strDistance + unit);
                    distanceCont.setVisibility(View.VISIBLE);
                }
            }

            tile.setVisibility(View.VISIBLE);
            fab.setVisibility(View.VISIBLE);
            //Set to true to not show default behaviour.
            return false;
        }
    });

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            int viewStatus = tile.getVisibility();
            if (viewStatus == View.VISIBLE) {
                tile.setVisibility(View.INVISIBLE);
                fab.setVisibility(View.INVISIBLE);
                //set previous marker back to partial opac (if there is a prevMarker
                if (dirtyMarker == 1) {
                    prevMarker.setAlpha(0.6f);
                }
            }

            mMap.setPadding(0, 0, 0, 0);
        }
    });

    FloatingActionButton shareIcon = (FloatingActionButton) findViewById(R.id.shareIcon);
    shareIcon.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //https://www.google.com.au/maps/place/Federation+Square/@-37.8179789,144.9668635,15z

            //Build implicit intent by triggering a SENDTO action, which will capture applications that allow for messages
            //that allow for messages to be sent to a specific user with data
            //http://developer.android.com/reference/android/content/Intent.html#ACTION_SENDTO
            Intent intent = new Intent(Intent.ACTION_SEND);
            intent.setType("text/plain");
            //Build SMS
            String encodedPlace = "empty";
            try {
                encodedPlace = URLEncoder.encode(String.valueOf(expPlaceTitle.getText()), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(expPlaceTitle.getText())
                    + " \n\nhttps://www.google.com.au/maps/place/" + encodedPlace);
            Intent sms = Intent.createChooser(intent, null);
            startActivity(sms);
        }
    });

    TextView fullArticle = (TextView) findViewById(R.id.fullArticle);
    fullArticle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String wikiPlace = WikiPlace.getName(String.valueOf(expPlaceTitle.getText()));
            String url = "https://en.wikipedia.org/wiki/" + wikiPlace;

            Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            startActivity(browserIntent);
        }
    });
}

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

private void uploadPhotoToServer(String file, final Message menssage, final JSONObject dataSend,
        final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
        final ImageView messageContent) {
    try {/*  w  w w.  j  a v a  2s  .  c o m*/
        RequestParams p = new RequestParams();
        final File archivo = new File(file);
        p.put("image", archivo);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setIndeterminate(false);
                progressText.setText("0%");
            }
        });
        SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/photo", p,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            JSONObject jsonObject = response.getJSONObject("data_response");
                            JSONArray photoArray = new JSONArray();
                            photoArray.put(0, jsonObject.getString("file_name"));
                            dataSend.put("photos", photoArray);
                            menssage.fileName = photoArray.toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                menssage.status = 1;
                                SpeakSocket.mSocket.emit("message", dataSend);
                            } else {
                                menssage.status = -1;
                            }
                        menssage.fileUploaded = true;
                        menssage.save();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (menssage.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0,
                                            menssage.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    progressLayout.setVisibility(View.GONE);
                                    System.gc();
                                }
                            }
                        });
                    }

                    @Override
                    public void onProgress(final long bytesWritten, final long totalSize) {
                        if (bytesWritten != totalSize) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                    progressBar.setProgress((int) Math.round(prog));
                                    progressText.setText((int) Math.round(prog) + "%");
                                    Log.e("PROGRESO", (int) Math.round(prog) + "");
                                }
                            });
                        }
                    }

                    @Override
                    public void onFinish() {
                        System.gc();
                    }
                }, activity);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

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

private void uploadVideoToServer(String file, final Message menssage, final JSONObject dataSend,
        final ProgressBar progressBar, final RelativeLayout progressLayout, final TextView progressText,
        final ImageView messageContent) {

    try {//from  w  ww .j a v  a 2  s .  c o m
        RequestParams p = new RequestParams();
        final File archivo = new File(file);
        p.put("video", archivo);
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                progressBar.setIndeterminate(false);
                progressText.setText("0%");
            }
        });

        SpeakHttp.client.setTimeout(70000);
        SpeakHttp.client.setResponseTimeout(70000);
        SpeakHttp.post("messages/" + SessionCustom.getUserId(activity) + "/upload/video", p,
                new JsonHttpResponseHandler() {
                    @Override
                    public void onSuccess(int statusCode, Header[] headers, final JSONObject response) {
                        super.onSuccess(statusCode, headers, response);
                        try {
                            JSONObject jsonObject = response.getJSONObject("data_response");
                            JSONArray photoArray = new JSONArray();
                            photoArray.put(0, jsonObject.getString("file_name"));
                            dataSend.put("videos", photoArray);
                            menssage.fileName = photoArray.toString();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (SpeakSocket.mSocket != null)
                            if (SpeakSocket.mSocket.connected()) {
                                menssage.status = 1;
                                SpeakSocket.mSocket.emit("message", dataSend);
                            } else {
                                menssage.status = -1;
                            }
                        menssage.fileUploaded = true;
                        menssage.save();
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (menssage.photo != null) {
                                    Bitmap bmp = BitmapFactory.decodeByteArray(menssage.photo, 0,
                                            menssage.photo.length);
                                    messageContent.setImageBitmap(bmp);
                                    progressLayout.setVisibility(View.GONE);
                                    System.gc();
                                }
                            }
                        });

                    }

                    @Override
                    public void onProgress(final long bytesWritten, final long totalSize) {
                        if (bytesWritten != totalSize) {
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    double prog = (100 / (double) totalSize) * (double) bytesWritten;
                                    progressBar.setProgress((int) Math.round(prog));
                                    progressText.setText((int) Math.round(prog) + "%");
                                    Log.e("PROGRESO", (int) Math.round(prog) + "");
                                }
                            });
                        }
                    }

                    @Override
                    public void onFinish() {
                        System.gc();
                    }
                }, activity);

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}