Keyboard mainactivity.this - android

I have three problems I want to learn how to make a customize keyboard and I found this site
http://www.fampennings.nl/maarten/android/09keyboard/index.htm
but there I have 3 problem about this keyboard.
First problem is that mainactivity isn't work at on key method unlike it was described.
private OnKeyboardActionListener mOnKeyboardActionListener = new OnKeyboardActionListener() {
#Override
public void onKey(int primaryCode, int[] keyCodes) {
// Get the EditText and its Editable
View focusCurrent = MainActivity.this.getWindow().getCurrentFocus();
if( focusCurrent==null || focusCurrent.getClass()!=EditText.class ) return;
EditText edittext = (EditText) focusCurrent;
Editable editable = edittext.getText();
other problem is that getSystemServise give error in Eclipse. I look to a lots of topic but every answers give different idea and I can't apply these ideas.
public void showCustomKeyboard( View v ) {
mKeyboardView.setVisibility(View.VISIBLE);
mKeyboardView.setEnabled(true);
if( v!=null ) ( (InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);
}
// getSystemService Gives eRror
an other problem is that registeredittext method it take int resid but there is findViewById give error like here.
public void registerEditText(int resid) {
// Find the EditText 'resid'
EditText edittext= (EditText)findViewById(resid); // gives error
// Make the custom keyboard appear
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {

Related

Android InputType not honored

I have a listview with an EditText in each row. The EditText is supposed to collect numeric values so I tried to keep the alpha keyboard off and allow the user to only see the numeric keypad.
What happens, though, is that when the listview is populated and I click on any EditText in the list, the numeric keyboard appears - but is then quickly replaced by the full qwerty keyboard - and the user must switch back to numeric to input numbers.
I've tried various combinations programmatically, like so:
mPercent.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
As well as multiple comnbinations of XML such as
android:inputType="phone"
or
android:digits="0123456789"
But, no matter the combination, they keyboard always rapidly switches back to qwerty and off the numeric keys.
I'm thinking it might be something with the TextWatcher. I use a textwatcher to indicate what has been typed. I remove it, add whatever text might be in that row's edittext and then add the textwatcher.
This is the guts of my custom adapter :
public View getView(final int position, View inView, ViewGroup parent) {
ViewHolder holder = null;
if (inView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inView = inflater.inflate(mLayoutResource, null);
holder = new ViewHolder();
holder.mPercent = (EditText) inView.findViewById(R.id.percent);
holder.mMaterial = (TextView) inView.findViewById(R.id.name);
inView.setTag(holder);
} else {
holder = (ViewHolder) inView.getTag();
}
mMaterial.moveToPosition(position);
holder.mPercent.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_NORMAL);
// remove textwatcher on percentage
holder.mPercent.removeTextChangedListener(percentWatcher);
// insert the percentage for this row
final String material = mMaterial.getString(mMaterial.getColumnIndex(OptionsProvider.OPTIONS_DATA));
final EditText percent = holder.mPercent;
percent.setTag(material); // use material and position as keys into which of the many edittexts the textwatcher is watching
percent.setId(position);
holder.mMaterial.setText(material);
// persist any text the user may have typed in the comment box
if (percentages.containsKey(material)) {
percent.setText(percentages.get(material));
}
else {
percent.setText("");
}
// turn on textwatcher
percentWatcher = new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// save this text and the position in which is resides.
// if the user scrolls before pressing send, only this position should
// contain the text
String text = percent.getText().toString().trim();
if (text.length() > 0) {
if ((position == percent.getId() &&
(material.equals( percent.getTag().toString())))) {
percentages.put(material, text);
Log.d(TAG, "Percentage inserted "+material+"="+text);
}
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
// force the EditText to stay with 3 digits (max of 100%)
#Override
public void afterTextChanged(Editable s) {
if (s.length() > 0) {
int pct = Integer.parseInt(s.toString());
Log.d(TAG, " Material "+(String) percent.getTag()+ " = "+pct);
}
}
};
// add the textwatcher back to the edittext
holder.mPercent.addTextChangedListener(percentWatcher);
Anyone know if removing/adding a textwatcher corrupts the InputType? Is this a path I should explore to figure out why the keyboard always goes back to qwerty?
Might be that the ListView steals the focus. Try to add this your ListView
XML
android:descendantFocusability="afterDescendants"
Or in Java
listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

how to set action listener to popup keyboard in my custom keyboard...

my key code in a row
<Key android:codes="49" android:keyLabel="1" android:verticalGap="2%p" android:popupKeyboard="#xml/popupview" android:popupCharacters="wW" android:keyEdgeFlags="left"/>
it show a popup window with 'w' and 'W' and a cross button when long press on '1'. but there is no action listener added to those character. If i click 'w' nothing happen but cross button works. But how can i add action listener to this character. thanks in advance :)
You should first take a look here and here . And this is full running sample. just copy it one by one and you are done.
Read this tutorial: Creating an Input Method
clone this repo: LatinIME
And some links
How to make a Android custom keyboard?
Android custom keyboard xml file
https://android.googlesource.com/platform/packages/inputmethods/LatinIME/+/3a2896c80475094f751ef447fc9c97028bfc2265/java/src/com/android/inputmethod/latin/LatinKeyboard.java
https://gitorious.org/rowboat/packages-inputmethods-latinime/source/f02964264f196447b03a88591a2964b67c318718:java/src/com/android/inputmethod/latin/LatinKeyboard.java
And you can also search for Softkeyboard Android Sample at Android Developer Site.
My Solution:
OnCreate:
mKeyboardView.setOnKeyboardActionListener(new ActionListener(
Activity.this,edittext, mKeyboardView));
public class BasicOnKeyboardActionListener implements KeyboardView.OnKeyboardActionListener {
EditText editText;
CustomKeyboardView displayKeyboardView;
private Activity mTargetActivity;
public ActionListener(Activity targetActivity, EditText editText,
CustomKeyboardView
displayKeyboardView) {
mTargetActivity = targetActivity;
this.editText = editText;
this.displayKeyboardView = displayKeyboardView;
}
#Override
public void onText(CharSequence text) {
int cursorPosition = editText.getSelectionEnd();
String previousText = editText.getText().toString();
String before, after;
if (cursorPosition < previousText.length()) {
before = previousText.substring(0, cursorPosition);
after = previousText.substring(cursorPosition);
} else {
before = previousText;
after = "";
}
editText.setText(before + text + after);
editText.setSelection(cursorPosition + 1);
}
#Override
public void onKey(int primaryCode, int[] keyCodes) {
switch (primaryCode) {
case xx:// xx is primaryCode that is given program for pressed key
onText("C");// C is char what you want to write
default:
break;
}
}
}

EditText in ListView hidden by keyboard when focused

I have a ListView containing rows with EditText's.
When I click on an EditText and it's not already focused it receives focus, the keyboard appears and the EditText is moved above the CandidateView (desired behaviour).
However when I make a key press, the EditText maintains focus and receives the input but moves down and is obscured by the keyboard (the previous movement is reversed).
When I click on the EditText when it is already selected without the keyboard shown, the keyboard pops up but the EditText is not moved to the right position (above the CandidateView). It still receives the input.
I add a header view containing EditText's and there everything works correctly.
This is the code of my ArrayAdapter where the row view is created:
View view = inflater.inflate(R.layout.row_profile_entry_text, null);
final String question = getItem(position);
TextView textViewQuestion = (TextView) view.findViewById(R.id.rpeq_TextViewQuestion);
textViewQuestion.setText(question);
final EditText editTextAnswer = (EditText) view.findViewById(R.id.rpeq_EditTextAnswer);
editTextAnswer.addTextChangedListener(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) {
mAnswers.put(question, s.toString());
}
});
if (mAnswers.containsKey(question)) {
editTextAnswer.setText(mAnswers.get(question));
}
return view;
I would also like to emphasize that I already added
android:windowSoftInputMode="adjustPan" to the Manifest and android:descendantFocusability="beforeDescendants" to the ListView as most of the answers to other questions suggest.
Without adjustPan the EditText is not able to receive focus at all but it does not solve the issue entirely.
Does someone have an idea what I am doing wrong?
Try this:
<activity name="YourActivity"
android:windowSoftInputMode="stateVisible|adjustResize|adjustPan">
</activity>
in the manifest file.
Most probably, adjustResize must work, if you are using a ScrollView.
after many hours spent on this problem this is my solution (for Android < 4.2):
1) Manifest => android:windowSoftInputMode="adjustPan"
2) Activity=> create OnTouchListner and pass to Adapter
private OnTouchListener exampleOnTouchListener = new OnTouchListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEvent.ACTION_UP == event.getAction()) {
int position = (Integer) v.getTag();
myListView.setSelection(position);
}
return false;
}
};
3) Adapter
if (exampleOnTouchListener!= null) {
myEditText.setTag(position);
myEditText.setOnTouchListener(exampleOnTouchListener);
// if last element set padding bottom for spacing
if (position == items.size() - 1) {
LinearLayout myLinearLayout = (LinearLayout) convertView
.findViewById(R.id.ticketcontolProposedRealvalueLinearLayout);
myLinearLayout.setPadding(0, 0, 0,SET_PADDING_BOTTOM);
}
}

