0

I have a ScrollView which cointains a Linear Layout, When I create and add a EditText programatically to the layout my code is supposed to scroll to the bottom, but then the focus goes to the second from bottom field instead of what I want which is for it to focus the bottom field and I can't work out why.

Here is the code:

public void addPlayer(View view){
    ScrollView scrollview = (ScrollView) findViewById(R.id.PlayerAddScroll);
    EditText tv = new EditText(this);
    tv.setHint("Player " + (playerCount + 1));
    playerCount++;
    tv.setSingleLine(true);
    LinearLayout playerListView = (LinearLayout) findViewById(R.id.playerListView);
    playerListView.addView(tv);
    playerFields.add(tv);
    scrollview.post(scrollBottom);
}

This is what scrollBottom does

Runnable scrollBottom=new Runnable() {
    @Override
    public void run() {
        ScrollView scrollView = (ScrollView) findViewById(R.id.PlayerAddScroll);
        scrollView.fullScroll(ScrollView.FOCUS_DOWN);
    }
};

My code causes this (Not focusing last field):

enter image description here

Abdelilah El Aissaoui
  • 4,204
  • 2
  • 27
  • 47
Troy Swan
  • 3
  • 3

3 Answers3

0

Found a fix by adding android:paddingBottom="5dp" to my LinearLayout in the XML.

Abdelilah El Aissaoui
  • 4,204
  • 2
  • 27
  • 47
Troy Swan
  • 3
  • 3
0

change your code like this and it will work fine !

    Runnable scrollBottom = new Runnable() {
    @Override
    public void run() { 
        //This linear is the linearLayout which you added your textView to it 
        LinearLayout playerListView = (LinearLayout) findViewById(R.id.ll);
        playerListView.getChildAt(playerListView.getChildCount()-1).requestFocus();

    }
};
Amir Hossein Mirzaei
  • 2,325
  • 1
  • 9
  • 17
0

I have tried to dynamically request focus for the last EditText after fullScroll method. the code is in the Runnable scrollBottom

ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
        scrollView.fullScroll(ScrollView.FOCUS_DOWN);

LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearLayout);
EditText editText = (EditText) linearLayout.getChildAt(linearLayout.getChildCount() - 1);
        editText.requestFocus();
D.Jiang
  • 199
  • 5