简体   繁体   English

Android Studio(java)使用字符串查找视图ID

[英]android studio(java) finding view id with string

I'm making a calculator for just a practice, but I found that there are so many buttons. 我只是为了练习而制作计算器,但发现按钮太多了。 I named their id like button+row+col ex) row=5, col=4 -> id=button54 我将他们的ID命名为button + row + col ex)row = 5,col = 4-> id = button54

Since I have to attack listener to every button, I found it very annoying things to do this manually. 由于我必须攻击监听器的每个按钮,因此我发现手动执行此操作非常烦人。 Like, 喜欢,

findViewById(R.id.button11).setOnClickListener(this);
findViewById(R.id.button12).setOnClickListener(this);
...
findViewById(R.id.button95).setOnClickListener(this);

Can I do this like 我可以这样吗

for(int i=1; i<=9; i++){
    for(int j=1; j<=5; j++){
        findViewById(R.id."button"+Integer.toString(i) + Integer.toString(j)).setOnClickListener(this);
    }
}

or other way to make this easier. 或其他方法来简化此过程。

在此处输入图片说明

You can't do that. 你不能那样做。 2 possibilities : 2种可能性:

  • create an Array with yours ID, to be able to use a for loop 使用您的ID创建一个数组,以便能够使用for循环
  • use ButterKnife with @BindViews annotation ButterKnife@BindViews批注一起使用

Since you're working with a lot of buttons I suggest you put them all into a ViewGroup (like LinearLayout, FrameLayout or something like that), then iterate through each View of that ViewGroup, check its instance then assign the click listener. 由于您正在使用许多按钮,因此建议您将它们全部放入一个ViewGroup中(例如LinearLayout,FrameLayout或类似的东西),然后遍历该ViewGroup的每个View,检查其实例,然后分配单击侦听器。

Here is some pseudo-code since I forgot how Java works 这是一些伪代码,因为我忘记了Java是如何工作的

ViewGroup viewGroup = findViewById(R.id.yourViewGroupName);
for each child in viewGroup.getChildren {
    if child is of type Button {
        child.setOnClickListener(this);
    }
}

I think you should add an onClick "ID" in your xml and let Android Studio do the work. 我认为您应该在XML中添加onClick“ ID”,然后让Android Studio来完成。

<Button
        android:id="@+id/bt_54"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:clickable="true"
        android:focusable="true"

        android:onClick="oc_bt_54"
        />

and now in your xml file hover over the onClick, which should be underlined red and go to the red light bulb on the left. 现在在您的xml文件中,将鼠标悬停在onClick上方,该光标应用红色加下划线并转到左侧的红色灯泡。 Your Option: Creat Method in Activity xy. 您的选择:活动xy中的创建方法。

and now in your Activity you will see: 现在在“活动”中,您将看到:

 public void oc_bt_54(View view) {

    }

No need for findViewByID() . 无需findViewByID() Very easy and clean solution. 非常简单和干净的解决方案。

(Tip: if you need the onClick method created in a special Activity, use: (提示:如果需要在特殊活动中创建的onClick方法,请使用:

tools:context=".your_special_Activity"

in the main layout of your xml.) 在xml的主布局中。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM