gpt4 book ai didi

android - 获取所选 edittext 的索引和 id 以进行进一步处理

转载 作者:太空宇宙 更新时间:2023-11-03 12:42:07 25 4
gpt4 key购买 nike

对 Android 和一般编程来说是新手,所以边学边学概念。

我有一个要动态添加编辑文本的 LinearLayout。

我需要能够在选中或获得焦点时获取任何编辑文本的索引和 ID。

我试过像这样循环遍历子计数来检查选中的:

int count = llmain.getChildCount();
for (int i=0; i< count; ++i) {
if ((llmain.getChildAt(i).isSelected()) == true){
//Do Stuff
}

但我不知道它是否接近,那将仅用于索引......

帮助将不胜感激!

谢谢

编辑:仍然没有可靠的方法来实现这一点。下面的示例带有

if(v instanceOf EditText) {
id = v.getId();
index = ll.indexOfChild(v);

索引返回 -1,ID 返回十位数字,但是,我在创建时分配了一个 ID。 ?奇怪的是,“if”中的代码正在运行,所以它至少认为它有焦点 View 。现在,如果我将“instanceof”更改为空检查,例如

if (v != null){
id = v.getId();
index = llmain.indexOfChild(v);

然后我添加了一个 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;
}

这将返回正确的值,除非我注释掉 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);

然后,要检索信息,请检查某种类型的监听器(onTouch、onFocus 等):

@Override
public void onTouch(View v, MotionEvent ev) {
int indexAndId = v.getId();
}

试一试:

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

关于android - 获取所选 edittext 的索引和 id 以进行进一步处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5981108/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com