Skip to content

Instantly share code, notes, and snippets.

@seongchan
Last active September 30, 2022 23:08
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seongchan/04f25d27d31a9e2ff393 to your computer and use it in GitHub Desktop.
Save seongchan/04f25d27d31a9e2ff393 to your computer and use it in GitHub Desktop.
(Android) EditText for Phone number style (XXX-XXXX-XXXX)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="@+id/phone_number"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:phoneNumber="true"
android:inputType="phone"
<!-- input string length for Koean phone number format. XXX-XXXX-XXXX -->
android:maxLength="13"/>
<Button
android:id="@+id/getNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/get_button"/>
<TextView
android:id="@+id/output_number"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/output_number_refinded"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
// impport, package name skipped...
public class EditTextPhoneNumberActivity extends Activity implements View.OnClickListener{
private EditText mPhoneNumber;
private TextView mOutputNumber;
private TextView mOutputNumber_refined;
private Button mBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPhoneNumber = (EditText)findViewById(R.id.phone_number);
mBtn = (Button)findViewById(R.id.getNumber);
mOutputNumber = (TextView)findViewById(R.id.output_number);
mOutputNumber_refined = (TextView)findViewById(R.id.output_number_refinded);
mPhoneNumber.addTextChangedListener(new PhoneNumberFormattingTextWatcher());
// mPhoneNumber.addTextChangedListener(new PhoneNumberFormattingTextWatcher("KR")); // API Level 21. Country Code
mBtn.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.getNumber :
String tmp = mPhoneNumber.getText().toString();
mOutputNumber.setText(tmp); // Edit Text Value ( -, dash included)
mOutputNumber_refined.setText(tmp.replace("-", "")); // split dash
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment