无法专注于最后的EditText

时间:2018-06-03 16:08:55

标签: java android

我有一个ScrollView,它包含了一个线性布局, 当我以编程方式创建EditText并将其添加到布局时,我的代码应该滚动到底部,但是然后焦点会转到底部字段的第二个而不是我想要的那个,它可以聚焦底部字段而我可以'找出原因。

以下是代码:

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);
}

这就是scrollBottom所做的事情

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

我的代码会导致此问题(不关注最后一个字段):

enter image description here

3 个答案:

答案 0 :(得分:0)

通过在XML中将android:paddingBottom="5dp"添加到我的LinearLayout来找到修复程序。

答案 1 :(得分:0)

像这样更改你的代码,它会正常工作!

    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();

    }
};

答案 2 :(得分:0)

我试图在fullScroll方法之后动态请求焦点为最后一个EditText。代码在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();