Example usage for android.widget TextView setHint

List of usage examples for android.widget TextView setHint

Introduction

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

Prototype

@android.view.RemotableViewMethod
public final void setHint(@StringRes int resid) 

Source Link

Document

Sets the text to be displayed when the text of the TextView is empty, from a resource.

Usage

From source file:fm.smart.r1.CreateExampleActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ExceptionHandler.register(this);
    setContentView(R.layout.create_example);
    final Intent queryIntent = getIntent();
    Bundle extras = queryIntent.getExtras();
    item_id = (String) extras.get("item_id");
    goal_id = (String) extras.get("goal_id");
    if (goal_id == null || goal_id.equals("")) {
        goal_id = Main.default_study_goal_id;
    }/*ww w.  ja  va  2s  . c om*/

    cue = (String) extras.get("cue");
    example = (String) extras.get("example");
    translation = (String) extras.get("translation");
    example_language = (String) extras.get("example_language");
    translation_language = (String) extras.get("translation_language");
    example_transliteration = (String) extras.get("example_transliteration");
    translation_transliteration = (String) extras.get("translation_transliteration");

    TextView example_text = (TextView) findViewById(R.id.create_example_sentence);
    if (!TextUtils.isEmpty(example)) {
        example_text.setText(example);
    }
    example_text.setHint(example_language + " sentence with " + cue);
    TextView translation_text = (TextView) findViewById(R.id.create_example_translation);
    if (!TextUtils.isEmpty(translation)) {
        translation_text.setText(translation);
    }
    translation_text.setHint(translation_language + " translation of example sentence");

    Button button = (Button) findViewById(R.id.create_example_submit);
    button.setOnClickListener(this);

    TextView translation_text_legend = (TextView) findViewById(R.id.create_example_translation_legend);

    TextView sentence_transliteration_textView = (TextView) findViewById(
            R.id.create_example_sentence_transliteration);
    EditText sentence_transliteration_input_textView = (EditText) findViewById(R.id.sentence_transliteration);
    if (!Utils.isIdeographicLanguage(Main.search_lang)) {
        sentence_transliteration_textView.setVisibility(View.GONE);
        sentence_transliteration_input_textView.setVisibility(View.GONE);
    } else if (!TextUtils.isEmpty(example_transliteration)) {
        sentence_transliteration_input_textView.setText(example_transliteration);
    }

    TextView translation_transliteration_textView = (TextView) findViewById(
            R.id.create_example_translation_transliteration);
    EditText translation_transliteration_input_textView = (EditText) findViewById(
            R.id.translation_transliteration);
    if (!Utils.isIdeographicLanguage(Main.result_lang)) {
        translation_transliteration_textView.setVisibility(View.GONE);
        translation_transliteration_input_textView.setVisibility(View.GONE);
    } else if (!TextUtils.isEmpty(translation_transliteration)) {
        translation_transliteration_input_textView.setText(translation_transliteration);
    }

}

From source file:com.brodev.socialapp.view.BlogPostNew.java

private void initView() {
    TextView moduleName = (TextView) this.findViewById(R.id.moduleName);
    moduleName.setText(phraseManage.getPhrase(getApplicationContext(), "blog.add_a_new_blog"));

    TextView title = (TextView) this.findViewById(R.id.textTitle);
    title.setHint(phraseManage.getPhrase(getApplicationContext(), "blog.title"));

    TextView post = (TextView) this.findViewById(R.id.textCotent);
    post.setHint(phraseManage.getPhrase(getApplicationContext(), "blog.post"));

    ImageView privacyImg = (ImageView) this.findViewById(R.id.post_stt_privacy_img);
    colorView.changeColorPrivacy(privacyImg, user.getColor());

    // category/* w w w.  j av  a2  s  .c om*/
    TextView categories = (TextView) this.findViewById(R.id.categoryView);
    categories.setText(phraseManage.getPhrase(getApplicationContext(), "blog.categories"));

    getCategory = (LinearLayout) this.findViewById(R.id.listCategories);
    BlogCategoryTask showBlogCategory = new BlogCategoryTask();

    progressBlog = (ProgressBar) this.findViewById(R.id.progress_blog);

    showBlogCategory.execute();

    // show privacy
    TextView postPrivacy = (TextView) this.findViewById(R.id.postPrivacy);
    postPrivacy.setText(phraseManage.getPhrase(getApplicationContext(), "blog.privacy"));

    final TextView privacy_status = (TextView) this.findViewById(R.id.status_privacy);
    privacy_status.setText(phraseManage.getPhrase(getApplicationContext(), "privacy.everyone"));

    privacy = new Privacy(this);
    privacy.setTextView(privacy_status);
    privacy_status.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            try {
                privacy.showMessage();
            } catch (Exception e) {

            }
        }
    });

}

From source file:fm.smart.r1.activity.CreateExampleActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ExceptionHandler.register(this);
    setContentView(R.layout.create_example);
    final Intent queryIntent = getIntent();
    Bundle extras = queryIntent.getExtras();
    item_id = (String) extras.get("item_id");
    list_id = (String) extras.get("list_id");
    if (list_id == null || list_id.equals("")) {
        list_id = Main.default_study_list_id;
    }//from w ww  .j  a  v  a 2  s.  c om

    cue = (String) extras.get("cue");
    example = (String) extras.get("example");
    translation = (String) extras.get("translation");
    example_language = (String) extras.get("example_language");
    translation_language = (String) extras.get("translation_language");
    example_transliteration = (String) extras.get("example_transliteration");
    translation_transliteration = (String) extras.get("translation_transliteration");

    TextView example_text = (TextView) findViewById(R.id.create_example_sentence);
    if (!TextUtils.isEmpty(example)) {
        example_text.setText(example);
    }
    example_text.setHint(example_language + " sentence with " + cue);
    TextView translation_text = (TextView) findViewById(R.id.create_example_translation);
    if (!TextUtils.isEmpty(translation)) {
        translation_text.setText(translation);
    }
    translation_text.setHint(translation_language + " translation of example sentence");

    Button button = (Button) findViewById(R.id.create_example_submit);
    button.setOnClickListener(this);

    TextView translation_text_legend = (TextView) findViewById(R.id.create_example_translation_legend);

    TextView sentence_transliteration_textView = (TextView) findViewById(
            R.id.create_example_sentence_transliteration);
    EditText sentence_transliteration_input_textView = (EditText) findViewById(R.id.sentence_transliteration);
    if (!Utils.isIdeographicLanguage(Main.search_lang)) {
        sentence_transliteration_textView.setVisibility(View.GONE);
        sentence_transliteration_input_textView.setVisibility(View.GONE);
    } else if (!TextUtils.isEmpty(example_transliteration)) {
        sentence_transliteration_input_textView.setText(example_transliteration);
    }

    TextView translation_transliteration_textView = (TextView) findViewById(
            R.id.create_example_translation_transliteration);
    EditText translation_transliteration_input_textView = (EditText) findViewById(
            R.id.translation_transliteration);
    if (!Utils.isIdeographicLanguage(Main.result_lang)) {
        translation_transliteration_textView.setVisibility(View.GONE);
        translation_transliteration_input_textView.setVisibility(View.GONE);
    } else if (!TextUtils.isEmpty(translation_transliteration)) {
        translation_transliteration_input_textView.setText(translation_transliteration);
    }

}

