Hot questions for Using Android EditText in layout

Question:

I am using appcompat v7 to get the look consistent on Android 5 and less. It works rather well. However I cannot figure out how to change the bottom line color and the accent color for EditTexts. Is it possible?

I have tried to define a custom android:editTextStyle (cf. below) but I only succeeded to change the full background color or text color but not the bottom line nor the accent color. Is there a specific property value to use? do I have to use a custom drawable image through the android:background property? is it not possible to specify a color in hexa?

 <style name="Theme.App.Base" parent="Theme.AppCompat.Light.DarkActionBar">
     <item name="android:editTextStyle">@style/Widget.App.EditText</item>
 </style>

 <style name="Widget.App.EditText" parent="Widget.AppCompat.EditText">
     ???
 </style>

According to android API 21 sources, EditTexts with material design seem to use colorControlActivated and colorControlNormal. Therefore, I have tried to override these properties in the previous style definition but it has no effect. Probably appcompat does not use it. Unfortunately, I cannot find the sources for the last version of appcompat with material design.


Answer:

Finally, I have found a solution. It simply consists of overriding the value for colorControlActivated, colorControlHighlight and colorControlNormal in your app theme definition and not your edittext style. Then, think to use this theme for whatever activity you desire. Below is an example:

<style name="Theme.App.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorControlNormal">#c5c5c5</item>
    <item name="colorControlActivated">@color/accent</item>
    <item name="colorControlHighlight">@color/accent</item>
</style>

Question:

I am running into an issue that I can't figure out. I wrote a simple custom IME keyboard based on this sample.

It basically has two custom keyboards, one for letters and one for numbers. They use different layouts.

However, when I add two EditText controls one for text and one for numbers, the keyboard does not refresh to the type it belongs. What I mean is that if I select the EditText with inputType="text" first, the QWERTY keyboard layout comes up. But then when I select the second EditText with inputType="number" the QWERTY keyboard shows up again. However it is supposed to load a different layout for numbers that is wired into the code.

In other words, here's the test activity layout:

Now if I select the "Text" field, the QWERTY keyboard comes up as below:

However, if I select the "Number" filed, the QWERTY keyboard still shows up which is wrong.

The expected behavior would be this keyboard to show up.

Here's the code for the CustomIME and I tried to use postInvalidate() on the view, pre-load all layouts during onInitializeInterface() but nothing worked. It never switches to the number's layout properly

public class CustomIME extends InputMethodService
        implements KeyboardView.OnKeyboardActionListener {

    public static final String CUSTOM_IME = "CUSTOM_IME";
    private KeyboardView mKeyboardView;
    private Keyboard mKeyboardCurrent;
    private KeyboardType mKeyboardTypeCurrent = KeyboardType.QWERTY_LETTERS;
    private boolean mCAPs = false;


    enum KeyboardType {
        QWERTY_LETTERS,
        NUMBERS
    }

    @Override
    public View onCreateInputView() {
        loadCurrentKeyboard();
        mKeyboardView = (KeyboardView) getLayoutInflater().inflate(R.layout.custom_ime_keyboard, null);
        mKeyboardView.setBackgroundResource(R.drawable.btn_gradient);
        mKeyboardView.setOnKeyboardActionListener(this);

        if (mKeyboardCurrent != null) {
            mKeyboardView.setKeyboard(mKeyboardCurrent);
        }

        return mKeyboardView;
    }

    @Override
    public void onInitializeInterface() {
        // tried loading everything here but did not make a difference
    }

    private void loadCurrentKeyboard() {
        if (mKeyboardTypeCurrent == KeyboardType.QWERTY_LETTERS) {
            mKeyboardCurrent = new Keyboard(getApplicationContext(), R.xml.custom_ime_qwerty);
        } else if (mKeyboardTypeCurrent == KeyboardType.NUMBERS) {
            mKeyboardCurrent = new Keyboard(getApplicationContext(), R.xml.custom_ime_number);
        } else {
            Log.e(CUSTOM_IME, "Invalid keyboard type");
        }
    }

    @Override
    public void onStartInput(EditorInfo attribute, boolean restarting) {
        super.onStartInput(attribute, restarting);
        switch (attribute.inputType & InputType.TYPE_MASK_CLASS) {
            case InputType.TYPE_CLASS_NUMBER:
                boolean signed = (attribute.inputType & InputType.TYPE_NUMBER_FLAG_SIGNED) != 0;
                boolean decimal = (attribute.inputType & InputType.TYPE_NUMBER_FLAG_DECIMAL) != 0;

                // set default
                mKeyboardTypeCurrent = KeyboardType.QWERTY_LETTERS;
                if (!signed && !decimal) {
                    mKeyboardTypeCurrent = KeyboardType.NUMBERS;
                }
                break;
            case InputType.TYPE_CLASS_TEXT:
            default:
                mKeyboardTypeCurrent = KeyboardType.QWERTY_LETTERS;
        }

        // This did not make a difference
        if (mKeyboardView != null) {
            mKeyboardView.postInvalidate();
        }
    }

    @Override
    public void onKey(int primaryCode, int[] keyCodes) {
        InputConnection inputConnection = getCurrentInputConnection();
        switch (primaryCode) {
            default:
                char asciiCode = (char) primaryCode;
                if (Character.isLetter(asciiCode) && mCAPs) {
                    asciiCode = Character.toUpperCase(asciiCode);
                }
                inputConnection.commitText(String.valueOf(asciiCode), 1);
        }
    }
}

And the layouts:

custom_ime_keyboard.xml:

<?xml version="1.0" encoding="UTF-8"?>
<android.inputmethodservice.KeyboardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/custom_ime_keyboard_id1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:keyPreviewLayout="@layout/custom_ime_preview" />

activity_main.xml

<LinearLayout
    android:id="@+id/layout1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_margin="10dp"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/edit1"
        android:layout_width="100dp"
        android:layout_height="60dp"
        android:inputType="text"
        android:hint="Text"
        android:padding="10dp"
        android:textSize="12sp" />

    <EditText
        android:id="@+id/edit2"
        android:layout_width="100dp"
        android:layout_height="60dp"
        android:hint="Number"
        android:inputType="number"
        android:padding="10dp"
        android:textSize="12sp" />
</LinearLayout>

Finally the keyboard layouts (custom_ime_qwerty.xml, and custom_ime_number.xml).

<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyHeight="64dp"
    android:keyWidth="9%p">
    <!--1st row-->
    <Row android:rowEdgeFlags="top">
        <Key
            android:codes="113"
            android:keyEdgeFlags="left"
            android:keyLabel="q" />
        <Key
            android:codes="119"
            android:keyLabel="w" />
        <Key
            android:codes="101"
            android:keyLabel="e" />
        <Key
            android:codes="114"
            android:keyLabel="r" />
        etc...


<Keyboard xmlns:android="http://schemas.android.com/apk/res/android"
    android:keyHeight="64dp"
    android:keyWidth="20%p"
    android:label="number"
    android:verticalGap="0px">
    <!--1st row-->
    <Row android:rowEdgeFlags="top">
        <Key
            android:codes="49"
            android:keyEdgeFlags="left"
            android:keyLabel="1" />
        <Key
            android:codes="50"
            android:keyLabel="2" />
        <Key
            android:codes="51"
            android:keyLabel="3" />

Answer:

I think onStartInputView() is the callback you need to obtain:

Called when the input view is being shown and input has started on a new editor. This will always be called after onStartInput(EditorInfo, boolean), allowing you to do your general setup there and just view-specific setup here. You are guaranteed that onCreateInputView() will have been called some time before this function is called.

So, you get to know what exact input type to show in onStartInput(), but the actual place to perform switching to this new keyboard type should be onStartInputView().

See how the sample SoftKeyboard application handles that functionality.



@Override public void onStartInput(EditorInfo attribute, boolean restarting) {
    super.onStartInput(attribute, restarting);

    ...

    // We are now going to initialize our state based on the type of
    // text being edited.
    switch (attribute.inputType & InputType.TYPE_MASK_CLASS) {
        case InputType.TYPE_CLASS_NUMBER:
        case InputType.TYPE_CLASS_DATETIME:
            mCurKeyboard = mSymbolsKeyboard;
            break;

        case InputType.TYPE_CLASS_PHONE:
            mCurKeyboard = mSymbolsKeyboard;
            break;

        case InputType.TYPE_CLASS_TEXT:
            mCurKeyboard = mQwertyKeyboard;
            ...
            break;

        default:
            // For all unknown input types, default to the alphabetic
            // keyboard with no special features.
            mCurKeyboard = mQwertyKeyboard;
    }

}

@Override public void onStartInputView(EditorInfo attribute, boolean restarting) {
    super.onStartInputView(attribute, restarting);
    // Apply the selected keyboard to the input view.
    setLatinKeyboard(mCurKeyboard);
    ...
}

private void setLatinKeyboard(LatinKeyboard nextKeyboard) {
    final boolean shouldSupportLanguageSwitchKey =
            mInputMethodManager.shouldOfferSwitchingToNextInputMethod(getToken());
    nextKeyboard.setLanguageSwitchKeyVisibility(shouldSupportLanguageSwitchKey);
    mInputView.setKeyboard(nextKeyboard);
}


Question:

I have an edittext enclosed within a textinputlayout from the support library and I'm finding it impossible to make the hint appear in the center of the field. I've tried all the usual tricks to be found in other stackoverflow discussions, as you can see from the code sample, but the hint still stubbornly appears on the left of the edittext. How can I solve this?

Please don't suggest using paddingLeft or paddingStart to do this - I want something that's going to work cleanly across different devices so it has to be a straight solution rather than a workaround.

Just to be clear: If I remove the textinputlayout then the hint is properly centered. It's the textinputlayout that's causing the problem here.

<android.support.design.widget.TextInputLayout
        android:id="@+id/someId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="30dp"
        android:layout_marginStart="30dp"
        android:layout_marginRight="30dp"
        android:layout_marginEnd="30dp"
        android:layout_marginTop="10dp"
        android:gravity="center"
        android:ellipsize="start"
        android:maxLines="1"
        android:inputType="textPersonName"
        >

    <EditText
        android:id="@+id/someId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:hint="@string/somehint"
        android:textColorHint="@color/somecolor"
        android:textSize="20sp"
        android:textColor="@android:color/black"
        android:background="@android:color/white"
        android:cursorVisible="true"
        android:textCursorDrawable="@null"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:inputType="textPersonName"
        android:maxLines="1"
        android:ellipsize="start"
        />

</android.support.design.widget.TextInputLayout>

Using the latest version of the support library:

    compile 'com.android.support:design:22.2.1'

Edit - things I've tried to resolve this:

1) replacing Edittext with android.support.v7.widget.AppCompatEditText - doesn't work

2) using app:hintTextAppearance="@style/TextAppearance.AppCompat" inside the textinputlayout - doesn't work

3) Instead of defining the hint in the edittext, setting the hint programmatically using textinputlayout.sethint inside the activity - doesn't work: the hint appears on the left.

4) Setting the hint on the edittext in onActivityCreated. This appeared to work initially, but I discovered that although the hint appears centered the functionality of inputtextlayout becomes broken and clicking on the edittext no longer performs the hint animation.


Answer:

There doesn't seem to be a way to do this (at least not that I can find). As a workaround I tried using the MaterialEdittext 3rd party library - also not ideal since although the small animated hint is centered, it appears inside the text box instead of outside it:

https://github.com/rengwuxian/MaterialEditText

Question:

Always getting this warning TextInputLayout: EditText added is not a TextInputEditText. Please switch to using that class instead. and not finishing Activity for First time. On Second time not getting an warning and activity finishing perfectly.

activity_login.xml

<LinearLayout
        android:id="@+id/ll_login_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:gravity="center_horizontal"
        android:orientation="vertical"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        android:visibility="visible">


        <android.support.design.widget.TextInputLayout
            android:id="@+id/email_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="16dp"
            android:hint="@string/email_phone"
            android:paddingTop="48dp">

            <android.support.v7.widget.AppCompatEditText
                android:id="@+id/et_email"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:inputType="textEmailAddress"
                android:paddingEnd="0dp"
                android:paddingStart="8dp" />

        </android.support.design.widget.TextInputLayout>

        <android.support.design.widget.TextInputLayout
            android:id="@+id/password_field"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/password"
            android:paddingBottom="16dp">

            <android.support.v7.widget.AppCompatEditText
                android:id="@+id/et_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:inputType="textPassword"
                android:paddingEnd="0dp"
                android:paddingStart="8dp" />

        </android.support.design.widget.TextInputLayout>


        <Button
            android:id="@+id/btn_login"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="@dimen/button_login_social_margin"
            android:layout_marginStart="@dimen/button_login_social_margin"
            android:layout_marginBottom="@dimen/activity_vertical_margin"
            android:text="@string/login"
            android:textColor="@android:color/black" />

    </LinearLayout>

LoginActivity.java

    public class LoginActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        final AppCompatEditText etEmailOrPh = (AppCompatEditText) findViewById(R.id.et_email);
        final AppCompatEditText etPassword = (AppCompatEditText) findViewById(R.id.et_password);
        final Button btnLogin = (Button) findViewById(R.id.btn_login);

        assert etEmailOrPh != null;
        assert etPassword != null;
        assert  btnLogin != null;

        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String emailOrPhone = etEmailOrPh.getText().toString().trim();
                String password = etPassword.getText().toString().trim();

                if(emailOrPhone.isEmpty()){
                    etEmailOrPh.setError(getResources().getString(R.string.email_phone_mandatory));
                    etEmailOrPh.requestFocus();
                } else if(emailOrPhone.contains("@") && CommonUtil.isValidEmail(emailOrPhone)) {
                    etEmailOrPh.setError(getResources().getString(R.string.email_error));
                    etEmailOrPh.requestFocus();
                } else if(password.isEmpty()) {
                    etPassword.setError(getResources().getString(R.string.password_mandatory));
                    etPassword.requestFocus();
                } else {
                    SharedPreferences cache = LoginActivity.this.getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);
                    final SharedPreferences.Editor preferenceEditor = cache.edit();
                    preferenceEditor.putInt(Constants.SHARED_PREF_ITEM_USER_ID, 1);
                    preferenceEditor.apply();
                    setResult(RESULT_OK);
                    finish();
                }
            }
        });

    }
}


