新的編程和Android,所以我真的不知道我在做什麼。任何人都可以告訴我爲什麼這個代碼爲索引返回-1的不正確值,併爲id的10位數字,當我清楚地分配一個id和索引不應該-1,因爲它的0基於??代碼問題查找ID和索引
我會認爲問題是在獲取焦點視圖的代碼中的某個地方,但是我嘗試了findFocus和getCurrentFocus,並且都返回相同的東西。這是代碼,謝謝!
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();
CharSequence text = "index is:" + index + "id is:" + id;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
此代碼何時運行?如果在'onCreate'期間,那麼焦點可能還沒有被分配......此外,'requestFocus'不保證立即授予焦點。 – 2011-05-13 16:06:29
您應該檢查'requestFocus'的返回值以確定它成功。另外,當參數不是子視圖時,'indexOfChild'返回'-1'。 – 2011-05-13 16:14:30