From source file:com.amazonaws.cognito.sync.demo.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    Log.i(TAG, "onCreate");

    /**//w ww  .  j a v  a 2  s  .com
     * Initialize Facebook SDK
     */
    FacebookSdk.sdkInitialize(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();

    //Twitter
    if (mOauthConsumer == null) {
        mOauthProvider = new DefaultOAuthProvider("https://api.twitter.com/oauth/request_token",
                "https://api.twitter.com/oauth/access_token", "https://api.twitter.com/oauth/authorize");
        mOauthConsumer = new DefaultOAuthConsumer(getString(R.string.twitter_consumer_key),
                getString(R.string.twitter_consumer_secret));
    }
    retrieveTwitterCredentials(getIntent());

    //If access token is already here, set fb session
    final AccessToken fbAccessToken = AccessToken.getCurrentAccessToken();
    if (fbAccessToken != null) {
        setFacebookSession(fbAccessToken);
        btnLoginFacebook.setVisibility(View.GONE);
    }

    /**
     * Initializes the sync client. This must be call before you can use it.
     */
    CognitoSyncClientManager.init(this);

    btnLoginFacebook = (Button) findViewById(R.id.btnLoginFacebook);
    btnLoginFacebook.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // start Facebook Login
            LoginManager.getInstance().logInWithReadPermissions(MainActivity.this,
                    Arrays.asList("public_profile"));
            LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    btnLoginFacebook.setVisibility(View.GONE);
                    new GetFbName(loginResult).execute();
                    setFacebookSession(loginResult.getAccessToken());
                }

                @Override
                public void onCancel() {
                    Toast.makeText(MainActivity.this, "Facebook login cancelled", Toast.LENGTH_LONG).show();
                }

                @Override
                public void onError(FacebookException error) {
                    Toast.makeText(MainActivity.this, "Error in Facebook login " + error.getMessage(),
                            Toast.LENGTH_LONG).show();
                }
            });
        }
    });
    btnLoginFacebook.setEnabled(getString(R.string.facebook_app_id) != "facebook_app_id");

    try {
        mAuthManager = new AmazonAuthorizationManager(this, Bundle.EMPTY);
    } catch (IllegalArgumentException e) {
        Log.d(TAG, "Login with Amazon isn't configured correctly. " + "Thus it's disabled in this demo.");
    }
    btnLoginLWA = (Button) findViewById(R.id.btnLoginLWA);
    btnLoginLWA.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            mAuthManager.authorize(APP_SCOPES, Bundle.EMPTY, new AuthorizeListener());
        }
    });
    btnLoginLWA.setEnabled(mAuthManager != null);

    Button btnWipedata = (Button) findViewById(R.id.btnWipedata);
    btnWipedata.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            new AlertDialog.Builder(MainActivity.this).setTitle("Wipe data?")
                    .setMessage("This will log off your current session and wipe all user data. "
                            + "Any data not synchronized will be lost.")
                    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // clear login status
                            if (fbAccessToken != null) {
                                LoginManager.getInstance().logOut();
                            }
                            btnLoginFacebook.setVisibility(View.VISIBLE);
                            if (mAuthManager != null) {
                                mAuthManager.clearAuthorizationState(null);
                            }
                            btnLoginLWA.setVisibility(View.VISIBLE);
                            // wipe data
                            CognitoSyncClientManager.getInstance().wipeData();

                            // Wipe shared preferences
                            AmazonSharedPreferencesWrapper
                                    .wipe(PreferenceManager.getDefaultSharedPreferences(MainActivity.this));
                        }

                    }).setNegativeButton("No", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    }).show();
        }
    });

    findViewById(R.id.btnListDatasets).setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, ListDatasetsActivity.class);
            startActivity(intent);
        }
    });

    btnLoginDevAuth = (Button) findViewById(R.id.btnLoginDevAuth);
    if ((CognitoSyncClientManager.credentialsProvider
            .getIdentityProvider()) instanceof DeveloperAuthenticationProvider) {
        btnLoginDevAuth.setEnabled(true);
        Log.w(TAG, "Developer authentication feature configured correctly. ");
    } else {
        btnLoginDevAuth.setEnabled(false);
        Log.w(TAG, "Developer authentication feature configured incorrectly. "
                + "Thus it's disabled in this demo.");
    }
    btnLoginDevAuth.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            // username and password dialog
            final Dialog login = new Dialog(MainActivity.this);
            login.setContentView(R.layout.login_dialog);
            login.setTitle("Sample developer login");
            final TextView txtUsername = (TextView) login.findViewById(R.id.txtUsername);
            txtUsername.setHint("Username");
            final TextView txtPassword = (TextView) login.findViewById(R.id.txtPassword);
            txtPassword.setHint("Password");
            Button btnLogin = (Button) login.findViewById(R.id.btnLogin);
            Button btnCancel = (Button) login.findViewById(R.id.btnCancel);

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

            btnLogin.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    // Validate the username and password
                    if (txtUsername.getText().toString().isEmpty()
                            || txtPassword.getText().toString().isEmpty()) {
                        new AlertDialog.Builder(MainActivity.this).setTitle("Login error")
                                .setMessage("Username or password cannot be empty!!").show();
                    } else {
                        // Clear the existing credentials
                        CognitoSyncClientManager.credentialsProvider.clearCredentials();
                        // Initiate user authentication against the
                        // developer backend in this case the sample Cognito
                        // developer authentication application.
                        ((DeveloperAuthenticationProvider) CognitoSyncClientManager.credentialsProvider
                                .getIdentityProvider()).login(txtUsername.getText().toString(),
                                        txtPassword.getText().toString(), MainActivity.this);
                    }
                    login.dismiss();
                }
            });
            login.show();
        }
    });

    /**
     * Button that leaves the app and launches the Twitter site to get an authorization.
     * If the user grants permissions to our app, it will be redirected to us again through
     * a callback.
     */
    Button btnLoginTwitter = (Button) findViewById(R.id.btnLoginTwitter);
    btnLoginTwitter.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        String callbackUrl = "callback://" + getString(R.string.twitter_callback_url);
                        String authUrl = mOauthProvider.retrieveRequestToken(mOauthConsumer, callbackUrl);
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl));
                        startActivity(intent);
                    } catch (Exception e) {
                        Log.w("oauth fail", e);
                    }
                }
            }).start();
        }
    });
    btnLoginTwitter.setEnabled(getString(R.string.twitter_consumer_secret) != "twitter_consumer_secret");

}

From source file:com.cmput301w15t15.travelclaimsapp.activitys.EditClaimActivity.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();

    switch (item.getItemId()) {
    case R.id.cmenu_dlist_delete:
        ClaimListController.removeDestination(destAdaptor.getItem(info.position), theClaim);
        destAdaptor.notifyDataSetChanged();
        return true;
    case R.id.cmenu_dlist_edit:
        //show a dialog for editing destinations 
        final EditText enterLocation = new EditText(this);
        final EditText enterReason = new EditText(this);

        enterLocation.setText(destAdaptor.getItem(info.position).getLocation());
        enterReason.setText(destAdaptor.getItem(info.position).getReason());

        enterLocation.setHint("Enter location");
        enterReason.setHint("Enter reason");

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.addView(enterLocation);
        linearLayout.addView(enterReason);

        AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setView(linearLayout);/*ww w.  j av  a  2 s  .c  om*/

        alert.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                destAdaptor.getItem(info.position).setLocation(enterLocation.getText().toString());
                destAdaptor.getItem(info.position).setReason(enterReason.getText().toString());
                destAdaptor.notifyDataSetChanged();
            }
        });
        alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.cancel();
            }
        });

        alert.show();
        return true;

    case R.id.cmenu_dlist_geolocation:
        adaptorPos = info.position;
        AlertDialog.Builder alertGl = new AlertDialog.Builder(this);
        alertGl.setPositiveButton("GPS", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (GeoLocationController.checkGPSEnabled()) {
                    GeoLocationController.setDestinationGeoLocationGPS(destAdaptor.getItem(info.position));
                    destAdaptor.notifyDataSetChanged();
                }
            }
        });
        alertGl.setNegativeButton("Map", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //Open map view \
                Intent intent = GeoLocationController.pickLocationIntent(EditClaimActivity.this);
                startActivityForResult(intent, GET_GEOLOCATION_CODE);
            }
        });

        alertGl.show();
        return true;
    case R.id.cmenu_delete_tag:
        ClaimListController.removeTag(theClaim, tagAdaptor.getItem(info.position));
        tagAdaptor.notifyDataSetChanged();
        return true;
    case R.id.cmenu_rename_tag:
        //create a Alert dialog for editing tag name
        final TextView enterTag = new AutoCompleteTextView(this);

        enterTag.setHint("Enter tag");

        AlertDialog.Builder alertTag = new AlertDialog.Builder(this);

        alertTag.setView(enterTag);

        alertTag.setPositiveButton("Add", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                tagAdaptor.getItem(info.position).setName(enterTag.getText().toString());
                tagAdaptor.notifyDataSetChanged();
            }
        });
        alertTag.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                dialog.cancel();
            }
        });

        alertTag.show();

        return true;
    default:
        return super.onContextItemSelected(item);
    }
}

