This is for my Android App. I have two EditText fields set to a maximum of one character that can be input in each field. Once the user inputs the first character I would like the focus to automatically jump to the second EditText field. I set up an addTextChangedListener on the first Edit Text and had it listen for when the text string is > 1. Then I call request focus on the second Edit Text. However, I keep receiving a force close when I input the character in the first Edit Text box. From what I've looked on StackOverflow, this should work. Anyone have any idea why it is not? I posted the relevant code below. Thanks.
LinearLayout llview = new LinearLayout(this);
llview.setOrientation(LinearLayout.VERTICAL);
EditText character1 = new EditText(this);
EditText character2 = new EditText(this);
character2.setId(2);
character1.addTextChangedListener(new TextWatcher(){
EditText character2 = (EditText) findViewById(2);
@Override
public void afterTextChanged(Editable s) {
if(s.length()>0)
{
character2.requestFocus();
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after){}
@Override
开发者_如何学C public void onTextChanged(CharSequence s, int start, int before,int count) {}
});
llview.addView(character1);
llview.addView(character2);
this.setContentView(llview);
I'm not sure that you've posted all of the relevant code. It would seem that you are building your view hierarchy programmatically (rather than using a layout file), yet there is no code showing where you insert character1 and character2 into the view hierarchy. It would be helpful if you posted the code for building your view hierarchy.
Also, what debugging steps have you attempted so far? Have you set breakpoints to confirm that your variables are not null pointers when you invoke methods on them? Have you done a stack trace?
If I was to guess just based on this code segment you posted, then I would have to guess that you haven't inserted character1 and character2 into your activity's view hierarchy and findViewById(2) is simply returning null. Have you checked to see that findViewById(2) is in fact returning something other than null?
精彩评论