下面列出了怎么用android.widget.EditText的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 处理点击非 EditText 区域时,自动关闭键盘
*
* @param isAutoCloseKeyboard 是否自动关闭键盘
* @param currentFocusView 当前获取焦点的控件
* @param motionEvent 触摸事件
* @param dialogOrActivity Dialog 或 Activity
*/
public static void handleAutoCloseKeyboard(boolean isAutoCloseKeyboard, View currentFocusView, MotionEvent motionEvent, Object dialogOrActivity) {
if (isAutoCloseKeyboard && motionEvent.getAction() == MotionEvent.ACTION_DOWN && currentFocusView != null && (currentFocusView instanceof EditText) && dialogOrActivity != null) {
int[] leftTop = {0, 0};
currentFocusView.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + currentFocusView.getHeight();
int right = left + currentFocusView.getWidth();
if (!(motionEvent.getX() > left && motionEvent.getX() < right && motionEvent.getY() > top && motionEvent.getY() < bottom)) {
if (dialogOrActivity instanceof Dialog) {
XKeyboardUtils.closeKeyboard((Dialog) dialogOrActivity);
} else if (dialogOrActivity instanceof Activity) {
XKeyboardUtils.closeKeyboard((Activity) dialogOrActivity);
}
}
}
}
@Test
public void onNavigationItemSelected_shouldSelectAdd_clickValid() {
String NEW_ENVIRONMENT = "newEnvironment";
int NEW_ENVIRONMENT_ID = 108;
when(environmentService.add(NEW_ENVIRONMENT)).thenReturn(Observable.just(NEW_ENVIRONMENT_ID));
setupActivity();
clickMenuItem(R.id.nav_add);
ShadowAlertDialogSupport shadowAlertDialog = ShadowAlertDialogSupport.getShadowAlertDialog();
View inflatedView = shadowAlertDialog.getInflatedView();
EditText name = inflatedView.findViewById(R.id.editTextDialogEnvironmentName);
name.setText(NEW_ENVIRONMENT);
when(utilityService.isBlankText(name)).thenReturn(false);
when(utilityService.sanitizedText(name)).thenReturn(NEW_ENVIRONMENT);
shadowAlertDialog.performButtonClick(AlertDialog.BUTTON_POSITIVE);
verify(environmentService).add(NEW_ENVIRONMENT);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// TODO: Implement this method
View view=inflater.inflate(R.layout.activity_comment_, null);
weibo.setObjectId(nico.SPUtils.get(getActivity(), "mes", "") + "");
adapter = new MyAdapter(getActivity());
et_content = (EditText) view.findViewById(R.id.et_content);
btn_publish = (TextView) view.findViewById(R.id.btn_publish);
listView = (ListView) view.findViewById(R.id.listview);
listView.setAdapter(adapter);
btn_publish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
// TODO Auto-generated method stub
publishComment(et_content.getText().toString());
}
});
findComments();
return view;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_authorised_area_1, container, false);
ClickMe = (Button) rootView.findViewById(R.id.button);
ClickMe.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mEdit = (EditText) getView().findViewById(R.id.editText_password);
if(auth(sha1Hash(mEdit.getText().toString()))) {
FragmentManager fm = getFragmentManager();
AuthorisedArea_2 f = new AuthorisedArea_2();
fm.beginTransaction().replace(R.id.main_content,f).commit();
}
}
});
return rootView;
}
public static Matcher<View> withError(final String expected) {
return new TypeSafeMatcher<View>() {
@Override
public boolean matchesSafely(View view) {
if (!(view instanceof EditText)) {
return false;
}
EditText editText = (EditText) view;
return editText.getError().toString().equals(expected);
}
@Override
public void describeTo(Description description) {
}
};
}
@Override
public AlertDialog getActuatorDialog(Activity activity, final Action action, final Rule rule,
final ActuatorDialogFinishListener listener) {
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.dialog_actuator_single_textinput, null);
final EditText editText1 = (EditText) view.findViewById(R.id.etDialogActuatorEditText1);
editText1.setHint(SPOTIFY_URI);
AlertDialog.Builder builder = new AlertDialog.Builder(activity)
.setView(view)
.setTitle(describeActuator())
.setPositiveButton(activity.getString(R.string.accept), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String arguments = Action.jsonStringBuilder(SPOTIFY_URI,
editText1.getText().toString());
action.setArguments(arguments);
rule.addAction(action);
listener.onActuatorDialogFinish(action, rule);
}
})
.setNegativeButton(activity.getString(R.string.reject), null);
return builder.create();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.black_list_layout);
mSearchEditText = (EditText) findViewById(R.id.search_edit_text);
mSearchEditText.setOnFocusChangeListener(this);
mSystemAppCheckBox = (CheckBox) findViewById(R.id.show_system_app_check);
mSystemAppCheckBox.setChecked(AppList.shouldExcludeSystemApps(this));
mSystemAppCheckBox.setOnCheckedChangeListener(this);
initActionBar();
initFragments();
}
private void initView(){
rgLocationMode = (RadioGroup) findViewById(R.id.rg_locationMode);
etInterval = (EditText) findViewById(R.id.et_interval);
etHttpTimeout = (EditText) findViewById(R.id.et_httpTimeout);
cbOnceLocation = (CheckBox)findViewById(R.id.cb_onceLocation);
cbGpsFirst = (CheckBox) findViewById(R.id.cb_gpsFirst);
cbAddress = (CheckBox) findViewById(R.id.cb_needAddress);
cbCacheAble = (CheckBox) findViewById(R.id.cb_cacheAble);
cbOnceLastest = (CheckBox) findViewById(R.id.cb_onceLastest);
cbSensorAble = (CheckBox)findViewById(R.id.cb_sensorAble);
tvResult = (TextView) findViewById(R.id.tv_result);
btLocation = (Button) findViewById(R.id.bt_location);
rgLocationMode.setOnCheckedChangeListener(this);
btLocation.setOnClickListener(this);
}
@Override
void setupViews(ViewGroup view) {
if (showSearchBox) {
ListView listView = (ListView) view.findViewById(R.id.com_facebook_picker_list_view);
View searchHeaderView = getActivity().getLayoutInflater().inflate(
R.layout.com_facebook_picker_search_box, listView, false);
listView.addHeaderView(searchHeaderView, null, false);
searchBox = (EditText) view.findViewById(R.id.com_facebook_picker_search_text);
searchBox.addTextChangedListener(new SearchTextWatcher());
if (!TextUtils.isEmpty(searchText)) {
searchBox.setText(searchText);
}
}
}
/**
* 初始化控件
*/
private void initialView() {
DialogView.Initial(LoginActivity.this, "正在登录......");
tv_phone_regster = (TextView) findViewById(R.id.login_textview_phone_regster);
tv_password = (TextView) findViewById(R.id.login_textview_forget_password);
et_user = (EditText) findViewById(R.id.login_editText_user);
et_password = (EditText) findViewById(R.id.login_editText_password);
tv_login = (TextView) findViewById(R.id.login_textview_enter);
rb_qq = (RadioButton) findViewById(R.id.login_imageView_qqlogin);
rb_weibo = (RadioButton) findViewById(R.id.login_imageView_weibologin);
tv_phone_regster.setOnClickListener(this);
tv_password.setOnClickListener(this);
tv_login.setOnClickListener(this);
rb_qq.setOnClickListener(this);
rb_weibo.setOnClickListener(this);
}
@Test
public void whenSearchPlanIsRemovedExpectItToBeRemoved() {
final int testedPlanPosition = 5;
onView(withId(R.id.menu_search))
.perform(click());
onView(withId(R.id.menu_search)).perform(typeText(expectedName + testedPlanPosition));
closeSoftKeyboard();
onView(withId(R.id.rv_plan_list))
.perform(RecyclerViewActions
.actionOnItemAtPosition(0,
new ViewClicker(R.id.id_remove_plan)));
onView(withText(R.string.plan_removal_confirmation_positive_button)).perform(click());
onView(withRecyclerView(R.id.rv_plan_list)
.atPosition(0))
.check(doesNotExist());
onView(isAssignableFrom(EditText.class)).perform(clearText());
onView(withId(R.id.rv_plan_list)).perform(scrollToPosition(testedPlanPosition));
onView(withRecyclerView(R.id.rv_plan_list)
.atPosition(testedPlanPosition))
.check(matches(hasDescendant(withText(expectedName
+ (testedPlanPosition + 1)))));
}
/**
* 打开软键盘
* @param editText {@link EditText}
* @param handler {@link Handler}
* @param delayMillis 延迟时间 ( 毫秒 )
* @return {@code true} success, {@code false} fail
*/
public static boolean openKeyboard(final EditText editText, final Handler handler, final long delayMillis) {
if (editText != null && handler != null) {
handler.postDelayed(new Runnable() {
@Override
public void run() {
try {
editText.requestFocus();
editText.setSelection(editText.getText().toString().length());
} catch (Exception e) {
}
openKeyboard(editText);
}
}, delayMillis);
return true;
}
return false;
}
public void setUrlBarText(String url){
if (url!=null){
CustomWebView WV = activityRef.get().webLayout.findViewById(R.id.browser_page);
if (WV!=null && this!=null && WV.equals(this)){
if ((activityRef.get().findViewById(R.id.browser_searchbar))!=null && !activityRef.get().findViewById(R.id.browser_searchbar).isFocused()){
if (url.startsWith("file:///android_asset/")) {
((EditText) activityRef.get().findViewById(R.id.browser_searchbar)).setText("");
((EditText) activityRef.get().findViewById(R.id.browser_searchbar)).setHint(R.string.urlbardefault);
}else{
((EditText) activityRef.get().findViewById(R.id.browser_searchbar))
.setText(url
.replace("http://", "")
.replace("https://", ""));
}
}
}
}
}
/**
* 设置编辑列表VIEW
*
* @param names 编辑view 的name
* @return this
*/
public BaseDialog setEditViewsName(List<String> names) {
if (middleLayout.getChildCount() > 0) {
middleLayout.removeAllViews();
}
for (String name :
names) {
TextView textView = new TextView(getContext());
textView.setText(name);
EditText editText = new EditText(getContext());
editText.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
editText.setHint("请输入" + name);
editText.setPadding(10, 0, 0, 0);
editText.setHintTextColor(Color.BLUE);
LinearLayout child = new LinearLayout(getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
child.setOrientation(LinearLayout.HORIZONTAL);
child.setGravity(Gravity.CENTER_VERTICAL);
child.setLayoutParams(params);
child.addView(textView);
child.addView(editText);
middleLayout.addView(child);
}
return this;
}
private void initView() {
actionBar = (QtNewActionBar) this.findViewById(R.id.my_action_bar);
setNewActionBar(actionBar);
setActionBarTitle(!isUpdate? R.string.atom_ui_todolist_title_create :R.string.atom_ui_todolist_title_update);
setActionBarRightText(R.string.atom_ui_common_save);
setActionBarRightTextClick(new View.OnClickListener() {
@Override
public void onClick(View v) {
editTodoList();
}
});
todolist_title = (EditText) findViewById(R.id.todolist_title);
todolist_content = (EditText) findViewById(R.id.todolist_content);
if (dailyMindMain != null) {
todolist_title.setText(dailyMindMain.title);
todolist_content.setText(dailyMindMain.content);
}
}
/**
* Detect Name of the Widget
*
* @param v
* Widget
* @return
*/
protected String detectName(View v) {
String name = "";
if (v instanceof TextView) {
TextView t = (TextView) v;
name = (t.getText() != null) ? t.getText().toString() : "";
if (v instanceof EditText) {
CharSequence hint = ((EditText) v).getHint();
name = (hint == null) ? "" : hint.toString();
}
} else if (v instanceof RadioGroup) {
RadioGroup g = (RadioGroup) v;
int max = g.getChildCount();
String text = "";
for (int i = 0; i < max; i++) {
View c = g.getChildAt(i);
text = detectName(c);
if (!text.equals("")) {
name = text;
break;
}
}
}
return name;
}
@Override
public void onButtonTouch(MotionEvent event, View view){
try {
if (event.getAction() == MotionEvent.ACTION_UP ){
String viewName = "";
String viewType = "";
String idName = ViewUtils.getSimpleResourceName(view.getContext(), view.getId());
//获取文本值
viewName =getButtonName(view );
//动态生成view 比如listView
if (view.hasOnClickListeners() && TextUtils.isEmpty(idName)){
idName = viewName;
}
viewType = (view instanceof EditText) ? "text": "button";
// onClickButton(idName,viewName,viewType);
onClickButton(idName,viewName,viewType);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void initview() {
currentcity = (TextView) homeContent.findViewById(R.id.currentcity);
pm25 = (TextView) homeContent.findViewById(R.id.pm25);
temp = (TextView) homeContent.findViewById(R.id.temp);
searchWeatherBtn= (Button) homeContent.findViewById(R.id.btn_search);
pollution = (TextView) homeContent.findViewById(R.id.pollution_level);
inputcity = (EditText) homeContent.findViewById(R.id.inputcity);
weatherInfolist = (ListView) homeContent
.findViewById(R.id.weather_infor_list);
}
private boolean inputIsValid() {
String enteredPassword = ((EditText)findViewById(R.id.edit_password)).getText().toString();
if ("".equals(enteredPassword)) {
enterErrorState(Localization.get("missing.fields"));
return false;
}
if (inMobileUserAuthMode) {
String enteredMobileUser = ((EditText)findViewById(R.id.edit_username)).getText().toString();
String enteredDomain = ((EditText)findViewById(R.id.edit_domain)).getText().toString();
if ("".equals(enteredMobileUser) || "".equals(enteredDomain)) {
enterErrorState(Localization.get("missing.fields"));
return false;
}
} else {
String enteredEmail = ((EditText)findViewById(R.id.edit_email)).getText().toString();
if ("".equals(enteredEmail)) {
enterErrorState(Localization.get("missing.fields"));
return false;
}
if (!enteredEmail.contains("@")) {
enterErrorState(Localization.get("email.address.invalid"));
return false;
}
}
return true;
}
private void findViews() {
nameEditText = (EditText) findViewById(R.id.lessons_add_name_EditText);
dayEditText = (EditText) findViewById(R.id.lessons_add_day_EditText);
steStartEditText = (EditText) findViewById(R.id.lessons_add_ste_start_EditText);
steEndEditText = (EditText) findViewById(R.id.lessons_add_ste_end_EditText);
timeStartEditText = (EditText) findViewById(R.id.lessons_add_time_start_EditText);
timeEndEditText = (EditText) findViewById(R.id.lessons_add_time_end_EditText);
placeEditText = (EditText) findViewById(R.id.lessons_add_place_EditText);
teacherEditText = (EditText) findViewById(R.id.lessons_add_teacher_EditText);
otherEditText = (EditText) findViewById(R.id.lessons_add_other_EditText);
mjzCheckBox = (CheckBox) findViewById(R.id.lessons_add_mjz_CheckBox);
saveButton = (Button) findViewById(R.id.lessons_add_save_Button);
deleteButton = (Button) findViewById(R.id.lessons_add_delete_Button);
}
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
alert.setMessage(getString(R.string.enter_new_file_name));
// Set an EditText view to get user input
final String filename = getArguments().getString(ARG_FILENAME);
final EditText input = new EditText(getActivity());
input.setId(android.R.id.edit);
input.setSingleLine();
input.setText(filename);
StringPathUtil spu = new StringPathUtil(filename);
String fnWoExt = spu.getFileNameWithoutExtension();
if(fnWoExt.length() > 0)
input.setSelection(0, fnWoExt.length());
alert.setView(input);
alert.setPositiveButton(getString(android.R.string.ok),
(dialog, whichButton) -> renameFile(input.getText().toString()));
alert.setNegativeButton(android.R.string.cancel,
(dialog, whichButton) ->
{
// Canceled.
});
return alert.create();
}
private ViewAction paste(final String type) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
// noinspection unchecked
Matcher<View> matchers = allOf(isDisplayed());
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
return allOf(matchers, supportsInputMethods());
} else {
// SearchView does not support input methods itself (rather it delegates to an internal text
// view for input).
return allOf(matchers, anyOf(supportsInputMethods(), isAssignableFrom(SearchView.class)));
}
}
@Override
public String getDescription() {
return "Straight typing into view";
}
@Override
public void perform(UiController uiController, View view) {
((EditText) view).setText(type);
}
};
}
/**
* Inits the views.
*/
private void initViews() {
etInputCaptchaCode = (EditText) findViewById(R.id.etInputCaptchaCode);
llCaptchaCode_Linear = (LinearLayout) findViewById(R.id.CaptchaCode_Linear);
btnGetCaptchaCode = (Button) findViewById(R.id.btnReGetCaptchaCode);
CaptchaCode_Loading=(ProgressBar) findViewById(R.id.CaptchaCode_Loading);
//
tvTips = (TextView) findViewById(R.id.tvTips);
tvPhoneSwitch = (TextView) findViewById(R.id.tvPhoneSwitch);
etName = (EditText) findViewById(R.id.etName);
etInputCode = (EditText) findViewById(R.id.etInputCode);
etInputPsw = (EditText) findViewById(R.id.etInputPsw);
btnGetCode = (Button) findViewById(R.id.btnGetCode);
btnReGetCode = (Button) findViewById(R.id.btnReGetCode);
btnSure = (Button) findViewById(R.id.btnSure);
llInputCode = (LinearLayout) findViewById(R.id.llInputCode);
llInputPsw = (LinearLayout) findViewById(R.id.llInputPsw);
ivBack = (ImageView) findViewById(R.id.ivBack);
ivStep = (ImageView) findViewById(R.id.ivStep);
tbPswFlag = (ToggleButton) findViewById(R.id.tbPswFlag);
toogleUI(ui_statue.DEFAULT);
dialog = new ProgressDialog(this);
dialog.setMessage("处理中,请稍候...");
MyInputFilter filter = new MyInputFilter();
etInputPsw.setFilters(new InputFilter[] { filter });
}
private void init() {
// TODO Auto-generated method stub
registerModel = new RegisterModel();
userNamEditText = (EditText) findViewById(R.id.register_username);
maiEditText = (EditText) findViewById(R.id.register_mail);
passwdEditText = (EditText) findViewById(R.id.register_passwd);
confirmPasswdEditText = (EditText) findViewById(R.id.register_repasswd);
registerButton = (Button) findViewById(R.id.register_ok);
registerButton.setOnClickListener(new Click());
}
private void initView() {
View dialogView = LayoutInflater.from(getContext()).inflate(R.layout.dialog_edittext_sure_false, null);
mIvLogo = (ImageView) dialogView.findViewById(R.id.iv_logo);
mTvTitle = (TextView) dialogView.findViewById(R.id.tv_title);
mTvSure = (TextView) dialogView.findViewById(R.id.tv_sure);
mTvCancel = (TextView) dialogView.findViewById(R.id.tv_cancle);
editText = (EditText) dialogView.findViewById(R.id.editText);
setContentView(dialogView);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_face);
mImageGenerator = new ImageGenerator(this);
mDateEditText = (EditText) findViewById(R.id.txtDateEntered);
mDisplayGeneratedImage = (ImageView) findViewById(R.id.imgGenerated);
mImageGenerator.setIconSize(50, 50);
mImageGenerator.setDateSize(30);
mImageGenerator.setMonthSize(10);
mImageGenerator.setDatePosition(42);
mImageGenerator.setMonthPosition(14);
mImageGenerator.setDateColor(Color.parseColor("#009688"));
mImageGenerator.setMonthColor(Color.WHITE);
mImageGenerator.setStorageToSDCard(true);
mImageGenerator.setDateTypeFace("Roboto-Light.ttf");
mImageGenerator.setMonthTypeFace("Ubuntu-R.ttf");
// Pop up Date picker on pressing the editText
mDateEditText.setOnClickListener(setDate);
}
protected TableRow createNewRow(String credit, String debit) {
fab.callOnClick();
TableRow row = (TableRow) table.getChildAt(table.getEditableRow());
EditText creditEditable = row.findViewById(R.id.editCredit);
EditText debitEditable = row.findViewById(R.id.editDebit);
creditEditable.setText(credit);
debitEditable.setText(debit);
table.editableRowToView();
return row;
}
private void initViews() {
etPwd = (EditText)findViewById(R.id.pwd);
etNewPwd1 = (EditText)findViewById(R.id.newPwd1);
etNewPwd2 = (EditText)findViewById(R.id.newPwd2);
btnOK = (Button)findViewById(R.id.ok);
btnOK.setOnClickListener(this);
}
public void enDisPassword (boolean enable,String password) {
TextView t = (TextView)v.findViewById(R.id.cloud_password_label);
EditText e = (EditText)v.findViewById(R.id.cloud_password);
e.setEnabled(enable);
e.setText(password);
if (enable) {
t.setAlpha(1.0f);
e.setAlpha(1.0f);
}
else {
t.setAlpha(0.4f);
e.setAlpha(0.4f);
}
}
@Override
public void onWidgetClick(View view) {
switch (view.getId()) {
case R.id.btn_hide_soft_input:
KeyboardUtils.hideSoftInput(this);
break;
case R.id.btn_show_soft_input:
KeyboardUtils.showSoftInput((EditText) findViewById(R.id.et));
break;
case R.id.btn_toggle_soft_input:
KeyboardUtils.toggleSoftInput();
break;
}
}