From source file:org.mercycorps.translationcards.activity.RecordingActivity.java

private void moveToDoneStep() {
    setContentView(R.layout.recording_done);
    recycleBitmap();//from  w  w w . ja  v a 2  s.c o m
    currentBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.recording_done_image);
    currentBitmapView = (ImageView) findViewById(R.id.recording_done_image);
    currentBitmapView.setImageBitmap(currentBitmap);
    TextView titleView = (TextView) findViewById(R.id.recording_done_title);
    titleView.setText(getString(R.string.recording_done_title, dictionaryLabel));
    TextView detailView = (TextView) findViewById(R.id.recording_done_detail);
    detailView.setText(getString(R.string.recording_done_detail, dictionaryLabel));
    TextView cardTextView = (TextView) findViewById(R.id.origin_translation_text);
    cardTextView.setText(label);
    TextView translatedCardText = (TextView) findViewById(R.id.translated_text);
    if (translatedText.trim().isEmpty()) {
        translatedCardText.setHint(String.format(getString(R.string.translated_text_hint), dictionaryLabel));
        translatedCardText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
    } else {
        translatedCardText.setText(translatedText);
        translatedCardText.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
    }
    ImageView cardIndicator = (ImageView) findViewById(R.id.indicator_icon);
    cardIndicator.setBackgroundResource(R.drawable.collapse_arrow);
    findViewById(R.id.translation_child).setVisibility(View.VISIBLE);
    findViewById(R.id.translation_child_actions).setVisibility(View.GONE);

    final CardAudioClickListener cardAudioClickListener = new CardAudioClickListener(
            new Dictionary.Translation(label, IS_ASSET, filename, NO_DB_ID, translatedText),
            (ProgressBar) findViewById(R.id.recording_done_progress_bar), mediaPlayerManager);
    findViewById(R.id.recording_done_card).setOnClickListener(cardAudioClickListener);

    View backButton = findViewById(R.id.recording_done_edit);
    backButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            cardAudioClickListener.stopMediaPlayer();
            inEditMode = true;
            moveToLabelStep();
        }
    });

    View doneButton = (View) findViewById(R.id.recording_done);
    doneButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            recycleBitmap();
            setResult(RESULT_OK, intent);
            finish();
        }
    });
    stepHistory.push(Step.DONE);
}

From source file:com.github.irshulx.Components.InputExtensions.java

public TextView insertEditText(int position, String hint, CharSequence text) {
    String nextHint = isLastText(position) ? null : editorCore.getPlaceHolder();
    if (editorCore.getRenderType() == RenderType.Editor) {

        /**//from  w  w w .jav  a 2 s.c o  m
         * when user press enter from first line without keyin anything, need to remove the placeholder from that line 0...
         */
        if (position == 1) {
            View view = editorCore.getParentView().getChildAt(0);
            EditorType type = editorCore.getControlType(view);
            if (type == EditorType.INPUT) {
                TextView textView = (TextView) view;
                if (TextUtils.isEmpty(textView.getText())) {
                    textView.setHint(null);
                }
            }
        }

        final CustomEditText view = getNewEditTextInst(nextHint, text);
        editorCore.getParentView().addView(view, position);
        editorCore.setActiveView(view);
        final android.os.Handler handler = new android.os.Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setFocus(view);
            }
        }, 0);
        editorCore.setActiveView(view);
        return view;
    } else {
        final TextView view = getNewTextView(text);
        view.setTag(editorCore.createTag(EditorType.INPUT));
        editorCore.getParentView().addView(view);
        return view;
    }
}

From source file:net.smartpager.android.activity.MainActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    getMenuInflater().inflate(R.menu.main, menu);
    mSearchView = (SearchView) menu.findItem(R.id.item_search_menu).getActionView();
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
    int id = mSearchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
    TextView mSearchViewText = (TextView) mSearchView.findViewById(id);
    mSearchViewText.setTextColor(Color.WHITE);
    mSearchViewText.setHint("");
    int closeButtonId = mSearchView.getContext().getResources().getIdentifier("android:id/search_close_btn",
            null, null);/*from   w ww . ja v a2  s .c o m*/
    ImageView closeButton = (ImageView) mSearchView.findViewById(closeButtonId);
    closeButton.setImageResource(R.drawable.action_close);

    int searchImgId = getResources().getIdentifier("android:id/search_button", null, null);
    ImageView v = (ImageView) mSearchView.findViewById(searchImgId);
    v.setImageResource(R.drawable.action_search);

    mSearchMenuItem = menu.findItem(R.id.item_search_menu);
    mSearchMenuItem.setVisible(true);

    mClearMenuItem = menu.findItem(R.id.item_clear_archive);
    mClearMenuItem.setVisible(false);
    mArchiveAllMenuItem = menu.findItem(R.id.item_archive_all);
    mArchiveAllMenuItem.setVisible(true);

    return true;
}

From source file:org.chromium.chrome.browser.ntp.NewTabPageView.java

/**
 * Sets up the hint text and event handlers for the search box text view.
 *//*from   w ww  . jav a2  s. co  m*/
private void initializeSearchBoxTextView() {
    final TextView searchBoxTextView = (TextView) mSearchBoxView.findViewById(R.id.search_box_text);
    String hintText = getResources().getString(R.string.search_or_type_url);

    if (!DeviceFormFactor.isTablet(getContext()) || mManager.isFakeOmniboxTextEnabledTablet()) {
        searchBoxTextView.setHint(hintText);
    } else {
        searchBoxTextView.setContentDescription(hintText);
    }
    searchBoxTextView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mManager.focusSearchBox(false, null);
        }
    });
    searchBoxTextView.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

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

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 0)
                return;
            mManager.focusSearchBox(false, s.toString());
            searchBoxTextView.setText("");
        }
    });
}

From source file:edu.usf.cutr.opentripplanner.android.fragments.MainFragment.java

private void addInterfaceListeners() {

    final OnMapClickListener onMapClickListener = new OnMapClickListener() {
        @Override/*from ww  w  . ja  v a2s. co  m*/
        public void onMapClick(LatLng latlng) {
            InputMethodManager imm = (InputMethodManager) MainFragment.this.getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mTbEndLocation.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(mTbStartLocation.getWindowToken(), 0);

            if (mTbStartLocation.hasFocus()) {
                setMarker(true, latlng, true);
            } else {
                setMarker(false, latlng, true);
            }
        }
    };
    mMap.setOnMapClickListener(onMapClickListener);

    OnMarkerDragListener onMarkerDragListener = new OnMarkerDragListener() {

        @Override
        public void onMarkerDrag(Marker marker) {
        }

        @Override
        public void onMarkerDragEnd(Marker marker) {
            LatLng markerLatlng = marker.getPosition();

            if (((mOTPApp.getSelectedServer() != null) && LocationUtil.checkPointInBoundingBox(markerLatlng,
                    mOTPApp.getSelectedServer(), OTPApp.CHECK_BOUNDS_ACCEPTABLE_ERROR))
                    || (mOTPApp.getSelectedServer() == null)) {
                if ((mStartMarker != null) && (marker.hashCode() == mStartMarker.hashCode())) {
                    if (mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_USE_INTELLIGENT_MARKERS, true)) {
                        updateMarkerPosition(markerLatlng, true);
                    } else {
                        mIsStartLocationGeocodingCompleted = true;
                        removeFocus(true);
                        setMarker(true, markerLatlng, false);
                    }
                    mStartMarkerPosition = markerLatlng;
                } else if ((mEndMarker != null) && (marker.hashCode() == mEndMarker.hashCode())) {
                    if (mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_USE_INTELLIGENT_MARKERS, true)) {
                        updateMarkerPosition(markerLatlng, false);
                    } else {
                        mIsEndLocationGeocodingCompleted = true;
                        removeFocus(false);
                        setMarker(false, markerLatlng, false);
                    }
                    mEndMarkerPosition = markerLatlng;
                }
            } else {

                if ((mStartMarker != null) && (marker.hashCode() == mStartMarker.hashCode())) {
                    marker.setPosition(mStartMarkerPosition);
                } else {
                    marker.setPosition(mEndMarkerPosition);
                }
                Toast.makeText(mApplicationContext,
                        mApplicationContext.getResources().getString(
                                R.string.toast_map_markers_marker_out_of_boundaries),
                        Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onMarkerDragStart(Marker marker) {
            InputMethodManager imm = (InputMethodManager) MainFragment.this.getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mTbEndLocation.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(mTbStartLocation.getWindowToken(), 0);
        }
    };
    mMap.setOnMarkerDragListener(onMarkerDragListener);

    OnMapLongClickListener onMapLongClickListener = new OnMapLongClickListener() {
        @Override
        public void onMapLongClick(LatLng latlng) {
            InputMethodManager imm = (InputMethodManager) MainFragment.this.getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mTbEndLocation.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(mTbStartLocation.getWindowToken(), 0);

            final LatLng latLngFinal = latlng;
            final CharSequence[] items = {
                    mApplicationContext.getResources()
                            .getString(R.string.point_type_selector_start_marker_option),
                    mApplicationContext.getResources()
                            .getString(R.string.point_type_selector_end_marker_option) };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainFragment.this.getActivity());
            builder.setTitle(getResources().getString(R.string.point_type_selector_title));
            builder.setItems(items, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    if (item == 0) {
                        setMarker(true, latLngFinal, true);
                    } else {
                        setMarker(false, latLngFinal, true);
                    }
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
        }
    };
    mMap.setOnMapLongClickListener(onMapLongClickListener);

    OnClickListener onClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            mDrawerLayout.openDrawer(Gravity.LEFT);
        }
    };
    mBtnHandle.setOnClickListener(onClickListener);

    OnInfoWindowClickListener onInfoWindowClickListener = new OnInfoWindowClickListener() {

        @Override
        public void onInfoWindowClick(Marker modeMarker) {
            saveOTPBundle();
            OTPBundle otpBundle = getFragmentListener().getOTPBundle();
            Matcher matcher = Pattern.compile("\\d+").matcher(modeMarker.getTitle());
            if (matcher.find()) {
                String numberString = modeMarker.getTitle().substring(0, matcher.end());
                //Step indexes shown to the user are in a scale starting by 1 but instructions steps internally start by 0
                int currentStepIndex = Integer.parseInt(numberString) - 1;
                otpBundle.setCurrentStepIndex(currentStepIndex);
                otpBundle.setFromInfoWindow(true);
                getFragmentListener().setOTPBundle(otpBundle);
                getFragmentListener().onSwitchedToDirectionFragment();
            }

        }
    };
    mMap.setOnInfoWindowClickListener(onInfoWindowClickListener);

    DrawerListener dl = new DrawerListener() {
        @Override
        public void onDrawerStateChanged(int arg0) {
        }

        @Override
        public void onDrawerSlide(View arg0, float arg1) {

            InputMethodManager imm = (InputMethodManager) MainFragment.this.getActivity()
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(mTbEndLocation.getWindowToken(), 0);
            imm.hideSoftInputFromWindow(mTbStartLocation.getWindowToken(), 0);
        }

        @Override
        public void onDrawerOpened(View arg0) {
        }

        @Override
        public void onDrawerClosed(View arg0) {
        }
    };
    mDrawerLayout.setDrawerListener(dl);

    OnTouchListener otlStart = new RightDrawableOnTouchListener(mTbStartLocation) {
        @Override
        public boolean onDrawableTouch(final MotionEvent event) {

            final CharSequence[] items = {
                    getResources().getString(R.string.text_box_dialog_location_type_current_location),
                    getResources().getString(R.string.text_box_dialog_location_type_contact),
                    getResources().getString(R.string.text_box_dialog_location_type_map_point) };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainFragment.this.getActivity());
            builder.setTitle(getResources().getString(R.string.text_box_dialog_choose_location_type_start));
            builder.setItems(items, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                    if (items[item].equals(getResources()
                            .getString(R.string.text_box_dialog_location_type_current_location))) {
                        LatLng mCurrentLatLng = getLastLocation();
                        if (mCurrentLatLng != null) {
                            SharedPreferences.Editor prefsEditor = mPrefs.edit();
                            setTextBoxLocation(getResources().getString(R.string.text_box_my_location), true);
                            prefsEditor.putBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, true);

                            if (mStartMarker != null) {
                                mStartMarker.remove();
                                mStartMarker = null;
                            }

                            prefsEditor.commit();
                        } else {
                            Toast.makeText(MainFragment.this.mApplicationContext,
                                    mApplicationContext.getResources()
                                            .getString(R.string.toast_tripplanner_current_location_error),
                                    Toast.LENGTH_LONG).show();
                        }

                    } else if (items[item]
                            .equals(getResources().getString(R.string.text_box_dialog_location_type_contact))) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE);
                        ((MyActivity) MainFragment.this.getActivity()).setButtonStartLocation(true);

                        MainFragment.this.getActivity().startActivityForResult(intent,
                                OTPApp.CHOOSE_CONTACT_REQUEST_CODE);

                    } else { // Point on Map
                        if (mStartMarker != null) {
                            updateMarkerPosition(mStartMarker.getPosition(), true);
                        } else {
                            setTextBoxLocation("", true);
                            mTbStartLocation
                                    .setHint(getResources().getString(R.string.text_box_need_to_place_marker));
                            mTbStartLocation.requestFocus();
                        }
                    }
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }

    };

    mTbStartLocation.setOnTouchListener(otlStart);

    OnTouchListener otlEnd = new RightDrawableOnTouchListener(mTbEndLocation) {
        @Override
        public boolean onDrawableTouch(final MotionEvent event) {

            final CharSequence[] items = {
                    getResources().getString(R.string.text_box_dialog_location_type_current_location),
                    getResources().getString(R.string.text_box_dialog_location_type_contact),
                    getResources().getString(R.string.text_box_dialog_location_type_map_point) };

            AlertDialog.Builder builder = new AlertDialog.Builder(MainFragment.this.getActivity());
            builder.setTitle(getResources().getString(R.string.text_box_dialog_choose_location_type_end));
            builder.setItems(items, new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int item) {
                    if (items[item].equals(getResources()
                            .getString(R.string.text_box_dialog_location_type_current_location))) {
                        LatLng mCurrentLatLng = getLastLocation();
                        if (mCurrentLatLng != null) {
                            SharedPreferences.Editor prefsEditor = mPrefs.edit();
                            setTextBoxLocation(getResources().getString(R.string.text_box_my_location), false);
                            prefsEditor.putBoolean(OTPApp.PREFERENCE_KEY_DESTINATION_IS_MY_LOCATION, true);

                            if (mEndMarker != null) {
                                mEndMarker.remove();
                                mEndMarker = null;
                            }

                            prefsEditor.commit();
                        } else {
                            Toast.makeText(MainFragment.this.mApplicationContext,
                                    mApplicationContext.getResources()
                                            .getString(R.string.toast_tripplanner_current_location_error),
                                    Toast.LENGTH_LONG).show();
                        }

                    } else if (items[item]
                            .equals(getResources().getString(R.string.text_box_dialog_location_type_contact))) {
                        Intent intent = new Intent(Intent.ACTION_PICK);
                        intent.setType(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_TYPE);
                        ((MyActivity) MainFragment.this.getActivity()).setButtonStartLocation(false);

                        MainFragment.this.getActivity().startActivityForResult(intent,
                                OTPApp.CHOOSE_CONTACT_REQUEST_CODE);

                    } else { // Point on Map
                        if (mEndMarker != null) {
                            updateMarkerPosition(mEndMarker.getPosition(), false);
                        } else {
                            setTextBoxLocation("", false);
                            mTbEndLocation
                                    .setHint(getResources().getString(R.string.text_box_need_to_place_marker));
                            mTbEndLocation.requestFocus();
                        }
                    }
                }
            });
            AlertDialog alert = builder.create();
            alert.show();
            return true;
        }

    };

    mTbEndLocation.setOnTouchListener(otlEnd);

    mBtnPlanTrip.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            processRequestTrip();
        }
    });

    OnFocusChangeListener tbLocationOnFocusChangeListener = new OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {

            if (hasFocus) {
                mMap.setOnMapClickListener(onMapClickListener);
            }

            TextView tv = (TextView) v;
            if (!hasFocus) {
                CharSequence tvCharSequence = tv.getText();

                if (tvCharSequence != null) {
                    String text = tvCharSequence.toString();

                    if (!TextUtils.isEmpty(text)) {
                        if (v.getId() == R.id.tbStartLocation && !mIsStartLocationGeocodingCompleted
                                && !mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, true)) {
                            processAddress(true, text, false);
                        } else if (v.getId() == R.id.tbEndLocation && !mIsEndLocationGeocodingCompleted
                                && !mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_DESTINATION_IS_MY_LOCATION, true)) {
                            processAddress(false, text, false);
                        }
                    } else {
                        if (v.getId() == R.id.tbStartLocation) {
                            tv.setHint(getResources().getString(R.string.text_box_start_location_hint));
                        } else if (v.getId() == R.id.tbEndLocation) {
                            tv.setHint(getResources().getString(R.string.text_box_end_location_hint));
                        }
                    }
                } else {
                    Log.w(OTPApp.TAG,
                            "Focus has changed, but was not possible to obtain start/end" + " textbox text");
                }
            }
        }
    };
    mTbStartLocation.setOnFocusChangeListener(tbLocationOnFocusChangeListener);
    mTbEndLocation.setOnFocusChangeListener(tbLocationOnFocusChangeListener);

    TextWatcher textWatcherStart = new TextWatcher() {

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

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

        @Override
        public void afterTextChanged(Editable s) {
            if (mIsStartLocationChangedByUser) {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                prefsEditor.putBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, false);
                prefsEditor.commit();
                mIsStartLocationGeocodingCompleted = false;
            } else {
                mIsStartLocationChangedByUser = true;
            }
        }
    };

    TextWatcher textWatcherEnd = new TextWatcher() {

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

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

        @Override
        public void afterTextChanged(Editable s) {
            if (mIsEndLocationChangedByUser) {
                SharedPreferences.Editor prefsEditor = mPrefs.edit();
                prefsEditor.putBoolean(OTPApp.PREFERENCE_KEY_DESTINATION_IS_MY_LOCATION, false);
                prefsEditor.commit();
                mIsEndLocationGeocodingCompleted = false;
            } else {
                mIsEndLocationChangedByUser = true;
            }
        }
    };

    mTbStartLocation.addTextChangedListener(textWatcherStart);
    mTbEndLocation.addTextChangedListener(textWatcherEnd);

    OnEditorActionListener tbLocationOnEditorActionListener = new OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (v.getId() == R.id.tbStartLocation) {
                if (actionId == EditorInfo.IME_ACTION_NEXT
                        || (event != null && event.getAction() == KeyEvent.ACTION_DOWN
                                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    if (!mIsStartLocationGeocodingCompleted
                            && !mPrefs.getBoolean(OTPApp.PREFERENCE_KEY_ORIGIN_IS_MY_LOCATION, true)) {
                        CharSequence tvCharSequence = v.getText();
                        if (tvCharSequence != null) {
                            processAddress(true, tvCharSequence.toString(), false);
                        } else {
                            Log.w(OTPApp.TAG, "User switched to next input, but was not possible to"
                                    + "obtain start/end textbox text");
                        }
                    }
                }
            } else if (v.getId() == R.id.tbEndLocation) {
                if (actionId == EditorInfo.IME_ACTION_DONE
                        || (event != null && event.getAction() == KeyEvent.ACTION_DOWN
                                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                    processRequestTrip();
                }
            }
            return false;
        }
    };

    mTbStartLocation.setOnEditorActionListener(tbLocationOnEditorActionListener);
    mTbEndLocation.setOnEditorActionListener(tbLocationOnEditorActionListener);

    OnClickListener oclDisplayDirection = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            saveOTPBundle();
            getFragmentListener().onSwitchedToDirectionFragment();
        }
    };
    mBtnDisplayDirection.setOnClickListener(oclDisplayDirection);

    // Do NOT show direction icon if there is no direction yet
    toggleItinerarySelectionSpinner(!getFragmentListener().getCurrentItinerary().isEmpty());

    OnClickListener oclMyLocation = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            LatLng mCurrentLatLng = getLastLocation();

            if (mCurrentLatLng == null) {
                Toast.makeText(mApplicationContext, mApplicationContext.getResources()
                        .getString(R.string.toast_tripplanner_current_location_error), Toast.LENGTH_LONG)
                        .show();
            } else {
                if (mMap.getCameraPosition().zoom < OTPApp.defaultMyLocationZoomLevel) {
                    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(mCurrentLatLng,
                            OTPApp.defaultMyLocationZoomLevel));
                } else {
                    mMap.animateCamera(CameraUpdateFactory.newLatLng(getLastLocation()));
                }
            }
        }
    };
    mBtnMyLocation.setOnClickListener(oclMyLocation);

    OnClickListener oclDateDialog = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            FragmentTransaction ft = MainFragment.this.getActivity().getSupportFragmentManager()
                    .beginTransaction();
            Fragment prev = MainFragment.this.getActivity().getSupportFragmentManager()
                    .findFragmentByTag(OTPApp.TAG_FRAGMENT_DATE_TIME_DIALOG);
            if (prev != null) {
                ft.remove(prev);
            }
            ft.addToBackStack(null);

            // Create and show the dialog.
            DateTimeDialog newFragment = new DateTimeDialog();

            Date dateDialogDate;
            if (mTripDate == null) {
                dateDialogDate = Calendar.getInstance().getTime();
            } else {
                dateDialogDate = mTripDate;
            }

            Bundle bundle = new Bundle();
            bundle.putSerializable(OTPApp.BUNDLE_KEY_TRIP_DATE, dateDialogDate);
            bundle.putBoolean(OTPApp.BUNDLE_KEY_ARRIVE_BY, mArriveBy);
            newFragment.setArguments(bundle);
            ft.commit();

            newFragment.show(MainFragment.this.getActivity().getSupportFragmentManager(),
                    OTPApp.TAG_FRAGMENT_DATE_TIME_DIALOG);
        }
    };
    mBtnDateDialog.setOnClickListener(oclDateDialog);

    AdapterView.OnItemSelectedListener itinerarySpinnerListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            mFragmentListener.onItinerarySelected(position);

            if (!mAppResumed) {
                showRouteOnMap(mFragmentListener.getCurrentItinerary(), true);
            } else {
                showRouteOnMap(mFragmentListener.getCurrentItinerary(), false);
                mAppResumed = false;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    };
    int currentItineraryIndex = mFragmentListener.getCurrentItineraryIndex();

    mItinerarySelectionSpinner.setSelection(currentItineraryIndex);
    mItinerarySelectionSpinner.setOnItemSelectedListener(itinerarySpinnerListener);

    mBikeTriangleParameters.setOnRangeSeekBarChangeListener(new OnRangeSeekBarChangeListener<Double>() {
        @Override
        public void onRangeSeekBarValuesChanged(RangeSeekBar<?> rangeSeekBar, Double minValue,
                Double maxValue) {
            // handle changed range values
            Log.i(OTPApp.TAG, "User selected new range values: MIN=" + minValue + ", MAX=" + maxValue);
        }

    });

    mDdlTravelMode.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            TraverseModeSpinnerItem traverseModeSpinnerItem = (TraverseModeSpinnerItem) mDdlTravelMode
                    .getItemAtPosition(position);
            if (traverseModeSpinnerItem != null) {
                if (traverseModeSpinnerItem.getTraverseModeSet().contains(TraverseMode.BICYCLE)) {
                    setBikeOptimizationAdapter(true);
                    showBikeParameters(true);
                } else {
                    setBikeOptimizationAdapter(false);
                    showBikeParameters(false);
                }

                mBtnPlanTrip.setImageBitmap(BitmapFactory.decodeResource(getResources(),
                        DirectionsGenerator.getModeIcon(traverseModeSpinnerItem.getTraverseModeSet())));
            }
            Log.e(OTPApp.TAG, "Not possible to change travel mode because traverse mode is unknown"
                    + "for selected transport medium");
        }
    });

    mDdlOptimization.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            OptimizeSpinnerItem optimizeSpinnerItem = (OptimizeSpinnerItem) mDdlOptimization
                    .getItemAtPosition(position);
            if (optimizeSpinnerItem != null) {
                showBikeParameters(optimizeSpinnerItem.getOptimizeType().equals(OptimizeType.TRIANGLE));
            } else {
                Log.e(OTPApp.TAG, "Not possible to change optimization mode because selected"
                        + "optimization is unknown");
            }
        }
    });

    mBikeTriangleParameters.setOnRangeSeekBarChangeListener(this);
}