EditText setError() with icon but without Popup message

I want to to have some validation for my EditText wherein I want to show "" icon (that comes when you put editText.setError("blah blah")) but don't want the text in the popup displaying that "blah blah".
Is there any way to do it? One way is to create a custom layout which will show the image icon in the EditText. But is there any better solution?
Problem solved after a lot of research and permutations- (Also thanks to #van)
Create a new class that will extend EditText something like this-
public class MyEditText extends EditText {
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
}
Use this class as a view in your xml like this-
<com.raj.poc.MyEditText
android:id="#+id/et_test"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
Now in the third step, just set a TextWatcher to your custom text view like this-
et = (MyEditText) findViewById(R.id.et_test);
errorIcon = getResources().getDrawable(R.drawable.ic_error);
errorIcon.setBounds(new Rect(0, 0, errorIcon.getIntrinsicWidth(), errorIcon.getIntrinsicHeight()));
et.setError(null,errorIcon);
et.addTextChangedListener(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) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
if(s.toString().length()>6){
et.setError("", null);
}else{
et.setError("", errorIcon);
}
}
});
where R.drawable.ic_error =
Keeping text null solves the problem
But if we keep only null in setError(null), this won't show the validation error; it should be null along with second param.
You dont need to create a new EditText class or change xml. The solution is very simple:
Edittext editText= (EditText) rootView.findViewById(R.id.email);
String str= editText.getText().toString();
if(str.equalsIgnoreCase("") ){
Drawable dr = getResources().getDrawable(R.drawable.error);
//add an error icon to yur drawable files
dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
editText.setCompoundDrawables(null,null,dr,null);
}
Sorry Rajkiran, but your solution is not working on Android 4.2 version. If I am trying to set null value for error, it is not even displayed. The solution I came up was to extend EditText and override setError method. No I have only error indicator without popup.
#Override
public void setError(CharSequence pError, Drawable pIcon) {
setCompoundDrawables(null, null, pIcon, null);
}
I have been dealing with the same problem. I wanted to use .setError() to my EditText when user insert null input. But I think the pop-out message is annoying, especially when you have more EditTexts.
My solution was naive and simple, but it worked on all devices I've tried so far.
I created my own class myEditText and just #Override this method:
#Override
public void setError(CharSequence error, Drawable icon) {
setCompoundDrawables(null, null, icon, null);
}
then use in layout.xml
<cz.project.myEditText
...
/>
and finally in my code
I put onFocusChangeListener to myEditText, so when someone clicks-in, the icon disappears.
myEditText input = (myEditText) findViewById(R.id.input);
input.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
input.setError(null);
});
if(val == null) input.setError("");
It works Exactly how I want = no pop-up message when .setError() is called on EditText.
To get only the error-icon without an error-message-popup only when setError("") is called (i.e. set an empty String as error-message) I use a custom EditText-class where I override setError(CharSequence, Drawable) like this:
#Override
public void setError(CharSequence error, Drawable icon) {
if (error == null) {
super.setError(null, icon);
setCompoundDrawables(null, null, null, null);
}
else if (error.toString().equals("")) setCompoundDrawables(null, null, icon, null);
else super.setError(error, icon);
}
Everything else stays the same:
Use setError(null) to get neither the icon nor the message-popup.
Use setError(errorMessage), where errorMessage is a String with length 1 at least, to get the icon and message-popup.
This is the very useful when you want to show the error messages for the edittext field when the user enter wrong information.this is very simply program only you have to use serError() method in the edittext.
Step 1:
Create button and implement onclickListener.
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
Step 2:
Validate the input fields and set the error in the input field.
if(edName.length()>3){
if(edNumber.length()>3){
Toast.makeText(getApplicationContext(), "Login success", Toast.LENGTH_SHORT).show();
}else{
edNumber.setError("Number Mininum length is 4");
}
}else{
edName.setError("Name Mininum length is 4");
}
Refer this link for more:http://velmuruganandroidcoding.blogspot.in/2014/08/set-error-message-in-edittext-android.html