Answer:

Change this EditText

android.support.v7.widget.AppCompatEditText

to this

android.support.design.widget.TextInputEditText

Full Code :

<android.support.design.widget.TextInputLayout
       android:id="@+id/email_field"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:paddingBottom="16dp"
       android:hint="@string/email_phone"
       android:paddingTop="48dp">

    <android.support.design.widget.TextInputEditText
            android:id="@+id/et_email"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:inputType="textEmailAddress"
            android:paddingEnd="0dp"
            android:paddingStart="8dp"
        />
</android.support.design.widget.TextInputLayout>

Question:

I'm stuck trying to add an editText field dynamically under my existing editText fields using a button. Currently pressing the button does nothing. Here is my code:

XML:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#d4cfcd">
tools:context="com.zdowning.decisionmaker.MainActivity">


<LinearLayout
    android:id="@+id/linearLayoutMain"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:gravity="center"
        android:hint="Enter Your Question Here"
        android:layout_marginBottom="20dp"
        android:layout_marginTop="20dp"/>

    <LinearLayout
        android:id="@+id/linearLayoutDecisions"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <EditText
        android:id="@+id/editText3"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:gravity="center"
        android:hint="Enter Answer #2" />

    <EditText
        android:id="@+id/editText2"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:gravity="center"
        android:hint="Enter Answer #1" />

    <EditText
        android:id="@+id/editText4"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:gravity="center"
        android:hint="Enter Answer #3" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:gravity="center">

        <Button
            android:id="@+id/add_button"
            style="?android:attr/borderlessButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:text="+"
            android:textColor="@android:color/background_light"
            android:textSize="18sp"/>

        <View
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:layout_weight="1" />

        <Button
            android:id="@+id/remove_button"
            style="?android:attr/borderlessButtonStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:text="-"
            android:textColor="@android:color/background_light"
            android:textSize="18sp"
            android:layout_margin="10dp"/>
    </LinearLayout>

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    <Button
        android:id="@+id/button"
        style="?android:attr/borderlessButtonStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        android:text="DECIDE!"
        android:textColor="@android:color/background_light"
        android:textSize="18sp"
        android:layout_centerInParent="true" />
    </RelativeLayout>

    <TextView
        android:id="@+id/textView7"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_margin="20dp"
        android:textColor="@android:color/black"
        android:textSize="36sp" />

</LinearLayout>

Java:

package com.zdowning.decisionmaker;

import android.graphics.Typeface;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.ScrollView;

import java.lang.*;

import static com.zdowning.decisionmaker.R.layout.activity_main;

public class MainActivity extends AppCompatActivity {
public int numberOfLines = 3;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    setContentView(activity_main);
    final Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             getAnswer();
        }
    });

    final Button Add_button = (Button) findViewById(R.id.add_button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Add_Line();
        }
    });
}


public void Add_Line() {
    LinearLayout ll = (LinearLayout) 
    findViewById(R.id.linearLayoutDecisions);

    // add edittext
    EditText et = new EditText(this);
    et.setId(numberOfLines + 1);
    ll.addView(et);
    numberOfLines++;
}


public void getAnswer() {
    String[] options = new String[3];

    EditText text = (EditText)findViewById(R.id.editText2);
    options[0] = text.getText().toString();

    text = (EditText)findViewById(R.id.editText3);
    options[1] = text.getText().toString();

    text = (EditText)findViewById(R.id.editText4);
    options[2] = text.getText().toString();

    int number = (int)(Math.random() * 3);
    String answer = options[number];

    TextView answerBox = (TextView)findViewById(R.id.textView7);
    answerBox.setText(answer);
}
}

Any advice would be a huge help as I'm brand new to android studio. Coding what is above took me hours.


Answer:

Change your Add_line() method to :

 public void Add_Line() {
    LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayoutDecisions);
    // add edittext
    EditText et = new EditText(this);
    LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    et.setLayoutParams(p);
    et.setText("Text");
    et.setId(numberOfLines + 1);
    ll.addView(et);
    numberOfLines++;
}

add the LayoutParams to the Edittext

Question:

I have dynamically created Layout. It has some edittexts, textview, spinners, etc.

After it, I have to get the info I introduce on those views.

So Im doing something like this

for(int i=0;i <= childs;i++){
        View v=parent.getChildAt(i);
             if (v instanceof TextView) {
                //do something
            }
            else if (v instanceof EditText) {
               //do OTHER thing
            }

The problem here is that Android detects v always as TextView when the View is either TextView or Edittext (I have no problem with spinners or button).

How can I solve this?


Answer:

That's because EditText extends TextView.

switch the order of checking:

if (v instanceof EditText) {
     //do something
} else if (v instanceof TextView) {
     //do OTHER thing
}

Question:

How do I mask editText now?

My inputType is number. How should I mask it now and at the same time restricting it to just number?


Answer:

You can use android:inputType="numberPassword" for the EditText.

Question:

I am new in android development, stuck to change the language of the whole android application. i found a way to set the strings into strings-languagecode in values directory and android:supportsRtl="true" in manifest file, it is good for changing the value of the text fields and their direction LTR and RTL automatically but I am getting the problem in EditText field because it's direction needs to be changed and set by the Java code for every xml file. Is there any way to set the direction of the EditText automatically in whole application with minimum effort? Please note I have minimum api level 15 in my project. Please help me out.

Thanks in advance.


Answer:

You can try these methods to change RTL or LTR layout directions.

For RIGHT TO LEFT:

ex. locale : Arabic(ar), Hebrew(he);

private void setRtl(){
    String languageToLoad  = "ar"; // rtl language Arabic
    Locale locale = new Locale(languageToLoad);  
    Locale.setDefault(locale); 

    Configuration config = new Configuration(); 
    config.locale = locale; 
    getBaseContext().getResources().updateConfiguration(config,  
            getBaseContext().getResources().getDisplayMetrics());
            //layout direction 
    Bidi b = new Bidi(languageToLoad,Bidi.DIRECTION_DEFAULT_RIGHT_TO_LEFT);
            b.isRightToLeft();
    //save current locale in SharedPreferences
    SharedPreferences languagepref = getSharedPreferences("language",MODE_PRIVATE);
    SharedPreferences.Editor editor = languagepref.edit();
    editor.putString("languageToLoad",languageToLoad );
    editor.commit(); 

    startActivity(...);// refresh activity.
}

For LEFT TO RIGHT:

ex locale : English(en), Tamil(ta)., etc.

private void setLtr(){
   String languageToLoad  = "en"; // ltr language English
   Locale locale = new Locale(languageToLoad);  
   Locale.setDefault(locale); 

   Configuration config = new Configuration(); 
   config.locale = locale; 
   getBaseContext().getResources().updateConfiguration(config,  
        getBaseContext().getResources().getDisplayMetrics());
        //layout direction 
   Bidi b = new Bidi(languageToLoad, Bidi.DIRECTION_DEFAULT_LEFT_TO_RIGHT);
            b.isLeftToRight();
   //save current locale in SharedPreferences
   SharedPreferences languagepref = getSharedPreferences("language",MODE_PRIVATE);
   SharedPreferences.Editor editor = languagepref.edit();
   editor.putString("languageToLoad",languageToLoad );
   editor.commit(); 

   startActivity(...);// refresh activity.

}

Call these method to change RTL or LTR layout directions.

Happy coding....

Question:

Is there any way to get something like that, plus the button to clean/delete the text when it contains something?

<android.support.design.widget.TextInputLayout
android:id="@+id/text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Inserisci Username">

                    <EditText
                        android:id="@+id/editText"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="Username"
                        android:inputType="text" />

</android.support.design.widget.TextInputLayout>

Answer:

To clear the text from edit text

@Override
public void onClick(View v) {
    editText.getText().clear(); 
    //or you can use editText.setText("");
}

To put the button inside edittext just make the custom layout

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/white"
>

<RelativeLayout android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/oval"
    android:layout_centerInParent="true"
    >

    <android.support.design.widget.TextInputLayout
        android:id="@+id/text_input_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:layout_toLeftOf="@+id/id_search_button"
        android:hint="Inserisci Username">

        <EditText
            android:id="@+id/editText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="username"
            android:background="@android:color/transparent"
            android:inputType="text" />

    </android.support.design.widget.TextInputLayout>

    <ImageButton android:id="@+id/id_search_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginRight="5dp"
        android:layout_centerVertical="true"
        android:background="@drawable/ic_clear_black"
        android:layout_alignParentEnd="true" />

</RelativeLayout>

</RelativeLayout>

drawable oval

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <solid android:color="#ffffff"/>
    <stroke android:width="2px" android:color="#ff00ffff"/>
    <corners android:radius="24dp" />
</shape>

To hide focus of the editText when app starts

add these lines inside activity tag of your class name in manifest file

<activity
        android:name=".yourActivityName"
        android:windowSoftInputMode="stateAlwaysHidden"
        android:focusable="true"
        android:focusableInTouchMode="true"
        />

You can set property of Layout like android:descendantFocusability="beforeDescendants" and android:focusableInTouchMode="true"

<RelativeLayout 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:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
xmlns:ads="http://schemas.android.com/apk/res-auto"
>

Question:

I want to align a TextView above an EditText. The following code is working well when the TextView is not higher than the space between the Top Margin of the window (red line) and the EditText (green line), like in the screenshot.

The problem occurs when the TextView has more lines than in the screenshot: it just "overruns" the EditText, but I want to keep the EditText in foreground.

In other words: I would like to place the TextView's bottom margin onto the green line and let it grow towards the red line, in order to maintain the visibility of the EditText.

// LINEAR LAYOUT
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);

// TEXTVIEW
// how to set bottom margins programmatically?
layout.addView(tv);

// EDITTEXT
// place the EditText to the bottom of the layout, working well
et.setGravity(Gravity.BOTTOM);
et.setInputType(InputType.TYPE_CLASS_TEXT);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.BOTTOM;
et.setLayoutParams(params);
layout.addView(et);

Answer:

This should do it for you:

// LINEAR LAYOUT
LinearLayout layout = new LinearLayout(getApplicationContext());
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);

// TEXTVIEW
LinearLayout.LayoutParams paramstv = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,1f);
tv.setLayoutParams(paramstv);
layout.addView(tv);

// EDITTEXT
et.setGravity(Gravity.BOTTOM);
et.setInputType(InputType.TYPE_CLASS_TEXT);

LinearLayout.LayoutParams etparams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT,8f);
etparams.gravity = Gravity.BOTTOM;
et.setLayoutParams(etparams);
layout.addView(et);

I guess the key is really to wrap both the EditText and TextView into LayoutParams. Probably you have to adjust the weights.

If this one doesn't work, try to create your layout with an XML file (the handling there is easier).

Question:

I'm writing a custom Android view which contains an EditText. I want to be able to center the text vertically through Java code but it's not working.

As you can see from the image above, the text is not centering vertically. I set the EditText background to a light red so you can see the layout bounds of it. I have an EditText on the left of it rendered through XML code and it it working correctly.

How do I get the text to show correctly?

.

Here is my code for the middle EditText:

txtSearch = new EditText(context);
txtSearch.setLayoutParams(new LinearLayout.LayoutParams(0, LayoutParams.MATCH_PARENT, 1f));
txtSearch.setGravity(Gravity.CENTER_VERTICAL);
txtSearch.setBackgroundColor(context.getResources().getColor(R.color.nowl_red_transparent_12));//Color.TRANSPARENT);
txtSearch.setHint("Search");
txtSearch.setHintTextColor(context.getResources().getColor(R.color.text_hint));
txtSearch.setInputType(InputType.TYPE_CLASS_TEXT);
txtSearch.setMaxLines(1);
txtSearch.setHorizontalScrollBarEnabled(true);
txtSearch.setTypeface(Typeface.create("sans-serif-light", Typeface.NORMAL));
txtSearch.setTextSize(16f);
txtSearch.setEllipsize(TextUtils.TruncateAt.END);
txtSearch.setText("Y u no center");
container.addView(txtSearch);

and here is the code for the EditText on the left which renders correctly:

<EditText
    android:layout_width="50dp"
    android:layout_height="match_parent"
    android:background="@color/transparent"
    android:hint="test" />

I tried practically everything. I used setGravity(Gravity.CENTER_VERTICAL), removed/added properties, and more. Nothing of which worked. Is this a bug with Android or is there something I'm missing here? It looks like this in the UI Preview and in actual Android devices as well.


Answer:

From the looks of it, it does look aligned to some degree. If it was top aligned, it would be on the far top with maybe 1dp of margin. If it was bottom aligned, it would be so high either.

I drew a green box on top of your original image to show what I think is what it is aligned relative to.

