code problem finding id and index
new to programming and android, so I really have no idea what im doing. can anyone tell me why this code returns incorrect values of -1 for index and a 10 digit number for id, when I clearly assign an id and the index should not be -1 because its 0 based??
I would think that the problem is somewhere in the code that gets the focused view, but ive tried findFocus and getCurrentFocus, and both return the same thing. Here is the code, thanks!
llmain = (LinearLayout) findViewById(R.id.linearLayoutMain);
linflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
int pos = 0;
View myView = linflater.inflate(R.layout.action, null);
myView.setId(pos);
pos++;
llmain.addView(myView);
myView.requestFocus();
View v = getCurrentFocus();
if(v instanceof EditText) {
id = v.getId();
index = llmain.indexOfChild(v);
Context context = getApplicationContext();
CharSe开发者_JAVA技巧quence text = "index is:" + index + "id is:" + id;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
In android a Views Id is a Long that is a unique Identifier for that View. It is best not to reference by using this number but instead to use R.id.viewIdSuppliedInLayout that way you can use descriptive text instead of trying to keep straight which numbers point to which views. If you are creating dynamic views like you appear to be doing it will be assigned an Id, you shouldn't have to set it. In your inflate() method you should pass R.id.actionsRootViewID as the second parameter. My gut instinct is that this is why indexOf is returning -1, because it can't find the view that you are looking for. 0 would be the first view in the layout, since it isn't finding your view it needs to let you know somehow that it failed to find, so they chose to have it return -1 to indicate this.
精彩评论