我怀疑这是一个相当简单的概念,但我还没有设法在互联网上找到答案。如何从EditText创建自定义控件?
我创建了格式化使用TextWatcher一个EditText内输入一个主要活动:
public class MainActivity extends Activity implements TextWatcher {
EditText text;
int textCount;
String numba1, numba, n;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (EditText)findViewById(R.id.editText1);
text.addTextChangedListener(this);
}
/* TextWatcher Implementation Methods */
public void beforeTextChanged(CharSequence s, int arg1, int arg2, int after) {
// Does Nothing
}
public void onTextChanged(CharSequence s, int start, int before, int end) {
//Does random stuff with text
}
public void afterTextChanged(Editable s) {
//Does much more random stuff with text
}
protected void onResume() {
super.onResume();
SharedPreferences prefs = getPreferences(0);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
text.setText(restoredText, TextView.BufferType.EDITABLE);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);
if (selectionStart != -1 && selectionEnd != -1) {
text.setSelection(selectionStart, selectionEnd);
}
}
}
protected void onPause() {
super.onPause();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putString("text", text.getText().toString());
editor.putInt("selection-start", text.getSelectionStart());
editor.putInt("selection-end", text.getSelectionEnd());
editor.commit();
}
接下来,我想重用我的项目好几次,所以想创建一个自定义的EditText控制,这看起来就像原来的一样,但是会完成所有格式并保存偏好。
理想我想能够只使用XML自定义的EditText出现:
<view
class="com.android.example.myEditText"
id="@+id/editText" />
我读过Android's Custom Components教程,但它主要是要改变的,而不是他们的行为组件的前景,会谈,所以我不愿意使用画布。
那么,我该如何做到这一点?
非常感谢你。但是,当我这样做时,'onCreate','onPause'和'onResume'似乎抱怨未被定义为'EditText'。我错过了明显的东西吗?另外,在示例API中,他们似乎使用Intents很多。我的代码会受益于他们吗? – 2012-08-02 05:09:47
当您通过使用'findViewById'使用'MyEditText'(或任何您命名您的类)而不是'EditText'来声明控件的引用或检索其引用时。希望解决你提到的未定义的EditText – 2012-08-02 06:02:53