Given you have replaced the original background with a custom color, It might be possible that Android is pulling some unexpected default settings either from your context object or the system defaults and adds a padding (although I don't remember Android having any padding by default). Have you tried txtSearch.setPadding(0, 0, 0, 0) just in case?

Question:

I have following code for creating tables where people input numbers (like in excel but more more simplified)

public class Table extends Fragment {
    private TableLayout tableLayout;
    private EditText[][] editTexts;
    private int x, y;
    private int shape;

    Table(int shape) {
        this.shape = shape;
    }

    int getX() {
        return x;
    }

    void setX(int x) {
        if (x > 0) this.x = x;
    }

    int getY() {
        return y;
    }

    void setY(int y) {
        if (y > 0) this.y = y;
    }

    void refresh() {
        tableLayout.removeAllViews();
        TableRow[] tableRows = new TableRow[y];
        editTexts = new EditText[y][x];
        for (int i = 0; i < tableRows.length; i++) {
            tableRows[i] = new TableRow(getContext());
            tableLayout.addView(tableRows[i]);
            for (int j = 0; j < editTexts[i].length; j++) {
                editTexts[i][j] = new EditText(getContext());
                editTexts[i][j].setPadding(10, 0, 10, 0);
                editTexts[i][j].setBackground(getResources().getDrawable(shape, Objects.requireNonNull(getActivity()).getApplicationContext().getTheme()));
                editTexts[i][j].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
                editTexts[i][j].setMinEms(1);
                editTexts[i][j].setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
                tableRows[i].addView(editTexts[i][j]);
            }
        }
    }

    String getElement(int x, int y) {
        return editTexts[y][x].getText().toString();
    }

    void setElement(String string, int x, int y) {
        editTexts[y][x].setText(string);
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_table, container, false);
        tableLayout = new TableLayout(getContext());

        FrameLayout frameLayout = view.findViewById(R.id.frame_layout);
        frameLayout.addView(tableLayout);
        refresh();
        return view;
    }
}