Make EditText ReadOnly

I want to make a read-only EditText view. The XML to do this code seems to be android:editable="false", but I want to do this in code.
How can I do this?
Please use this code..
Edittext.setEnabled(false);
If you setEnabled(false) then your editText would look disabled (gray, etc). You may not want to change the visual aspect of your editor.
A less intrusive way would be to use setFocusable(false).
I believe that this answers your question closer to your initial intent.
In XML use:
android:editable="false"
As an example:
<EditText
android:id="#+id/EditText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:editable="false" />
This works for me:
EditText.setKeyListener(null);
editText.setInputType(InputType.TYPE_NULL);
As per the docs this prevents the soft keyboard from being displayed. It also prevents pasting, allows scrolling and doesn't alter the visual aspect of the view. However, this also prevents selecting and copying of the text within the view.
From my tests setting setInputType to TYPE_NULL seems to be functionally equivalent to the depreciated android:editable="false". Additionally, android:inputType="none" seems to have no noticeable effect.
android:editable="false" has been deprecated. Therefore you cant use it to make the edit text readonly.
I have done this using the bellow solution. Here I have used
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
Give it try :)
<EditText
android:id="#+id/et_newsgpa_university"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:hint="#string/hint_educational_institute"
android:textSize="#dimen/regular_text"
android:inputType="none"
android:textIsSelectable="true"
android:focusable="false"
android:maxLines="1"
android:imeOptions="actionNext"/>
The best is by using TextView instead.
editText.setEnabled(false);
editText.setFilters(new InputFilter[] { new InputFilter() {
public CharSequence filter(CharSequence src, int start, int end,
Spanned dst, int dstart, int dend) {
return src.length() < 1 ? dst.subSequence(dstart, dend) : "";
}
} });
This will give you uneditable EditText filter. you first need to put the text you want on the editText field and then apply this filter.
writing this two line is more than enough for your work.
yourEditText.setKeyListener(null);
yourEditText.setEnabled(false);
set in XML
android:inputType="none"
Try using
editText.setEnabled(false);
editText.setClickable(false);
Try overriding the onLongClick listener of the edit text to remove context menu:
EditText myTextField = (EditText)findViewById(R.id.my_edit_text_id);
myTextField.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
return true;
}
});
android:editable
If set, specifies that this TextView has an input method. It will be a textual one unless it has otherwise been specified. For TextView, this is false by default. For EditText, it is true by default.
Must be a boolean value, either true or false.
This may also be a reference to a resource (in the form #[package:]type:name) or theme attribute (in the form ?[package:][type:]name) containing a value of this type.
This corresponds to the global attribute resource symbol editable.
Related Methods
If you just want to be able to copy text from the control but not be able to edit it you might want to use a TextView instead and set text is selectable.
code:
myTextView.setTextIsSelectable(true);
myTextView.setFocusable(true);
myTextView.setFocusableInTouchMode(true);
// myTextView.setSelectAllOnFocus(true);
xml:
<TextView
android:textIsSelectable="true"
android:focusable="true"
android:focusableInTouchMode="true"
...
/>
<!--android:selectAllOnFocus="true"-->
The documentation of setTextIsSelectable says:
When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value...
However I had to explicitly set focusable and focusableInTouchMode to true to make it work with touch input.
Use this code:
editText.setEnabled(false);
editText.setTextColor(ContextCompat.getColor(context, R.color.black);
Disabling editText gives a read-only look and behavior but also changes the text-color to gray so setting its text color is needed.
this is my implementation (a little long, but useful to me!):
With this code you can make EditView Read-only or Normal. even in read-only state, the text can be copied by user. you can change the backgroud to make it look different from a normal EditText.
public static TextWatcher setReadOnly(final EditText edt, final boolean readOnlyState, TextWatcher remove) {
edt.setCursorVisible(!readOnlyState);
TextWatcher tw = null;
final String text = edt.getText().toString();
if (readOnlyState) {
tw = new TextWatcher();
#Override
public void afterTextChanged(Editable s) {
}
#Override
//saving the text before change
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
// and replace it with content if it is about to change
public void onTextChanged(CharSequence s, int start,int before, int count) {
edt.removeTextChangedListener(this);
edt.setText(text);
edt.addTextChangedListener(this);
}
};
edt.addTextChangedListener(tw);
return tw;
} else {
edt.removeTextChangedListener(remove);
return remove;
}
}
the benefit of this code is that, the EditText is displayed as normal EditText but the content is not changeable. The return value should be kept as a variable to one be able revert back from read-only state to normal.
to make an EditText read-only, just put it as:
TextWatcher tw = setReadOnly(editText, true, null);
and to make it normal use tw from previous statement:
setReadOnly(editText, false, tw);
This worked for me, taking several of the suggestions above into account. Makes the TextEdit focusable, but if user clicks or focuses, we show a list of selections in a PopupWindow. (We are replacing the wacky Spinner widget). TextEdit xml is very generic...
public void onCreate(Bundle savedInstanceState) {
....
fEditState = (EditText) findViewById(R.id.state_edit);
fEditState.setLongClickable(false);
fEditState.setKeyListener(null);
fEditState.setFocusable(true);
fEditState.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus)
{
if (hasFocus)
{
showStatesPopup();
}
}
});
fEditState.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0)
{
showStatesPopup();
}
});
....
}
private void showStatesPopup()
{
// fPopupWindowStates instantiated in OnCreate()
if (!fPopupWindowStates.isShowing()) {
// show the list view as dropdown
fPopupWindowStates.showAsDropDown(fEditState, -5, 0);
}
}
This was the only full simple solution for me.
editText.setEnabled(false); // Prevents data entry
editText.setFocusable(false); // Prevents being able to tab to it from keyboard
As android:editable="" is deprecated,
Setting
android:clickable="false"
android:focusable="false"
android:inputType="none"
android:cursorVisible="false"
will make it "read-only". However, users will still be able to paste into the field or perform any other long click actions. To disable this, simply override onLongClickListener().
In Kotlin:
myEditText.setOnLongClickListener { true }
suffices.
My approach to this has been creating a custom TextWatcher class as follows:
class ReadOnlyTextWatcher implements TextWatcher {
private final EditText textEdit;
private String originalText;
private boolean mustUndo = true;
public ReadOnlyTextWatcher(EditText textEdit) {
this.textEdit = textEdit;
}
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
if (mustUndo) {
originalText = charSequence.toString();
}
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void afterTextChanged(Editable editable) {
if (mustUndo) {
mustUndo = false;
textEdit.setText(originalText);
} else {
mustUndo = true;
}
}
}
Then you just add that watcher to any field you want to be read only despite being enabled:
editText.addTextChangedListener(new ReadOnlyTextWatcher(editText));
I had no problem making EditTextPreference read-only, by using:
editTextPref.setSelectable(false);
This works well when coupled with using the 'summary' field to display read-only fields (useful for displaying account info, for example). Updating the summary fields dynamically snatched from http://gmariotti.blogspot.com/2013/01/preferenceactivity-preferencefragment.html
private static final List<String> keyList;
static {
keyList = new ArrayList<String>();
keyList.add("field1");
keyList.add("field2");
keyList.add("field3");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
for(int i=0;i<getPreferenceScreen().getPreferenceCount();i++){
initSummary(getPreferenceScreen().getPreference(i));
}
}
private void initSummary(Preference p) {
if (p instanceof PreferenceCategory) {
PreferenceCategory pCat = (PreferenceCategory) p;
for (int i = 0; i < pCat.getPreferenceCount(); i++) {
initSummary(pCat.getPreference(i));
}
} else {
updatePrefSummary(p);
}
}
private void updatePrefSummary(Preference p) {
if (p instanceof ListPreference) {
ListPreference listPref = (ListPreference) p;
p.setSummary(listPref.getEntry());
}
if (p instanceof EditTextPreference) {
EditTextPreference editTextPref = (EditTextPreference) p;
//editTextPref.setEnabled(false); // this can be used to 'gray out' as well
editTextPref.setSelectable(false);
if (keyList.contains(p.getKey())) {
p.setSummary(editTextPref.getText());
}
}
}
Set this in EdiTextView xml file
android:focusable="false"
in java file:
Edittext.setEnabled(false);
in xml file:
android:editable="false"
These 2 lines makes ur edittext selectable and at the same time not editable (it doesn't even show the soft keyboard):
editText.setInputType(InputType.TYPE_NULL);
editText.setTextIsSelectable(true);

Categories

Resources