动态按钮和OnClickListener按钮、动态、OnClickListener

2023-09-06 11:22:43 作者:眼眸熏染柔情

说我有一个动态创建按钮:

Say I have buttons that are created dynamically:

for(int j = 0; j < spirits.length;

     j++){
                         Button imgBtn = new Button(v.getContext());
                         imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
                         imgBtn.setMinimumWidth(100);
                         imgBtn.setMinimumHeight(100);
                         imgBtn.setId(j+1);
                         imgBtn.setTag(spirits[j]);
                         imgBtn.setText(spirits[j]);
                         imgBtn.setOnClickListener(new SpiritsClickListener());
                         cabinet_layout.addView(imgBtn);
                     }

我希望每一个它的pressed时间(开 - 关),以改变按钮的文本我怎么可以参考的按钮OnClickListener类中?

I want to change the text of the button every time it's pressed (On - Off) How can I reference the buttons within the OnClickListener class?

推荐答案

在您的onClickListener,你有一个调用的函数的onClick(视图v){} ,其中 v 是用户点击查看。您可以使用 v 来获取有关按钮的详细信息,包括其ID。你也可以采取这种观点,如果你知道它是一个按钮,将其转换为一个按钮。

in your onClickListener, you have a function called onClick(View v){} where v is the View that was clicked. You may use v to get details about the button, including its ID. You can also take this view, and if you know it is a button, cast it to a button.

Button clicked = (Button)v;

您可以使用它在你的java code,就像你通常会使用一个按钮。

You can then use it in your javacode just as you would normally use a button.