But i have a problem: this table can`t auto resize its columns on-the-fly. For example, i typed some numbers and i get this:

Image 1 :

Then, i click back button on my phone and get this:

Image 2 :

My question is: how to get result as in picture 2 without pressing anything, i want to resize table columns when i typing, not after this.

Thanks.


Answer:

Your Mainly Facing this issue because layout params are not set properly you should try setting layout params at this piece of code:

 void refresh() {
        tableLayout.removeAllViews();
        TableRow[] tableRows = new TableRow[y];
        editTexts = new EditText[y][x];
        for (int i = 0; i < tableRows.length; i++) {
            tableRows[i] = new TableRow(getContext());
            tableLayout.addView(tableRows[i]);
            for (int j = 0; j < editTexts[i].length; j++) {
                editTexts[i][j] = new EditText(getContext());
                editTexts[i][j].setPadding(10, 0, 10, 0);
                editTexts[i][j].setLayoutParams(new 
                TableRow.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, 
                ViewGroup.LayoutParams.WRAP_CONTENT));
                editTexts[i][j].setBackground(getResources().getDrawable(shape, Objects.requireNonNull(getActivity()).getApplicationContext().getTheme()));
                editTexts[i][j].setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);
                editTexts[i][j].setMinEms(1);
                editTexts[i][j].setImeOptions(EditorInfo.IME_FLAG_NO_EXTRACT_UI);
                tableRows[i].addView(editTexts[i][j]);
            }
        }
    }

Question:

I have a linear layout in a fragment with a bunch of checkboxes and various edittext widgets inside it. Basically like a quiz. A bunch of multiple choice(checkboxes) and a dozen short answer(edittexts) questions.

What I would like is for users to be able to click an edittext, type in an answer, then press DONE or click anywhere else on the layout and have the widget lose focus and the keyboard hide. Currently I am overriding the setOnEditorActionListener and setOnFocusChangeListener methods of each edittext to give focus back to a main layout, and hide the keyboard respectively. Here is the code for an edittext instance called "input_7d":

    final EditText input_7d = (EditText) thisview.findViewById(R.id.txtinput_7d);
    final LinearLayout parentLayout = (LinearLayout) thisview.findViewById(R.id.main_layout);

    input_7d.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_DONE) {
                parentLayout.requestFocus();
            }
            return false;
        }
    });

    input_7d.setOnFocusChangeListener(new TextView.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if(!hasFocus){
                InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(parentLayout.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    });

This is annoying to do for every edittext I add, and it means editing lots of code if I remove them or add more in the future. What I would like to do is have a custom edittext class that can return focus to it's parent view/layout and hide the keyboard, then use that instead of the built in edittext. I'm very new to this and I haven't been able to find a way for a custom edittext to pass focus back to it's parent layout. Is there a better way to get a bunch of edittexts to all have this behavior and not have it all "hardcoded" into my fragment class?


Answer:

So I could not find a way to have a edittext pass focus back to it's parent layout from inside the view itself. So instead I have opted to just disable focusable property of it when it

1) It loses focus (user clicked outside the view on something focusable, ie. The parent layout)

2) Finishes it's edit(user presses Done action on soft keyboard)

Surprisingly neither of these actions by default remove focus and the cursor from a default editText. At least not inside my scroll views.

So I added these lines to a custom view(myEditText) that extends the editText view:

this.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if(actionId == EditorInfo.IME_ACTION_DONE) {
            myEditText.setFocusable(false);
            myEditText.setFocusableInTouchMode(false);

        }
        return false;
    }
});
this.setOnFocusChangeListener(new TextView.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if(!hasFocus){
            myEditText.setFocusable(false);
            myEditText.setFocusableInTouchMode(false);
            hideKeyboardFrom(context, v);
        }
    }
});
this.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        myEditText.setFocusableInTouchMode(true);
        myEditText.setFocusable(true);
        return false;
    }
});

I find it really annoying that to get simple functionality like not having the cursor blinking at me always or having the view not take focus when changing fragments and such you have to do such a weird workaround. Making a view unfocusable unless it's focused in which case it is focusable but only until it isn't focused again just seems dumb. Still wondering if there is a better way to do this for a large number of edits in one layout.

Question:

I'm Working on Personal Details model, there have 2 radio option Married and Unmarried.On click of the Married radio button it will enable the Edit Text it will take the Number of Child of that Married person. Based on that entered value for the Edit Text. Dynamically Linear Layout is implementing. But The issues is when click on the Edit Text it's creating the Linear Layout(On erase of the Edit Text the Linear Layout also should erase).

My code is like this. In Main Activity

et_childCount.addTextChangedListener(new TextWatcher() {
   @Override
       public void beforeTextChanged(CharSequence s, int start, int count, int after) {
   @Override
       public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    @Override
       public void afterTextChanged(Editable s) {
           if (s != null) {
               countI = childCount;
               noOfChild = countI;
                if (noOfChild >= 1) {
                   for (int i = 1; i <= noOfChild; i++) {
                       LinearLayout linearLayout = new LinearLayout(getActivity());
                       LayoutParams params = new LinearLayout.LayoutParams(
                               LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                       linearLayout.setLayoutParams(params);
                       linearLayout.setOrientation(LinearLayout.VERTICAL);
                       TextView tv_BorderChildDetails = new TextView(getActivity());
                       tv_BorderChildDetails.setText("Child " + i);
                       tv_BorderChildDetails.setGravity(Gravity.CENTER_HORIZONTAL);
                       tv_BorderChildDetails.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                       linearLayout.addView(tv_BorderChildDetails);
                       EditText et_cName = new EditText(getActivity());
                       EditText et_cDob = new EditText(getActivity());
                       EditText et_cSchoolName = new EditText(getActivity());
                       et_cName.setHint("Child name");
                       et_cDob.setHint("Date of birth");
                       et_cSchoolName.setHint("School name");
                       childNameList.add(et_cName);
                       childDOBList.add(et_cDob);
                       childSchoolNameList.add(et_cSchoolName);
                       et_cName.setLayoutParams(params);
                       et_cDob.setLayoutParams(params);
                       et_cSchoolName.setLayoutParams(params);
                        linearLayout.addView(et_cName);
                       linearLayout.addView(et_cDob);
                       linearLayout.addView(et_cSchoolName); } } });

Answer:

You can use TextWatcher() like so:

editText.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {}

    @Override
    public void afterTextChanged(Editable s) {
        // Convert the editable to int.
        int userInput = Integer.parseInt(s.getText().toString());
        // First we want to copy the data ArrayList so we don't affect the original one.
        ArrayList<Data> new = copyArray(originalDataArrayList);
        // Then we want to run a for loop to change the item count depending on the userInput value.
        for (int i = 0; i < newArray.size(); i++){
          if (i >= userInput){
            newArray.remove(i);
        }
      }
        // Now we have ArrayList with the required size.
        // Here you create a new adapter and pass the new ArrayList to it and set the ListView adapter as the new adapter.
    }
});

Copy ArrayList Method:

    private ArrayList<Data> copyArray(ArrayList<Data> array) {
    ArrayList<Data> newArray = new ArrayList<>();
    newArray.addAll(array);
    return newArray;
}

Question:

I'm a beginner in android development, my project requires me to build a simple UI app using two fragments (home and field). The home will show the starup page with 5 buttons. when we click on these buttons, it will then call field fragment and show fields like:

conductivity:----,height:---- and etc to fill up, like inserting manual data.

my issue here is , the project requires me to use linearlayout in horizontal alignment for the field frag, when i do that and add edit text and text views, its lined in same line as horizontal, but what i need is it to appear one and the other below it: SOme thing like

conductivity(text view): ___________(editText) [another line] height(text view):________(editText)

and so on. SOrry this might be a simple issue but i have been stuck on this for 2 days now. Help me

my code for field fragment.xml is as follows:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hp1_textView"
    android:id="@+id/hp1_textView"
    android:textSize="32sp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />

<LinearLayout        android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/hp1_textView"
    android:layout_centerHorizontal="true"
    android:id="@+id/linearLayout">
    <TextView            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/conductivity"
        android:id="@+id/textView"/>
    <EditText            android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_weight="1"
        android:hint="@string/conductivity_field" />
    <TextView            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="pH:"
        android:id="@+id/textView2" />
    <EditText            android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:layout_weight="1"
        android:hint="0.-14" />

</LinearLayout>
</RelativeLayout>

THis is how i want it to display


Answer:

Use this xml in your code as it is

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp"
        android:weightSum="2">


        <TextView
            android:id="@+id/textView1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Conductivity (uS):  "
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/editText1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="745.2" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp"
        android:weightSum="2">


        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="pH:  "
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="7.1" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp"
        android:weightSum="2">


        <TextView
            android:id="@+id/textView3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Moisture(%):  "
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/editText3"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="0-100" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:padding="5dp"
        android:weightSum="2">


        <TextView
            android:id="@+id/textVie4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:singleLine="true"
            android:text="Dissolved oxygen(ppm):  "
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/editText4"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:hint="0-100" />

    </LinearLayout>

    <Button
        android:id="@+id/btn1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:padding="5dp"
        android:text="Save Log Entry" />

    <Button
        android:id="@+id/btn2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:padding="5dp"
        android:text="Show Log Entry" />


</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:orientation="horizontal"
    android:padding="5dp"
    android:weightSum="3">


    <Button
        android:id="@+id/btn3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:padding="5dp"
        android:text="Previouse" />

    <Button
        android:id="@+id/btn4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:padding="5dp"
        android:text="Next" />


    <Button
        android:id="@+id/btn5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_weight="1"
        android:padding="5dp"
        android:text="Home" />

</LinearLayout>

</RelativeLayout>

I hope its solve your problem.....

Question:

I am getting the following error when trying to show an error message on the UI's TextInputLayout:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.blablabla.appname, PID: 23691
    java.lang.NoSuchFieldError: No field error_color_material of type I in class Landroid/support/v7/appcompat/R$color; or its superclasses (declaration of 'android.support.v7.appcompat.R$color' appears in /data/app/com.blablabla.appname-2/split_lib_slice_6_apk.apk)
        at android.support.design.widget.TextInputLayout.setErrorEnabled(TextInputLayout.java:654)
        at android.support.design.widget.TextInputLayout.setError(TextInputLayout.java:721)
        at android.support.design.widget.TextInputLayout.setError(TextInputLayout.java:708)
        at com.blablabla.appname.activity.SetupProfileActivity.validateUsername(SetupProfileActivity.java:465)

SetupProfileActivity.java:465:

private boolean validateUsername() {
    final String username = inputUsername.getText().toString().trim();
    if (inputUsername.getText().toString().trim().isEmpty()) {
        inputLayoutUsername.setError(getText(R.string.username_warning)); // Line 465
        requestFocus(inputUsername);
        return false;
    } else {
        inputLayoutFullName.setErrorEnabled(false);
    }

    return true;
}

What's the issue? I tried looking up but couldn't find anything related to the No field error_color_material message.


Answer:

Turns out that my app module's build.Gradle was missing a support library:

implementation 'com.android.support:design:28.0.0'

Everything was resolved after adding that then resyncing!

Question:

I have two EditText widgets and want to hide the keyboard when the user clicks outside of those (if the keyboard is still active at that time obviously). To do this I am using a setOnFocusChangeListener on both of them like so :

eTNom=convertView.findViewById(R.id.EditText_nom);

eTNom.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (!hasFocus) 
            hideKeyboard(v);
    }
});

The other setOnFocusChangeListener is handled exactly the same way.

However this does not work because the onFocusChange method is called multiple times (4-5) every time I click on one of the two EditText. This results in the hasFocus variable switching between true and false rapidly after the method is called and the keyboard only shows up for a very brief moment.

Here's exactly what's happening : https://imgur.com/ZFjXPPz

I have seen this question asked once but the accepted answer suggested to add android:windowSoftInputMode="adjustPan" in the manifest file. I did that but it did not solve my problem. I also saw people recommending to set the clickable, focusable and focusableInTouchMode attributes to true in the parent layout, which I also did, but it still does not work.

I thought that the problem came from the fact that I have two EditText widgets but when I deleted one from my activity I still had the same problem so I am pretty much lost right now and any sort of help would be really appreciated.

Thanks.


Answer:

Put below lines in Menifest

<activity android:name=".ActivityName"
      android:windowSoftInputMode="stateHidden"  />

OR you can show/hide the keyboard by using below two functions

public void hideSoftKeyboard() {
    if(getCurrentFocus()!=null) {
       InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
       inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}

 /* Shows the soft keyboard */
public void showSoftKeyboard(View view) {
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    view.requestFocus();
    inputMethodManager.showSoftInput(view, 0);

}

Question:

I have a linear layout (linear2 in code) with horizontal orientation. I've placed a button, editText and a second button into this layout. I'd like to have the button's width as "wrap_content". How do I give all the remaining space to editText without using weight? Is it possible to place this layout to the bottom without using weight of vertical views?

Code is here:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/backNormal"
    android:orientation="vertical">

    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:orientation="vertical"
        android:layout_weight="12">
        <LinearLayout
            android:id="@+id/linear1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/linear2"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="2"
        android:orientation="horizontal">
        <ImageView
            android:id="@+id/buttonClip"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity= "center_vertical|center_horizontal"/>

        <EditText
            android:id="@+id/editChatMessage"
            android:layout_width="0dp"
            android:layout_height="fill_parent"
            android:gravity="top|left"
            android:maxLines="5"
            android:layout_gravity= "center_vertical|center_horizontal"
            android:layout_weight="5"/>
        <Button
            android:id="@+id/buttonProcess"
            android:text='Process'
            android:gravity="center"
            android:layout_gravity= "center_vertical|center_horizontal"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="1"/>
    </LinearLayout>
</LinearLayout>

Thanks!


Answer:

Try this way,hope this will help you to solve your problem.

Here i try to improve your LinearLayout weight allocation

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/backNormal"
    android:orientation="vertical">
    <ScrollView
        android:id="@+id/scroll"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="0.85">
        <LinearLayout
            android:id="@+id/linear1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:id="@+id/linear2"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="0.15"
        android:gravity="center">
        <ImageView
            android:id="@+id/buttonClip"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:src="@drawable/ic_launcher"
            android:scaleType="fitXY"/>

        <EditText
            android:id="@+id/editChatMessage"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:gravity="top|left"
            android:maxLines="5"
            android:layout_weight="1"/>
        <Button
            android:id="@+id/buttonProcess"
            android:text='Process'
            android:gravity="center"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"/>
    </LinearLayout>
</LinearLayout>

Question:

Hopefully I'm not missing something stupid. I'm able to create a single EditText and add it to a LinearLayout; however, when I try to do so to an array of EditTexts, I get an NPE on whatever line is first in the for loop. Here is the working code:

LinearLayout p2player1 = (LinearLayout)findViewById(R.id.p2player1);
    EditText p1 = new EditText(this);
    LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(200,LinearLayout.LayoutParams.WRAP_CONTENT);
    p1.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
    p1.setInputType(InputType.TYPE_CLASS_NUMBER);
    p1.setId(View.generateViewId());
    p1.setLayoutParams(editParams);
    p2player1.addView(p1,editParams);

Everything fine.

Here's the array code:

LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(200,LinearLayout.LayoutParams.WRAP_CONTENT);
    EditText[] play1 = new EditText[20];
    editParams.setMargins(184,0,0,0);
    for (int i=0;i<21;i++) {
        play1[i].setLayoutParams(editParams);
        play1[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        play1[i].setId(View.generateViewId());
        play1[i].setInputType(InputType.TYPE_CLASS_NUMBER);
        play1[i].setHint("0000");
        if (i>2 && IsOdd(i)) {
            play1[i].setFocusable(false);
        }

        p2player1.addView(play1[i],editParams);
    }
public boolean IsOdd(int n) {
    if ((n % 2) == 0) {
        return false;
    } else { return true; }
}

I included the IsOdd function just so it could be seen. That's not where it actually is. My Ultimate Goal is to generate a LinearLayout of Vertical EditTexts. Seems like it would be so easy, so I'm sure I'm being stupid, and missing something very easy.

Here's the NPE:

Process: com.dyna.ks.scorekeeper, PID: 5439
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dyna.ks.scorekeeper/com.dyna.ks.scorekeeper.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2984)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045)
                                                                       at android.app.ActivityThread.-wrap14(ActivityThread.java)
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642)
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                       at android.os.Looper.loop(Looper.java:154)
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6776)
                                                                       at java.lang.reflect.Method.invoke(Native Method)
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                                                                    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setLayoutParams(android.view.ViewGroup$LayoutParams)' on a null object reference
                                                                       at com.dyna.ks.scorekeeper.MainActivity.setupTwoPlayer(MainActivity.java:105)
                                                                       at com.dyna.ks.scorekeeper.MainActivity.onCreate(MainActivity.java:62)
                                                                       at android.app.Activity.performCreate(Activity.java:6955)
                                                                       at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1126)
                                                                       at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2927)
                                                                       at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3045) 
                                                                       at android.app.ActivityThread.-wrap14(ActivityThread.java) 
                                                                       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1642) 
                                                                       at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                       at android.os.Looper.loop(Looper.java:154) 
                                                                       at android.app.ActivityThread.main(ActivityThread.java:6776) 
                                                                       at java.lang.reflect.Method.invoke(Native Method) 
                                                                       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 

What am I missing or doing wrong, please?


Answer:

This is because you did not initialized all editText.

Below is declaration only.

EditText[] play1 = new EditText[20];

You need to initialise each edittext into loop as play1[i] = new EditText(this);. See below code which will work fine

for (int i=0;i<21;i++) {
        play1[i] = new EditText(this);
        play1[i].setLayoutParams(editParams);
        play1[i].setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        play1[i].setId(View.generateViewId());
        play1[i].setInputType(InputType.TYPE_CLASS_NUMBER);
        play1[i].setHint("0000");
        if (i>2 && IsOdd(i)) {
            play1[i].setFocusable(false);
        }

        p2player1.addView(play1[i],editParams);
    }

Question:

I have seen/tried the following questions, but mine is not the same:

  • Android keyboard next button issue on EditText
  • Move to another EditText when Soft Keyboard Next is clicked on Android

First, I have a CardView wherein I have a EditText, like below:

<RelativeLayout
    android:id="@+id/topCard"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/myCard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"           
        android:clickable="false"
        android:foreground="?android:attr/selectableItemBackground"
        android:orientation="horizontal"
        app:cardCornerRadius="5dp"
        app:cardElevation="3dp"
        app:cardPreventCornerOverlap="false"
        app:cardUseCompatPadding="true">

        <RelativeLayout
            android:layout_width="5dp"
            android:layout_height="match_parent"
            android:background="#26c2ef">

        </RelativeLayout>


        <RelativeLayout
            android:id="@+id/cardTopTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:layout_marginTop="5dp">


            <TextView
                android:id="@+id/lessonTitleHeading"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginStart="10dp"
                android:layout_marginTop="10dp"
                android:text="Please provide a name:"
                android:textColor="#000000"
                android:textSize="18sp" />

            <ImageView
                android:id="@+id/horiLine"
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_below="@+id/lessonTitleHeading"
                android:layout_marginEnd="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginStart="10dp"
                android:background="#60000000" />

            <EditText
                android:id="@+id/noteEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/horiLine"
                android:layout_marginEnd="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:layout_marginStart="10dp"
                android:layout_marginTop="5dp"
                android:background="@android:color/transparent"
                android:hint="Enter name here..."
                android:imeOptions="actionNext" />


        </RelativeLayout>


    </android.support.v7.widget.CardView>


</RelativeLayout>

I then inflate this layout in another by using include like this:

<include
    android:id="@+id/lessonTitle"
    layout="@layout/activity_notes_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    />

and in my Activity class I do the following:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_leason);

    View tvOne = findViewById(R.id.tvOne);
    View tvTwo = findViewById(R.id.tvTwo);
    View tvThree = findViewById(R.id.tvThree);
    View tvFour = findViewById(R.id.tvFour);

    final TextView tvOne = (TextView)vLessonTitle.findViewById(R.id.lessonTitleHeading);
    final EditText etOne = (EditText) vLessonTitle.findViewById(R.id.noteEditText);

    TextView tvTwo = (TextView)vlessonProbStu.findViewById(R.id.lessonTitleHeading);
    final EditText etTwo = (EditText) vlessonProbStu.findViewById(R.id.noteEditText);

    TextView tvThree = (TextView)vLessonWorkedOn.findViewById(R.id.lessonTitleHeading);
    final EditText etThree = (EditText) vLessonWorkedOn.findViewById(R.id.noteEditText);

    TextView tvFour = (TextView)vlessonWhatStudShouldWorkOn.findViewById(R.id.lessonTitleHeading);
    final EditText etFour = (EditText)vlessonWhatStudShouldWorkOn.findViewById(R.id.noteEditText);

    tvOne.setText("This is the first CardView:");
    etOne.setHint("Enter Title Here...");

    tvTwo.setText("This is the second CardView:");
    etTwo.setHint("Enter Text Here...");

    tvThree.setText("This is the third CardView:");
    etThree.setHint("Enter Text Here...");

    tvFour.setText("This is the fourth CardView:");
    etFour.setHint("Enter Text Here...");

    //I tried this, but it didn't work...
    etOne.setOnKeyListener(new View.OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            // If the event is a key-down event on the "enter" button
            if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
                    (keyCode == KeyEvent.KEYCODE_ENTER))
            {
                // Perform action on Enter key press
                etLessonTitle.clearFocus();
                etLessonProbStu.requestFocus();
                return true;
            }
            return false;
        }
    });

}

The Layout now looks like this:

At this point I have a bunch of CardViews with EditTexts underneath each other like above. I would like to use the next button in the keyboard to go to the next CardsViews EditText.

If you have a look at my Activity class above, I tried using setOnKeyListener and clearFocus from the current EditText then requestFocus on the next EditText, but that didn't work.

Any ideas how I can achieve this?


Answer:

Try this you need to set android:inputType="" to your Editext with android:imeOptions="actionNext"

<EditText
    android:id="@+id/noteEditText"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/horiLine"
    android:layout_marginEnd="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginStart="10dp"
    android:layout_marginTop="5dp"
    android:background="@android:color/transparent"
    android:hint="Enter name here..."
    android:inputType="text" // specifies your input type here  
    android:imeOptions="actionNext" />

Question:

I'm currently developing a simple Notes application where the user can input a title and the content of their note. What I am looking to achieve is that when the user clicks the note content (EditText) the soft keyboard comes up and only the note content EditText reduces in size (resizes) whilst everything else remains in the same position.

My current implementation can be seen below:

Manifest:

<activity android:theme="@style/AppTheme"
        android:name=".AddActivity"
        android:label="@string/add_record"
        android:windowSoftInputMode="adjustResize"
        android:parentActivityName=".MainActivity"
        android:excludeFromRecents="true"/>

XML - Add Activity

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/add_record"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="20dp">

    <EditText
        android:id="@+id/title_edittext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/enter_title"
        android:inputType="textCapSentences"
        android:textColor="@color/fontPrimary"
        android:theme="@style/EditTextCustomCursor">

        <requestFocus />
    </EditText>

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/modify_scrollview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fitsSystemWindows="false"
        android:isScrollContainer="false"
        android:fillViewport="true">

        <EditText
            android:id="@+id/note_edittext"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@null"
            android:ellipsize="end"
            android:gravity="top|left"
            android:hint="@string/enter_note"
            android:inputType="textCapSentences|textMultiLine"
            android:paddingLeft="5dp"
            android:scrollHorizontally="false"
            android:textColor="@color/fontPrimary"
            android:theme="@style/EditTextCustomCursor" />
    </ScrollView>

</LinearLayout>

Java - Add Activity

private int screenHeight;
private int actionBarHeight = 350;
private int keyboardHeight;

...

private void setupListeners() {

    final LinearLayout layout = (LinearLayout) findViewById(R.id.add_record);
    layout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            Rect r = new Rect();
            layout.getWindowVisibleDisplayFrame(r);

            screenHeight = layout.getRootView().getHeight();
            keyboardHeight = screenHeight - (r.bottom - r.top);
            Log.d("Keyboard Size", "Size: " + keyboardHeight);

        }
    });

    KeyboardVisibilityEvent.setEventListener(
            AddActivity.this,
            new KeyboardVisibilityEventListener() {
                @Override
                public void onVisibilityChanged(boolean isOpen) {

                    if (isOpen) {
                        Log.d("KB", "openKeyboard");
                        scrollView.setLayoutParams(new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.FILL_PARENT, screenHeight - actionBarHeight - keyboardHeight));
                    } else {
                        Log.d("KB", "closeKeyboard");
                        scrollView.setLayoutParams(new LinearLayout.LayoutParams(
                                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
                    }
                }
            });
}

This is using the Keyboard library (https://github.com/yshrsmz/KeyboardVisibilityEvent) to detect when the keyboard is opened or closed. This works perfectly and the height / layout is adjusted just how I want it to look but only if the user clicks at the top of the EditText. If the user clicks at the bottom of the EditText (if they have entered a long note) then the whole layout gets pushed up leaving a large gap at the bottom of the page.

Therefore, is there any way how wherever in the EditText / ScrollView the user clicks, for it to only adjust that one EditText in height and leave the other EditText in place at the top of the screen without pushing it and the SupportActionBar out of view? Also, the ScrollView is being used to achieve the vertical scrollbar on the right side of the screen - if this same behaviour can be achieved using just the EditText, then I would remove the ScrollView altogether.

EDIT - Add Photos

Image 1: Long note content (bottom of note content is at the bottom of the scrollView (which cannot be seen, until scrolled))

Image 2: Same note but clicking at the bottom, forces the top EditText and Support ActionBar out of view whilst leaving a gap at the bottom.

Explanation: Where the F is highlighted (in Image 2) that is the bottom of the EditText / ScrollView so you can see the large gap created between the top of the soft keyboard and the bottom of the EditText / ScrollView

Desired behaviour: Clicking anywhere in the bottom EditText should only resize that particular EditText to make room for the soft keyboard and ensure that this EditText is above the soft keyboard so the user can see what they are typing whilst the top EditText remains in the same position throughout.


Answer:

Its because you're adding edittext in a scroll view. why do you even need scroll view? scroll view have a property of going to specific line when keyboard pop-up which is causing this behavior. if you really want to use scrollview, then add master layout as scrollview. add one direct child aka linear layout in there and add all the content in that linear layout.

Question:

I need to show n number of Edit text added dynamically below a static Edit text. I am adding the ET but some how it is not visible. What am doing wrong??

Here is my code:

private void addEditTextView(int numberOfViews){
    // Using layout params same as above static ET
    ViewGroup.LayoutParams layoutParams = staticEditText.getLayoutParams();

    for (int index = 0; index <= numberOfViews; index++) {
        final EditText newET = new EditText(getActivity());

        //Added below 2 lines just to make sure width and height are coming
        layoutParams.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
        newET.setLayoutParams(layoutParams);
        newET.setHint("Select ME");
        newET.setFocusable(false);
        newET.setId(index);
        newET.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //TODO set time
                Log.d("Clicked...",newET.getId()+"");
            }
        });
        //parentLayout is Linear Layout with Vertical orientation
        parentLayout.addView(newET);
    }
}

XML code :

 <LinearLayout
        android:id="@+id/parentLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <EditText
            android:id="@+id/staticEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="3dp"
            android:background="@drawable/rectangle_bg_dark_gray_border"
            android:focusable="false"
            android:hint="staticEditText"
            android:padding="7dp" />

    </LinearLayout>

UPDATE : parentLayout.getChildCount() is coming correctly. New views are getting added but not visible!


Answer:

Hi try adding a Scrollview

 <?xml version="1.0" encoding="utf-8"?>
 <LinearLayout 
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       xmlns:android="http://schemas.android.com/apk/res/android">
       <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                  android:id="@+id/parentLayout" 
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:orientation="vertical">
                  <!-- EDITTEXT here -->
            </LinearLayout>
      </ScrollView>
 </LinearLayout>

Question:

I am currently working on a program where I can take two inflatable edittexts and do calculations with them. So I'm trying to get each value, put them into the designated arraylist and calculate values according to the corresponding array, But I am having trouble as I am getting an indexoutofbounds exception and I have no idea if my code is even working. Could I get some help please?

Here is my code.

public class CalculateActivity extends AppCompatActivity {
Button calculate;
LinearLayout courses;
ArrayList<Course> coursesList;
SemesterDatabase db;
TextView gpa;
int percentage = 0;
int hundredth =0;
float averageGrade = 0.0f;

float[] gradePoints = new float[]{};


ArrayList<Float> gradesList = new ArrayList();
ArrayList<Float> scoreList = new ArrayList();
ArrayList<Float> totalList = new ArrayList();



int id;
TextView semester;

class C03171 implements OnClickListener {
    C03171() {
    }

     public void onClick(View view) {
        float gradePointsCalc = 0.0f;
        float totalCrdtHrs = 0.0f;

//EDIT BY Jyoti JK, Thank you for your help

            for (int x = 0; x < scoreList.size()&& x<totalList.size(); x++)

        {CalculateActivity.this.gradesList.add(scoreList.get(x) / totalList.get(x));
        }



        for (int i = 0; i < CalculateActivity.this.coursesList.size(); i++) {
            int crdtHrs = ((Course) CalculateActivity.this.coursesList.get(i)).getCreditHours();
            totalCrdtHrs += (float) crdtHrs;
            averageGrade += (((Float)CalculateActivity.this.gradesList.get(i).floatValue())*(((Course) CalculateActivity.this.coursesList.get(i)).getCreditHours())/totalCrdtHrs);

        }
        float gpaCalc = averageGrade;
        CalculateActivity.this.gpa.setText(String.format("%.3f", new Object[]{Float.valueOf(gpaCalc)}));
    }
}


class C03194 implements DialogInterface.OnClickListener {
    C03194() {
    }

    public void onClick(DialogInterface dialogInterface, int i) {
        dialogInterface.cancel();
    }
}

class C03205 implements DialogInterface.OnClickListener {
    C03205() {
    }

    public void onClick(DialogInterface dialogInterface, int i) {
        CalculateActivity.this.db.deleteSemester(CalculateActivity.this.id);
        CalculateActivity.this.db.deleteAllCourses(CalculateActivity.this.id);
        CalculateActivity.this.onBackPressed();
    }
}



protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView((int) R.layout.activity_calculate);
    setSupportActionBar((Toolbar) findViewById( R.id.toolbar));
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle((CharSequence) "Calculate GPA");
    this.db = new SemesterDatabase(this);
    this.id = getIntent().getIntExtra("semesterId", 1);
    this.coursesList = this.db.getAllCourses(this.id);
    this.semester = (TextView) findViewById(R.id.semester);
    this.semester.setText(getIntent().getStringExtra("semesterName"));
    this.gpa = (TextView) findViewById(R.id.gpa);
    this.calculate = (Button) findViewById(R.id.calculate);
    this.courses = (LinearLayout) findViewById(R.id.courses);
    addCourses();
    this.calculate.setOnClickListener(new C03171());

}

public void addCourses() {
    LayoutInflater inflater = LayoutInflater.from(this);
    for (int i = 0; i < this.coursesList.size(); i++) {
        View v = inflater.inflate(R.layout.item_course, null, false);
        this.courses.addView(v);
        final int position = CalculateActivity.this.scoreList.size();
        final int position2 = CalculateActivity.this.totalList.size();
        CalculateActivity.this.scoreList.add(0.0f);
        final EditText Score = (EditText) v.findViewById(R.id.Score);
        final EditText Total = (EditText) v.findViewById(R.id.Total);

        Score.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }


            public void afterTextChanged(Editable editable) {
                percentage = Integer.parseInt(editable.toString());
                float perc = (float) percentage;
                CalculateActivity.this.scoreList.set(position, perc);

            }
        });

        Total.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void afterTextChanged(Editable editable) {
                hundredth = Integer.parseInt(editable.toString());
                float hund = (float) percentage;
                CalculateActivity.this.scoreList.set(position, hund);

            }
        });




    }
}

Basically I think what my code is doing is taking the edittext value from

 Score.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }


            public void afterTextChanged(Editable editable) {
                percentage = Integer.parseInt(editable.toString());
                float perc = (float) percentage;
                CalculateActivity.this.scoreList.set(position, perc);

            }
        });

        Total.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void afterTextChanged(Editable editable) {
                hundredth = Integer.parseInt(editable.toString());
                float hund = (float) percentage;
                CalculateActivity.this.scoreList.set(position, hund);

            }
        });

And getting the values to

for (int x = 0; x < scoreList.size(); x++)

        {
            ArrayList<Float> finalscore = new ArrayList();
            finalscore.add(scoreList.get(x) / totalList.get(x));
            for (int j = 0; j < finalscore.size(); j++)

            {
                CalculateActivity.this.gradesList.add(finalscore.get(j));
            }
        }

And finally calculating it using

 for (int i = 0; i < CalculateActivity.this.coursesList.size(); i++) {

             averageGrade += ((Float)CalculateActivity.this.gradesList.get(i).floatValue())*(((Course) CalculateActivity.this.coursesList.get(i)).getCreditHours());

        }
        float gpaCalc = averageGrade;
        CalculateActivity.this.gpa.setText(String.format("%.3f", new Object[]{Float.valueOf(gpaCalc)}));

But I have absolutely No idea where it went wrong and I have no idea how to see where it went wrong. I would appreciate detailed comments!

Oh and here's The error Log.

FATAL EXCEPTION: main
                                                                             Process: com.example.joon.chadwickgrades, PID: 19395
                                                                             java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
                                                                                 at java.util.ArrayList.get(ArrayList.java:411)
                                                                                 at com.example.joon.chadwickgrades.CalculateActivity$C03171.onClick(CalculateActivity.java:66)
                                                                                 at android.view.View.performClick(View.java:5623)
                                                                                 at android.view.View$PerformClick.run(View.java:22433)
                                                                                 at android.os.Handler.handleCallback(Handler.java:751)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                 at android.os.Looper.loop(Looper.java:154)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6247)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762)

Answer:

As your code,

for (int x = 0; x < scoreList.size(); x++)

    {
        ArrayList<Float> finalscore = new ArrayList();
        finalscore.add(scoreList.get(x) / totalList.get(x));
        for (int j = 0; j < finalscore.size(); j++)

        {
            CalculateActivity.this.gradesList.add(finalscore.get(j));
        }
    }

For Every iteration ,

1.You are creating a finalscore arraylist object.

2.And adding only one element to it.

3.And then inner for loop starts. the size of finalscore is always one. And you are adding it to gradesList.

I think you can change it as,

 for (int x = 0; x < scoreList.size() && x<totalList.size(); x++)

    {

       CalculateActivity.this.gradesList.add(scoreList.get(x) / totalList.get(x));

    }

And change the code like,

for (int i = 0; i < CalculateActivity.this.coursesList.size() && i <CalculateActivity.this.gradesList.size(); i++) {
            int crdtHrs = ((Course) CalculateActivity.this.coursesList.get(i)).getCreditHours();
            totalCrdtHrs += (float) crdtHrs;
            averageGrade += (((Float)CalculateActivity.this.gradesList.get(i).floatValue())*(((Course) CalculateActivity.this.coursesList.get(i)).getCreditHours())/totalCrdtHrs);

        }

Edit:

The point is, Whenever you are getting data from the list, You need to check whether it is null and also it's size. which is a best practice to avoid exceptions

Question:

I have a design where there is an input EditText with a set of options for input units (RadioGroup full of RadioButtons). When the user selects a certain option, I have implemented ViewGroup.LayoutParams to adjust the width to the required value.

Everything works fine normally, but when I add animateLayoutChanges to improve the overall appearance, the cursor in the EditView is negatively affected:

  • The user inputs a value, everything appears normal (gravity is right in the EditText by the way)
  • The option that shrinks the view is checked - the view animates shrinking properly - BUT - the entry is now out of sight! Hidden where it should have been. If you click into the field or change the RadioButton option to one with the same size input, the entry then moves to the appropriate position...
  • Similarly - the view is small and has an entry in the correct position, an option where the view expands is chosen - now the view expands and the entry is left in the centre of the view instead of moving to the right position! Again it refreshes when another action regarding the EditText is performed..

I have attempted to fix this by:

  • Storing the input string into a temporary variable and replacing it with setText()
  • Using append("") to add nothing prior to re-adding the string
  • Calling .requestFocus() in the EditText upon selection
  • Redrawing the view with .invalidate()
  • Setting the cursor to the end of the view
  • Attempting to custom-set animations (without success, I may have to continue with this approach?)

If anyone knows how I can potentially refresh the view so that it updates the text position or otherwise disable the animation on just this view whilst retaining all of the others that would be great!

Thanks!


Answer:

I ended up working out a solution after all..! Here it is for those who may be in a similar situation. I set animateLayoutChanges to false and custom animated the other transitions - in my case it was TextViews next to the EditText that were appearing and disappearing as it changed size. I had to use the .animate().alpha(float) method as below.

For becoming visible:

textViewFractionIn.setVisibility(View.VISIBLE);
textViewFractionIn.animate()
    .alpha(1.0f)
    .setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            // Has to be blank it seems to override the previous .setListener in the GONE case?
            }
        });

And for making it invisible (GONE in this case):

textViewFractionIn.animate()
    .alpha(0.0f)
    .setListener(new AnimatorListenerAdapter() {
        @Override
        public void onAnimationEnd(Animator animation) {
            super.onAnimationEnd(animation);
            textViewFractionIn.setVisibility(View.GONE);
            }
        });

This animates the fading of views as per default, but any movements of the views remain discrete and thus the EditText cursor remains in the right spot!

Question:

I want to add an edit text directly to the toolbar. The edittext is always shown below or above the toolbar. What can I do?

I tried to put the edit text in app_bar_nav.xml, but that doesnt help with the position of it. I also tried an include statement and changing the layout type to linear layout... also without a good result.

app_bar_nav.xml

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".NavActivity">

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/appBarLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorBlack"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

    <EditText
        android:id="@+id/myEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorBlack"
        android:hint="Adresse" />

</com.google.android.material.appbar.AppBarLayout>

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:clickable="true"
    app:srcCompat="@android:drawable/ic_menu_search" />

<include layout="@layout/content_nav" />

activity_nav.xml

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">


<include
    layout="@layout/app_bar_nav"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<com.google.android.material.navigation.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_nav"
    app:menu="@menu/activity_nav_drawer" />


Answer:

Add Edit text inside Toolbar it self, please try below code

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/colorBlack"
        app:popupTheme="@style/AppTheme.PopupOverlay" >

    <EditText
        android:id="@+id/myEditText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorBlack"
        android:hint="Adresse" />
    </androidx.appcompat.widget.Toolbar>

Question:

I'm having a question where I couldn't find the answer online or know how to find it..

I have EditText xml attribute and I made an event listener to this attribute by changing the color of an underline beneath it. Is there a way when the focus is removed from this EditText (i.e user click on any other element rather than this one) to remove the highlighted color for the line I colored?

On the onclick event listener? It seems weird, but I want the opposite of the onclick like onclickremove or something.


Answer:

You can use the the setOnFocusChangeListener to your EditText. If lost focus,clear the color filter:

editText.setOnFocusChangeListener(new OnFocusChangeListener() {          
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
               editText.getBackground().setColorFilter(color, PorterDuff.Mode.SRC_IN);
            }
            else{                   
               editText.getBackground().clearColorFilter();
            }
        }
    });

If you want to change your view color, just add the below line in onFocusChange:

view.setBackgroundColor(Color.parseColor("#ffffff"));

Hope this helps.

Question:

How to disable numbers entering after zero in edittext?

I have validated only for this..

 if (TextUtils.isEmpty(strBalance)) {
                    Toast.makeText(TransactionSellINActivity.this, "Amount should not be empty", Toast.LENGTH_SHORT)
                            .show();
                } else if (strBalance.equalsIgnoreCase("0")) {
                    Toast.makeText(TransactionSellINActivity.this, "Amount should not be Zero", Toast.LENGTH_SHORT)
                            .show();
                }

But if user enters 01 or 001 or 02,03 etc.,? ie number after zero? -> I want to restrict those numbers

How to handle such case?


Answer:

if (TextUtils.isEmpty(strBalance)) {
                Toast.makeText(TransactionSellINActivity.this, "Amount should not be empty", Toast.LENGTH_SHORT)
                        .show();
            } else if (strBalance.equalsIgnoreCase("0")) {
                Toast.makeText(TransactionSellINActivity.this, "Amount should not be Zero", Toast.LENGTH_SHORT)
                        .show();
            }
            else if(strBalance.indexOf("0")!=a.length()-1)
                {
                Toast.makeText(TransactionSellINActivity.this, "Amount Not Valid", Toast.LENGTH_SHORT)
                        .show();
                }
                else{
                    Toast.makeText(TransactionSellINActivity.this, "Amount  Valid", Toast.LENGTH_SHORT)
                        .show();
                }

Question:

I've tried get edittext value but does not work.This is my code in android fragment:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    final View v=inflater.inflate(R.layout.fragment_add_patient, container, false);
    final EditText FirstName=(EditText) v.findViewById(R.id.FirstName);
    final Button addPatientButton=(Button) v.findViewById(R.id.AddPatientButton);
    addPatientButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(isOnline()) {
                try {
                    if (FirstName.getText().toString().trim().equals("")) {
                        FirstName.setError("First Name is required!");
                        return;
                    }

I receive error at this line :FirstName.getText().toString().trim().equals("")

The error is following: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference.

Here is my fragment_add_patient xml file which contains all items.

<RelativeLayout 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"
tools:context="com.example.ionut.myapplication.PatientController.AddPatientFragment">

<!-- TODO: Update blank fragment layout -->

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="80dp"
    android:id="@+id/PatientFirstName"
    android:hint="First Name" />
<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textPersonName"
    android:ems="10"
    android:layout_marginTop="27dp"
    android:id="@+id/PatientLastName"
    android:hint="Last Name"
    android:layout_below="@+id/PatientFirstName"
    android:layout_alignLeft="@+id/PatientFirstName"
    android:layout_alignStart="@+id/PatientFirstName" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="textEmailAddress"
    android:ems="10"
    android:layout_below="@+id/PatientLastName"
    android:layout_alignRight="@+id/PatientLastName"
    android:layout_alignEnd="@+id/PatientLastName"
    android:layout_marginTop="25dp"
    android:id="@+id/Email"
    android:hint="Email" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:layout_marginTop="22dp"
    android:id="@+id/PatientAge"
    android:hint="Age"
    android:layout_below="@+id/Email"
    android:layout_alignLeft="@+id/Email"
    android:layout_alignStart="@+id/Email" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="phone"
    android:ems="10"
    android:layout_below="@+id/PatientAge"
    android:layout_alignLeft="@+id/PatientAge"
    android:layout_alignStart="@+id/PatientAge"
    android:layout_marginTop="32dp"
    android:id="@+id/PatientPhone"
    android:hint="Phone" />


<Button
    android:text="Add Patient"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/AddPatientButton"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="77dp" />

<Spinner
    android:id="@+id/cspinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="25dp"
    android:layout_below="@+id/PatientPhone"
    android:layout_alignRight="@+id/PatientPhone"
    android:layout_alignEnd="@+id/PatientPhone"
    android:layout_alignLeft="@+id/PatientPhone"
    android:layout_alignStart="@+id/PatientPhone" />

Thanks in advance!.


Answer:

The FirstName EditText is null because the findViewById method is trying to find an editext with the id of FirstName but the correct id is PatientFirstName

To solve the issue, replace the

final EditText FirstName=(EditText) v.findViewById(R.id.FirstName);

with

final EditText FirstName=(EditText) v.findViewById(R.id.PatientFirstName);

Question:

So, I saw that thing in the Todoist app. When you click the add fab, the keyboard pops up with some layout above it where you can enter text and set some things. How can I do it?

This is how the thing actually looks:

Is there some example on how this is done?

(please don't mind that this is the iOS version of the app, I don't own a android device)


Answer:

Make bottom sheet with fragment and edit text in fragment,and set button fab to show bottom sheet when clicked,,you can set the bottomsheet visibility GONE if you want

Question:

Layout: I have an EditText and 2 RecyclerViews inside a NestedScrollView, which are not visible (visibility=gone)

<androidx.coordinatorlayout.widget.CoordinatorLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    //... toolbar

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginBottom="?attr/actionBarSize"
            android:fillViewport="true"
            android:scrollbars="vertical">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/editText"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_weight="1"
                    android:backgroundTint="@android:color/transparent"
                    android:gravity="top"
                    android:inputType="textMultiLine|textCapSentences"
                    android:padding="@dimen/activity_margin"
                    android:singleLine="false" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rv_items"
                    android:padding="@dimen/activity_margin"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:scrollbars="vertical"
                    android:visibility="gone" />

                <androidx.recyclerview.widget.RecyclerView
                    android:id="@+id/rv_Labels"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:padding="12dp"
                    android:visibility="gone" />

            </LinearLayout>


        </androidx.core.widget.NestedScrollView>

    </LinearLayout>

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:id="@+id/coordinator_layout"
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:layout_gravity="bottom"
        android:layout_marginBottom="?actionBarSize" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        //...
    />


</androidx.coordinatorlayout.widget.CoordinatorLayout>

The problem: When I enter more text than the height of the screen, the EditText is scrolled down to where the cursor is. But when I try to scroll up, nothing happens. Here's a screen recording I made.

Can't scroll:

  • after entering/pasting long text for the 1st time.

Can scroll:

  • after reopening the activity with text already entered
  • after closing the keyboard
  • after closing the keyboard and opening it again

Searching for similar problems yielded:

  • EditText not scrollable inside ScrollView
  • Enable Scrollable EditText within a ScrollView and ViewFlipper
  • ... and other results with the same answer:

...

editText.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.editText) {
            v.getParent().requestDisallowInterceptTouchEvent(true);
            switch (event.getAction() & MotionEvent.ACTION_MASK) {
            case MotionEvent.ACTION_UP:
                v.getParent().requestDisallowInterceptTouchEvent(false);
                break;
            }
        }
        return false;
    }
});

That solution doesn't work:

  1. The questions are about ScrollViews, not NestedScrollViews. And NestedScrollView is one of the proposed solutions (which I already use)
  2. When I add the above code, the EditText is sort of scrollable, but only when the keyboard is shown. If it is not, then it's impossible to scroll - trying to scroll causes text to be selected.
  3. Scrolling (with the keyboard open) moves the cursor.

Please let me know if you need any more info or if I've missed anything. Thank you!


Answer:

The answer is actually simpler than I thought. After pasting your xml (and making the necessary changes for it to build - missing dimens. etc...) I just changed the height of your EditText to wrap_content and the bug was gone.

The answer lies here: Comparing the measurements of the EditText at different points in time, on the left with height=match_parent and on the right with height=wrap_content

On the left: The EditText is drawn on screen empty with a certain size, you paste the text and it's size doesn't change. Showing/Hiding the keyboard is one important event in the life of a screen, it's called a configuration change this causes elements to be measured again and re-drawn.

On the right: If you change the height of the EditText to wrap_content it will force a measure and re-draw immediately after insertion.

Hope this helps :)

Question:

I frequently have troubles with EditTexts and ArrayLists because I often use them. I was trying to take the inputted values from an inflatable edittext and put them into an ArrayList, but apparently, the values I am receiving are always 0,0,0. How can I fix this?

Here is the code that I thought would work:

public void addCourses() {
    LayoutInflater inflater = LayoutInflater.from(this);
    for (int i = 0; i < this.coursesList.size(); i++) {
        View v = inflater.inflate(R.layout.item_course, null, false);
        this.courses.addView(v);
        final int position = CalculateActivity.this.scoreList.size();
        final int position2 = CalculateActivity.this.totalList.size();
        CalculateActivity.this.scoreList.add(0);

        EditText Score = (EditText) v.findViewById(R.id.Score);
        EditText Total = (EditText) v.findViewById(R.id.Total);

        Score.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }


            public void afterTextChanged(Editable editable) {
                percentage = Integer.parseInt(editable.toString());
                int perc = (int) percentage;
                CalculateActivity.this.scoreList.set(position, perc);

            }
        });

        Total.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            public void afterTextChanged(Editable editable) {
                hundredth = Integer.parseInt(editable.toString());
                int hund = (int) percentage;
                CalculateActivity.this.scoreList.set(position2, hund);

            }
        });




    }
}

If you need any other code to help you figure this out, just put it in the comments.

EDIT::: The initialization of ScoreList and TotalList looks as such

ArrayList<Integer> gradesList = new ArrayList();
ArrayList<Integer> scoreList = new ArrayList();
ArrayList<Integer> totalList = new ArrayList();

Also, the code above is used here:

public void onClick(View view) {

        for (int x = 0; x < scoreList.size()&& x < totalList.size(); x++)

        {
            CalculateActivity.this.gradesList.add(scoreList.get(x) / totalList.get(x));

        }



        for (int i = 0; i <  CalculateActivity.this.gradesList.size(); i++) {
             int crdtHrs = ((Course) CalculateActivity.this.coursesList.get(i)).getCreditHours();

                totalCrdtHrs += (int) crdtHrs;
                averageGrade1 += (((int) CalculateActivity.this.gradesList.get(i)) * (((Course) CalculateActivity.this.coursesList.get(i)).getCreditHours()));
                averageGrade2 = averageGrade1/totalCrdtHrs;



        }

        int gpaCalc = averageGrade2;


        CalculateActivity.this.gpa.setText(String.format(""+gpaCalc));
    }
}

also the problem is that when I Log.d the ArrayList of scoreList or TotalList, the values return as 0,0,0 no matter what value I put in.


Answer:

use getText(). It would be simpler.

public void onCreate(Bundle savedInstanceState){

super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mButton = (Button)findViewById(R.id.button);
mEdit   = (EditText)findViewById(R.id.edittext);

mButton.setOnClickListener(
    new View.OnClickListener()
    {
        public void onClick(View view)
        {
            Log.v("EditText", mEdit.getText().toString());
        }
    });}

Question:

How to fix the tab at the bottom it moves up when I am trying to use the search (EditText) in on of my fragments

I want the tabs to hide behind the keypad.


Answer:

you can hide your tablayout when keyboard is visible

if(keyboardVisible)
      tabHost.setVisibility( View.GONE );    
 else
      tabHost.setVisibility( View.VISIBLE );

refer here to detect keyboard visibility

Question:

I am trying to create an expandable listview where the last item of every list contains an EditText and the other Items containing TextViews. The code I've come up so far:

@Override
public View getChildView(int groupPosition, final int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {
    MainActivity.ViewHolder holder = null;
    final String childText = (String) getChild(groupPosition, childPosition);
    boolean bLastChild = childPosition == _listDataChild.get(groupPosition).size() - 1;

    if (convertView == null) {
        holder = new MainActivity.ViewHolder();
        LayoutInflater infalInflater = (LayoutInflater) this._context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if(bLastChild) {
            convertView = infalInflater.inflate(R.layout.list_edit_item, null);
        }else {
            convertView = infalInflater.inflate(R.layout.list_item, null);
            holder.textView = (TextView) convertView.findViewById(R.id.text);
        }
        convertView.setTag(holder);
    } else {
        holder = (MainActivity.ViewHolder)convertView.getTag();
    }

    if(!bLastChild) {
        holder.textView.setText(childText);
    }

    return convertView;
}

Now I have the following Problem:

If I expand a group the first time it works. But when I collapse the group and expand it a second time the app crashes and I get the error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

I guess this happens because holder.textView.setText(childText); is called when the holder refers to the layout with the EditText. But I don't know why this happens

The main idea for this code comes from here

EDIT

After some logging I found out, that the second time the group is expanded getChildView is called once for every child and then one time more at childPosition = 0 but the convertView stays the same as in the call from the last childposition:

childPosition: 0; convertView: android.widget.LinearLayout{a049868 V.E...... ........ 0,157-1080,244} childPosition 1; convertView: android.widget.LinearLayout{6f19175 V.E...... ........ 0,247-1080,334} childPosition 2; convertView: android.widget.LinearLayout{4aac50a V.E...... ........ 0,337-1080,424} childPosition 3; convertView: android.widget.LinearLayout{47b217b V.E...... ........ 0,427-1080,514} childPosition 4; convertView: android.widget.LinearLayout{cc2eb98 V.E...... ........ 0,517-1080,604} childPosition 5; convertView: android.widget.LinearLayout{256cff1 V.E...... ........ 0,607-1080,694} childPosition 6; convertView: android.widget.LinearLayout{7b827d6 V.E...... ........ 0,697-1080,786} childPosition 0; convertView: android.widget.LinearLayout{7b827d6 V.E...... ........ 0,697-1080,786}


Answer:

Solved the problem by overriting the following two functions:

@Override
public int getChildTypeCount(){
    return 2;
}

@Override
public int getChildType(final int groupPosition, final int childPosition){
    if (childPosition == _listDataChild.get(groupPosition).size() - 1){
        return 1;
    }else{
        return 0;
    }
}

Question:

I'm attempting to create a note taker using Firebase and I'm falling at the first hurdle as I'm getting the error as per the title of this question.

My XML file is:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.frapp.NoteTakerActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay"
    android:id="@+id/appBarLayout2">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimaryDark"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Dark" />

</android.support.design.widget.AppBarLayout>

<include
    android:id="@+id/noteTitleTxt"
    layout="@layout/content_note_taker" />


<EditText
        android:id="@+id/noteTitleTxt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/appBarLayout2"
        android:ems="10"
        android:hint="Enter Title"
        android:inputType="text" />

    <Spinner
        android:id="@+id/spinnerNoteType"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/noteTitleTxt"
        android:layout_marginTop="13dp"
        android:entries="@array/type" />

    <Button
        android:id="@+id/addNoteBtn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/spinnerNoteType"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="19dp"
        android:text="Add Note" />


</RelativeLayout>

The java class in question is:

package com.example.android.frapp;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

public class NoteTakerActivity extends AppCompatActivity {

EditText editNoteTitle; // It's this causing the issue
Button addButton;
Spinner spinnerType;

DatabaseReference databaseNotes;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_note_taker);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    databaseNotes = FirebaseDatabase.getInstance().getReference("notes");

    editNoteTitle = (EditText) findViewById(R.id.noteTitleTxt);
    addButton = (Button) findViewById(R.id.addNoteBtn);
    spinnerType = (Spinner) findViewById(R.id.spinnerNoteType);

    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            addNote();
        }
    });

}

private void addNote() {
    String title = editNoteTitle.getText().toString().trim();
    String type = spinnerType.getSelectedItem().toString();

    if (!TextUtils.isEmpty(title)) {

        String id = databaseNotes.push().getKey(); // id being created is unique every time

        Notes notes = new Notes(id, title, type);

        databaseNotes.child(id).setValue(notes); // to send data to database

        Toast.makeText(this, "Title added", Toast.LENGTH_SHORT).show();

    } else {
        Toast.makeText(this, "You must give the note a title", Toast.LENGTH_SHORT).show();
    }
}

}

I've made sure I don't have any duplicate edit text names and got rid of any classes and xml files that are no longer needed just to be sure.

I've cleaned and rebuilt I don't know how many times but can't get past this issue. Does anyone have any other ideas I can use/try?

Thanks


Answer:

Here you have it twice!

<include
    android:id="@+id/noteTitleTxt"  // <-----------------
    layout="@layout/content_note_taker" />

<EditText
    android:id="@+id/noteTitleTxt"  // <-----------------

Just remove the one id in your include tag. While not shown in your post, I bet its top container is RelativeLayout.

Question:

here a snippet from one of the layouts in my ViewPager.

<android.support.design.widget.TextInputLayout
        android:layout_width="286dp"
        android:layout_height="wrap_content"
        android:id="@+id/textInputLayout2"
        android:layout_marginTop="15dp"
        android:weightSum="1">

        <EditText
            android:id="@+id/email"
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_email"
            android:inputType="textEmailAddress"
            android:singleLine="true"
            android:textColor="@android:color/white"/>

    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:layout_width="286dp"
        android:layout_height="wrap_content"
        android:id="@+id/textInputLayout"
        android:layout_marginTop="15dp"
        android:weightSum="1">

        <EditText
            android:id="@+id/password"
            android:layout_marginTop="30dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_password"
            android:inputType="textPassword"
            android:singleLine="true"
            android:textColor="@android:color/white"
            android:onClick="layoutBuilt"/>

    </android.support.design.widget.TextInputLayout>

And here is the layoutBuild void:

public void layoutBuilt(View view) {
        inputEmail = (EditText) findViewById(R.id.email);
        inputPassword = (EditText) findViewById(R.id.password);
        inputPassword.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    //ACTION DONE
                }
                return false;
            }
        });
}

So my Problem is, that the User must click two times at the Done Button, that it works.

NOTE: It works when I click on the passowordEditText manually and than click Done. When I am clicking on the EmailEditText type in my Email and click Next the passowordEditText will be automatically selected. And when I type in password and click Done. That doesnt work.

Why and how to fix it? Thanks in advance.


Answer:

Set the android:imeOptions to both of your `EditText.

