Android edittext布局文件如下:
<EditText
android:id="@+id/et_change"
android:layout_width="match_parent"
android:layout_height="50dp"
android:hint="@string/PleaseInputWidth"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:inputType="numberDecimal">
</EditText>
因为输入类型为numberDecimal,当仅输入“.”时,该语句width= Float.parseFloat(editText.getText().toString());会报错,提示“”不能转为float,可以进行如下修改,当只输入“.”时,自动补充为“0.”
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText etChange;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etChange = findViewById(R.id.et_change);
etChange.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// No need to implement
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// No need to implement
}
@Override
public void afterTextChanged(Editable s) {
if (s == null || s.length() == 0) {
return;
}
if (s.toString().equals(".")) {
etChange.setText("0.");
etChange.setSelection(etChange.getText().length());
}
if (s.toString().startsWith(".")) {
etChange.setText("0" + s.toString());
etChange.setSelection(etChange.getText().length() - 1);
}
}
});
}
}