一般来说是android和编程的新手,所以学习我的概念.
我有一个LinearLayout,我动态添加edittexts.
我需要能够在选择或焦点时获取任何edittext的索引和ID.
我已经尝试循环子计数以检查选择如下:
int count = llmain.getChildCount();
for (int i=0; i< count; ++i) {
if ((llmain.getChildAt(i).isSelected()) == true){
//Do Stuff
}
Run Code Online (Sandbox Code Playgroud)
但我不知道它是否接近,这只是索引......
非常感谢帮助!
谢谢
编辑:仍然没有一个可靠的方法来实现这一目标.下面的例子用
if(v instanceOf EditText) {
id = v.getId();
index = ll.indexOfChild(v);
Run Code Online (Sandbox Code Playgroud)
为索引返回-1,为id返回10位数,但是,我在创建时分配id.?奇怪的是"if"中的代码正在运行,所以它至少认为它具有焦点视图.现在,如果我将"instanceof"更改为null检查,就像
if (v != null){
id = v.getId();
index = llmain.indexOfChild(v);
Run Code Online (Sandbox Code Playgroud)
我添加了一个setFocusableInTouchMode(true),我得到一个正确的返回,然而,它然后就像我调用clearFocus(),因为没有一个EditTexts被聚焦.这是我的概念代码的完整证明,它返回正确的值,但不再让EditTexts实际上具有焦点.
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&(event.getKeyCode() == 66)) // KeyEvent.* lists all the key codes u pressed
{
View myView = linflater.inflate(R.layout.action, null);
myView.setId(pos);
pos++;
myView.setFocusableInTouchMode(true);
llmain.addView(myView);
myView.requestFocus();
View v = llmain.findFocus();
if (v != null){
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();
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
这将返回正确的值,除非我注释setFocusableInTouchMode行,然后它返回奇数-1表示索引,十位表示ID.我究竟做错了什么?必须是一个好的(和工作)答案,以超过我的代表的一半.....
所以没有人有解决方案吗?它仍然让我疯狂!
再次感谢
我最初的想法是在添加EditText时将ID设置为等于索引,假设只有EditTexts将在此特定布局中:
LinearLayout llMain = (LinearLayout)findViewById(R.id.llmain);
EditText editText = new EditText(this);
//0-based index, so get the number of current views, and use it for the next
editText.setId(llMain.getChildCount());
llMain.addView(editText);
Run Code Online (Sandbox Code Playgroud)
然后,要检索信息,请将检查放入某种类型的侦听器(onTouch,onFocus,类似的东西):
@Override
public void onTouch(View v, MotionEvent ev) {
int indexAndId = v.getId();
}
Run Code Online (Sandbox Code Playgroud)
试一试:
LinearLayout ll = (LinearLayout)findViewById(R.id.ll);
int index, id;
//finds the currently focused View within the ViewGroup
View v = ll.findFocus();
if(v instanceOf EditText) {
id = v.getId();
index = ll.indexOfChild(v);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3536 次 |
| 最近记录: |