<android.support.design.widget.TextInputLayout
    android:layout_width="286dp"
    android:layout_height="wrap_content"
    android:id="@+id/textInputLayout2"
    android:layout_marginTop="15dp"
    android:weightSum="1">

    <EditText
        android:id="@+id/email"
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_email"
        android:inputType="textEmailAddress"
        android:singleLine="true"
        android:imeOptions="actionNext"
        android:textColor="@android:color/white"/>

</android.support.design.widget.TextInputLayout>

<android.support.design.widget.TextInputLayout
    android:layout_width="286dp"
    android:layout_height="wrap_content"
    android:id="@+id/textInputLayout"
    android:layout_marginTop="15dp"
    android:weightSum="1">

    <EditText
        android:id="@+id/password"
        android:layout_marginTop="30dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_password"
        android:inputType="textPassword"
        android:imeOptions="actionDone"
        android:singleLine="true"
        android:textColor="@android:color/white"
        android:onClick="layoutBuilt"/>

</android.support.design.widget.TextInputLayout>

Question:

I need to get the value of an EditText inside a row of a tablelayout. I create the table, the row and the edittext dynamically. I had help getting the childcount, but I still can't seem to get the text that is inputted by the user into the edittext. Here's the xml code creating the base layout.

<RelativeLayout 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"
            tools:context = "com.example.neil.hvacbuilder.MainActivity" >
        <ScrollView
    android:layout_width = "match_parent"
    android:layout_height = "match_parent"
    android:id = "@+id/scrollView"
    android:layout_alignParentLeft = "true"
    android:layout_alignParentStart = "true"
    android:layout_below = "@+id/imgPartPicked" >

    <TableLayout
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"
        android:stretchColumns="*"
        android:id = "@+id/tblLayoutContent"
        android:layout_alignParentLeft = "true"
        android:layout_alignParentStart = "true"
        android:layout_alignParentBottom = "true" >
    </TableLayout >
</ScrollView >
</RelativeLayout >

Here's the code that generates the row and the edittexts inside the row.

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.part_detail);
    Bundle bundle = getIntent().getExtras();
    String btnName = bundle.getString("btnNameStored");
    String btnOrig = bundle.getString("btnOrig");

    TextView textView = (TextView) findViewById(R.id.txtBtnPushed);
    textView.setText(btnOrig);
    BufferedReader reader;
    InputStream is = null;

    // Get the name of the part picked and then grab the dimensions that are needed for that
    // part.

    try {

        is = getAssets().open(btnName);

        reader = new BufferedReader(new InputStreamReader(is));

        String line = reader.readLine();
        int lineLength = (line.length());

        TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);

        while (line != null){

            TableRow tblRow = new TableRow(this);
            tblRow.setPadding(5, 30, 5, 5);
            table.addView(tblRow);
            line = line.toUpperCase();

            // sets the max number of columns to 2 and iterates through the number of lines.
            // filling each cell with a Text Box with the name of each dimension of the part
            // that was picked. And a EditView for the user to put in the dimensions.

            for (int col = 0; col < NUM_COL; col++) {
                //This is the label of what measurement needs to be enter.
                TextView lblName = new TextView(this);
                // This is the number you enter for the measurement.
                EditText txtPartMeasurement = new EditText(this);

                txtPartMeasurement.setInputType(InputType.TYPE_CLASS_NUMBER |
                        InputType.TYPE_NUMBER_FLAG_DECIMAL);

                // Set all the input attributes for the text boxes.

                txtPartMeasurement.setTextSize(14);

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    txtPartMeasurement.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_END);
                }
                txtPartMeasurement.setEnabled(true);

                // Set all the input attributes for the labels of what needs to be entered.
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    lblName.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                }
                lblName.setBackgroundColor(getResources().getColor(R.color.colorPartMeasurements));
                lblName.setFocusable(true);
                lblName.setText(line);
                lblName.setTextSize(14);

                txtPartMeasurement.setTag(line);

                // Add the labels and text boxes to the grid.
                tblRow.addView(lblName);
                tblRow.addView(txtPartMeasurement);

                // Get the next line in the file if there is one.
                line = reader.readLine();
            }
        };

    }
    catch (IOException e) {
        e.printStackTrace();
    }

}

Here's the code that gives me the values entered by thee user, but it not worky right.

    @Override
public void onClick(View v) {
    Button button = (Button) v;
    String btnText = button.getText().toString();


    switch (v.getId()) {
        //This is the Save and Continue button. It saves the info entered and goes back to
        // pick the next part needed.
        case R.id.btnNextPartDetail:

            TableLayout PartDetailLayout = ((TableLayout) findViewById(R.id.tblLayoutContent));
            int childParts = PartDetailLayout.getChildCount();
            if (PartDetailLayout != null) {
                for (int i = 0; i < PartDetailLayout.getChildCount(); i++) {
                    View viewChild = PartDetailLayout.getChildAt(i);
                    if (viewChild instanceof EditText) {
                        // get text from edit text
                        String text = ((EditText) viewChild).getText().toString();

                    }
                    else if (viewChild instanceof TextView) {
                        // get text from text view
                        String text = ((TextView) viewChild).getText().toString();
                        //TODO: add rest of the logic
                    }
                }
            }

            Toast.makeText(getApplicationContext(),
                    "Button Save/Continue Selected",
                    Toast.LENGTH_LONG).show();
            break;

It gets me the count, but not the value. I don't know what the id will be of each edittext so I add a tag as each is created. But the tag is also dynamic as it comes from a file.

So, my question is what am I doing wrong and how do I get the value of each edittext. Mind you, there can be 10 or 14 or more edittexts in the table.

Sorry for the long post, but I wanted to be as complete as possible. Thanks.

Okay, Here's the working code. Again thanks

                TableLayout PartDetailLayout = ((TableLayout) findViewById(R.id.tblLayoutContent));
            int childParts = PartDetailLayout.getChildCount();
            if (PartDetailLayout != null) {
                for (int i = 0; i < childParts; i++) {
                    View viewChild = PartDetailLayout.getChildAt(i);
                    if (viewChild instanceof TableRow) {
                        int rowChildParts = ((TableRow) viewChild).getChildCount();
                        for (int j = 0; j < rowChildParts; j++) {
                            View viewChild2 = ((TableRow) viewChild).getChildAt(j);
                            if (viewChild2 instanceof EditText) {
                                // get text from edit text
                                String txtEdit = ((EditText) viewChild2).getText()
                                        .toString();

                            } else if (viewChild2 instanceof TextView) {
                                // get text from text view
                                String txttext = ((TextView) viewChild2).getText().toString();

                                //TODO: add rest of the logic
                            }
                        }
                    }
                }
            }

Answer:

The possible problem is that you check childs of TableLayout, but your EditText and TextView are in TableRow, so you need to check childs of childs.

I assume, that would be like that:

TableLayout PartDetailLayout = ((TableLayout) findViewById(R.id.tblLayoutContent));
        iTableLayout PartDetailLayout = ((TableLayout) findViewById(R.id.tblLayoutContent));
int childParts = PartDetailLayout.getChildCount();
if (PartDetailLayout != null) {
    for (int i = 0; i < childParts; i++) {
        View viewChild = PartDetailLayout.getChildAt(i);
        if (viewChild instanceof TableRow) {
            int rowChildParts = ((TableRow) viewChild).getChildCount();
            for (int j = 0; j < rowChildParts; j++) {
                View viewChild2 = ((TableRow) viewChild).getChildAt(j);
                if (viewChild2 instanceof EditText) {
                    // get text from edit text
                    String text = ((EditText) viewChild2).getText().toString();
                } else if (viewChild2 instanceof TextView) {
                    // get text from text view
                    String text = ((TextView) viewChild2).getText().toString();
                    //TODO: add rest of the logic
                }
            }
        }
    }
}

Question:

This phase is supposed to take all basic information and add so-called "Generals", as many as the user wants, but when I click on en "Enter your phone number" EditText, or any of the generals' EditTexts, and the virtual keyboard appears, the whole layout gets pulled up so that the focused EditText can be visible.

Problem is that I need to have the top ribbon containing "Confirm" button available at all occasions. I'm aware of the fact the user can fix that by pressing the Back button, but that'd be extremely unpractical. I need to know how to keep the ribbon up there after everything else gets pulled up by the mentioned EditTexts.

Screenshot of the layout before mentioned EditTexts are tapped: https://www.mediafire.com/convkey/2da9/4pa1balkda4y4d46g.jpg

Screenshot of the layout after mentioned EditTexts are tapped: https://www.mediafire.com/convkey/3f9e/so8qq8vud6m3h996g.jpg

Here is layout's XML. "topRibbonLL" LinearLayout should always keep its place at the top, while everything else should be pulled up by tapping the mentioned EditTexts.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/topRibbonLL"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <TextView
            android:id="@+id/firstDataTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="left|center_vertical"
            android:layout_weight="1"
            android:text="Step 3: First data"
            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button
            android:id="@+id/confirmButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="right"
            android:layout_weight="1"
            android:text="Confirm"
            android:onClick="newFileStep3ConfirmPressed" />

    </LinearLayout>

    <CheckBox
        android:id="@+id/shareableCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Other people can share my file" />

    <TextView
        android:id="@+id/shareableDescription"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingBottom="16dp"
        android:text="Description of the shareableCheckBox effect."
        android:textAppearance="?android:attr/textAppearanceSmall" />

    <ScrollView
        android:id="@+id/dataScrollView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <EditText
                android:id="@+id/dataFileName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:focusable="true"
                android:focusableInTouchMode="true" >
            </EditText>

            <EditText
                android:id="@+id/dataFullName"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="textPersonName"
                android:focusable="true"
                android:focusableInTouchMode="true" />

            <EditText
                android:id="@+id/dataAddress"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="textPostalAddress"
                android:focusable="true"
                android:focusableInTouchMode="true" />

            <EditText
                android:id="@+id/dataPhoneNumber"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:ems="10"
                android:inputType="phone"
                android:focusable="true"
                android:focusableInTouchMode="true" />

            <TextView
                android:id="@+id/textView2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:text="Generals:"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <LinearLayout
                android:id="@+id/generalsContainer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical" >

                <Button
                    android:id="@+id/newGeneralButton"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:text="Add new general"
                    android:onClick="newGeneralButtonPressed" />

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

</LinearLayout>

Necessary EditTexts are re-set-up after the layout is opened, so that they'd have grey text etc.

private void setupNewCardEditText(final EditText editText, final String text) {
    editText.setTextColor(R.integer.tempTextColor);
    editText.setText(text);
    editText.setGravity(Gravity.CENTER);
    editText.setFocusable(true);
    editText.setFocusableInTouchMode(true);

    editText.setOnFocusChangeListener(new OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                if (editText.getTextColors().getDefaultColor() == R.integer.tempTextColor) {
                    editText.setTextColor(0xFF000000);
                    editText.setText("");
                }
            } else {
                if (editText.getText().toString().equals("")) {
                    editText.setTextColor(R.integer.tempTextColor);
                    editText.setText(text);
                }
            }
        }

    });
}

Answer:

I solved my problem. I used low-priority threading with a while loop to re-position the ribbon whenever it's not on top and visible. I also had to change the root layout to RelativeLayout to I could have control of the coordinates.

Question:

I have a tablelayout with programmatically created table rows and a programmatically created edit text within each row. A table row is added by a click of a button which has the edit text named 'editTextTime' within each row. The 'editTextTime' is clickable, so when you click on it a time picker dialog appears. After the time is selected from the time picker it appears in 'editTextTime'.

But here's the problem, when the time is selected it appears in another 'editTextTime' too at the same time, if two rows were selected. I need the time after selection only to be set as text in the selected 'editTextTime' of the current row it is inside and not to appear inside any other 'editTextTime' from another row. How would I go about this?


Answer:

The problem (I suppose) is that you named all the EditTexts the same and the setTimeToEditText function is outside of the "programmatically creation code", so, you need to set the onClickListener for each one like this.

UPDATE I will post a simple example adding EditText programmatically

public class MainActivity extends Activity {


    LinearLayout myLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myLayout = (LinearLayout)findViewById(R.id.linearLayout);
        for(int i=0;i<5;i++) {

        final EditText myEditText = new EditText(MainActivity.this); // Pass it an Activity or Context
        //Stuff to make your edittext looks nice
        myEditText .setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) { //When you click on the            
                // Process to get Current Time
                final Calendar c = Calendar.getInstance();
                int mHour = c.get(Calendar.HOUR_OF_DAY);
                int mMinute = c.get(Calendar.MINUTE);

                TimePickerDialog tpd = new TimePickerDialog(MainActivity.this, //same Activity Context like before
                new TimePickerDialog.OnTimeSetListener() {

                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay,
                            int minute) {
                        myEditText.setText(hourOfDay + ":" + minute); //You set the time for the EditText created
                    }
                }, mHour, mMinute, false);
                tpd.show();

            }
        });
        myLayout.addView(myEditText);
        }
    }
}

Question:

My activity contains several EditTexts and CheckBoxes. Some of them are dynamically added by the user. I want to have an Array of all EditText- and CheckBox-objects. I use LinearLayout, RelativeLayout and TableLayout in my XML. I tried this:

public void getAllEditTextsAndCheckBoxes(View view){

    ArrayList<View> views = new ArrayList<View>();

    for (int i = 0; i < this.mainScrollView.getFocusables(View.FOCUS_FORWARD).size(); i++) {

       View actualView = mainScrollView.getFocusables(View.FOCUS_FORWARD).get(i);


        if(actualView instanceof EditText) {
            views.add((EditText) actualView);
        }
        if(actualView instanceof CheckBox) {
            views.add((CheckBox) actualView);
        }

    }

}

But this gives me only the EditTexts and not a single CheckBox Here is the structure of my messy xml file:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView>
   <LinearLayout>
      <!-- several LinearLayouts and Buttons-->
      <RelativeLayout>
         <TableLayout>
            <TableRow>
            </TableRow>

            <TableRow>
               <EditText/>
               **<CheckBox/>**
            </TableRow>

            <TableRow>
               <EditText/>
               **<CheckBox/>**
            </TableRow>
         </TableLayout>
      </RelativeLayout>
   <!-- some other LinearLayouts and Buttons -->
   </LinearLayout>

(I tried to leave out the unimportant information but since I don't know how much you need, I could not make it very short: http://pastebin.com/DnQnxtVJ)


Answer:

I've tested your module with the given layout and it's returning the result as expected. I've created a Fragment and passed the xml as a layout for it. Once the fragment gets added to the activity. I am able to extract all checkboxes and EditText views. Checked through the added logs.

    @Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        getAllEditTextsAndCheckBoxes(view);

    }

    public void getAllEditTextsAndCheckBoxes(View view){

        ArrayList<View> returnViews = new ArrayList<View>();

        ArrayList<View> focusableViews = view.getFocusables(View.FOCUS_FORWARD);

        for (int i = 0; i < focusableViews.size(); i++) {

            View actualView = focusableViews.get(i);

            if(actualView instanceof EditText) {
                returnViews.add((EditText) actualView);
            }
            if(actualView instanceof CheckBox) {
                returnViews.add((CheckBox) actualView);
            }

        }

        for(View mView: returnViews){
            if (mView instanceof  EditText){
                Log.d("ash_sow", "EditText Found!!");
            }
            else if(mView instanceof CheckBox){
                Log.d("ash_sow", "CheckBox Found!!");
            }
        }

    }

So I think It might be happening when you trying to add the component at runtime or it could be some other issue. So just try again and have a closer look at the probable suspects.

Question:

So i am having a very strange problem, i have an activity that shows user's posts and date in a ListView with a Custom ListView, gets from the server and populates them on onCreate.

this is how the interface looks of the activity

so what's happening is whenever i start the activity the edittext part was getting selected and generally the keyboard comes up

i googled to how to not focus the EditText at startup found by adding these two lines in the parent layout focus on the EditText can be prevented

android:focusable="true" 
android:focusableInTouchMode="true"

so i added that to the RelativeLayout xml of the activity this is the xml of the picture above

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/verticalLinear"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context=".UserHome">

    <EditText
        android:id="@+id/tweetText"
        android:layout_width="match_parent"
        android:layout_height="122dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:ems="10"
        android:hint="Write Your Tweet"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/userListHome"
        android:layout_alignParentEnd="true"
        android:onClick="postTweetFunction"
        android:text="Post" />


    <ListView
        android:id="@+id/userListHome"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:layout_below="@+id/tweetText"
        android:focusable="true"
        android:focusableInTouchMode="true"/>


</RelativeLayout>

Now about the problem part i needed to say above to make you understand what is the problem exactly cause its a strange one.

so the listview is not appearing until the editext is selected and the keyboard comes up

i am sure the listview is populating and the custom listview is working

but the listview content does not appear until i select the editext and the keyboard comes up, like the listview was sleeping until the editext is selected.

here is the example

see in that activity and the editext is not selected, so even thou the listview is populated it's not showing.

but as soon as i click on he edittext and the keyboard comes up its like it wokes up the sleeping listview

and the listview and adapter is not anonymous i have defined them here is the activity code if needed for reference

public class UserHome extends AppCompatActivity {

    ListView listView;
    ArrayList<String> userOwnTweets;
    ArrayList<String> userOwnTweetsDate;
    ArrayList<String> getUserOwnTweetsObjectId;
    EditText tweetText;
    CustomArrayAdapter customArrayAdapter;
    Typeface custom_font1, custom_font2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_home);

        custom_font1 = Typeface.createFromAsset(getAssets(),  "fonts/gooddog.otf");
        custom_font2 = Typeface.createFromAsset(getAssets(),  "fonts/quicksand.otf");

        listView = (ListView) findViewById(R.id.userListHome);
        tweetText = (EditText) findViewById(R.id.tweetText);

        userOwnTweets = new ArrayList<String>();
        userOwnTweetsDate = new ArrayList<String>();
        getUserOwnTweetsObjectId = new ArrayList<String>();


        customArrayAdapter = new CustomArrayAdapter(getApplicationContext());
        listView.setAdapter(customArrayAdapter);


        // updating the tweets onCreate
        updateTweetList();

    }


    public void updateTweetList(){

        // clearing the lists to avoid duplicate entries
        userOwnTweets.clear();
        userOwnTweetsDate.clear();
        getUserOwnTweetsObjectId.clear();



        // just backend code to get the tweets of the user
        ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Tweet");
        query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {

                if (e == null && objects.size() > 0){

                    for (ParseObject object : objects){

                        String tempString = object.getString("tweet");
                        tempString = tempString.substring(0, Math.min(tempString.length(), 20));
                        tempString+="...";

                        // adding them to the arraylists
                        userOwnTweets.add(tempString);
                        userOwnTweetsDate.add(object.getString("date"));
                        getUserOwnTweetsObjectId.add(object.getObjectId());
                    }
                }
            }
        });

        // updating the customlistview for datastatechanged
        customArrayAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
        finish();
    }

    public void postTweetFunction(View view){



        // adding a new tweet and refreshing the tweet list from teh server
        ParseObject userTwitter = new ParseObject("Tweet");
        userTwitter.put("tweet", tweetText.getText().toString());
        userTwitter.put("username", ParseUser.getCurrentUser().getUsername());
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        userTwitter.put("date", String.valueOf(dateFormat.format(new Date())));
        userTwitter.saveInBackground(new SaveCallback() {
            @Override
            public void done(ParseException e) {

                if (e == null) {

                    Toast.makeText(getApplicationContext(), "Tweet Added", Toast.LENGTH_SHORT).show();
                    tweetText.setText("");
                    updateTweetList();

                }
            }
        });
        hideKeyBoard();


    }

    public void hideKeyBoard(){


        // hiding the keyboard
        try {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }


    // the custom adapter
    class CustomArrayAdapter extends BaseAdapter {

        Context context;
        LayoutInflater layoutInflater;

        // Constructor
        public CustomArrayAdapter(Context context) {
            this.context = context;
            layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return userOwnTweets.size();
        }

        @Override
        public Object getItem(int position) {
            return userOwnTweets.get(position);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {

            view = layoutInflater.inflate(R.layout.row_layout, null);

            TextView userHomeTweet = (TextView) view.findViewById(R.id.userHomeTweet);
            TextView userHomeTweetdate = (TextView) view.findViewById(R.id.userHomeTweetDate);
            userHomeTweet.setTypeface(custom_font1);
            userHomeTweetdate.setTypeface(custom_font2);

            try {
                userHomeTweet.setText(userOwnTweets.get(i));
                userHomeTweetdate.setText(userOwnTweetsDate.get(i));
            }catch(Exception e){
                e.printStackTrace();
            }

            // random color for each

            int color = Color.LTGRAY;
            view.setBackgroundColor(color);

            return view;
        }
    }

}

i have used proper commenting, the code is simple enough , i am just using a Server with MongoDB i have commented on them.

and this is the customlistview layout xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/userHomeTweet"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:textSize="40dp"
        />

    <TextView
        android:id="@+id/userHomeTweetDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="49dp"
        android:textSize="20dp" />


</RelativeLayout>

each of the listview element has a each this layout inside them hence making it a customlistview

SO here is everything i am as clear as possible, but ask me if i missed anything that may make a difference in solving the issue

so can you tell me, why the listview does not show up until i select the EditText and the Keyboard comes up, seems like a strange problem, please point me in the right direction. Thanks.


Answer:

Try this

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/verticalLinear"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusable="true"
    android:focusableInTouchMode="true"
    tools:context=".UserHome">

    <EditText
        android:id="@+id/tweetText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_toStartOf="@id/button"
        android:ems="10"
        android:hint="Write Your Tweet"
        android:inputType="textPersonName" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/userListHome"
        android:layout_alignParentEnd="true"
        android:onClick="postTweetFunction"
        android:text="Post" />


    <ListView
        android:id="@+id/userListHome"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/tweetText"
        android:layout_alignParentBottom="true" />


</RelativeLayout>

EDIT

public void updateTweetList(){

        // clearing the lists to avoid duplicate entries
        userOwnTweets.clear();
        userOwnTweetsDate.clear();
        getUserOwnTweetsObjectId.clear();



        // just backend code to get the tweets of the user
        ParseQuery<ParseObject> query = new ParseQuery<ParseObject>("Tweet");
        query.whereEqualTo("username", ParseUser.getCurrentUser().getUsername());
        query.findInBackground(new FindCallback<ParseObject>() {
            @Override
            public void done(List<ParseObject> objects, ParseException e) {

                if (e == null && objects.size() > 0){

                    for (ParseObject object : objects){

                        String tempString = object.getString("tweet");
                        tempString = tempString.substring(0, Math.min(tempString.length(), 20));
                        tempString+="...";

                        // adding them to the arraylists
                        userOwnTweets.add(tempString);
                        userOwnTweetsDate.add(object.getString("date"));
                        getUserOwnTweetsObjectId.add(object.getObjectId());
                    }

                   // updating the customlistview for datastatechanged
                   customArrayAdapter.notifyDataSetChanged();
                }
            }
        });


    }

Question:

I have defined the EditText like below

<EditText
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:id="@+id/searchText"
    android:paddingStart="16dp"
    android:backgroundTint="@color/grey"
    android:drawableStart="@drawable/searchsmall"
    android:drawablePadding="15dp"
    android:padding="10dp"
     />

The output.

I have set the android:drawablePadding but text is not moving to the right.

I want he results like below.

How can I do it ?

Thanks


Answer:

you can use below code

 android:drawablePadding="5dp"