将字符串值转换为按钮名称

时间:2019-04-13 11:28:52

标签: java android

在VB中,您使用CType将字符串转换为控件的名称

Dim btn1 as Button
Dim Str as String ="btn1"
CType((Str), Button).Text ="your text"

如何在Java中实现相同的目标?

2 个答案:

答案 0 :(得分:1)

如果您有ID(名称)为btn1btn2,....,btn20之类的按钮,并且希望通过for循环设置其文本,则可以使用getIdentifier()像这样:

for (int i = 1; i <= 20; i++) {
    int id = getResources().getIdentifier("btn" + i, "id", getPackageName());
    Button button = findViewById(id);
    button.setText("something" + i);
}

方法getIdentifier()采用View的ID(名称)并返回其整数ID。
然后用findViewById(id)获得对该View的引用。
如果您的代码不在活动类之内,则可能需要用有效的getResources()来对getPackageName()Context进行限定,例如:

int id = context.getResources().getIdentifier("btn" + i, "id", context.getPackageName());

答案 1 :(得分:0)

如果您要设置按钮显示的文本,则类似:-

    Button btn1 = this.findViewById(R.id.done); // Gets the Button as per the id in the layout.
    btn1.setText("Your Text");
  • 在某些旧版本的Android Studio中,您必须专门从findViewById强制转换类型,例如上述使用Button btn1 = (Button) this.findViewById(R.id.done);

其他评论:-

  

我最多有20个按钮btn1 ......... btn20,然后我想使用循环   引用此按钮,这意味着我需要一个btn字符串和一个   数字的整数。连接字符串和整数将得到   我是实际的按钮名称。

我相信以下内容可能符合您的要求。这将创建20个按钮,并将它们添加到布局中。

每个将设置两个字段/成员。 -文本(由按钮显示的文本)字段将设置为我的按钮#?(其中?为1-20) -Tag(可以根据需要使用的字段)将设置为String,它是ArrayList中相应Button的偏移量(即0-19)。

每个人都将添加一个onClickListener,它将发出一个Toast,详细说明Text和Tag的Button值。

此外,通过根据按钮的“文本”值或“标签”值搜索按钮来实现对按钮的引用。给出了两个示例,其中搜索 0 ,首先是Tag值(将被发现为0),然后是Text值(将不会被发现)。结果被写入日志。

public class OtherActivity extends AppCompatActivity {

    ArrayList<Button> mButtons = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_other);
        LinearLayout mMainLayout = this.findViewById(R.id.mainlayout);

        // Add the 20 buttons dynamically assigning Text and a Tag
        for (int i=0; i < 20; i++) {
            Button current_button = new Button(this);
            current_button.setText("My Button #" + String.valueOf(i + 1));
            current_button.setTag(String.valueOf(i));
            mButtons.add(current_button);
            mMainLayout.addView(current_button);
            current_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(
                            v.getContext(),
                            "You CLicked on the Buttton with Text as :-" + ((Button) v).getText().toString() + " Tag as " + ((Button)v).getTag(),
                            Toast.LENGTH_SHORT
                    ).show();
                }
            });
        }

        // Search for the button according to some text    
        // Should work as Tag has been set to 0
        Button button_to_use = findButtonByTagOrText("0",true,mButtons);
        if (button_to_use != null) {
            Log.d("BUTTONFINDRESULT","Button 0 Found according to the Tag");
        } else {
            Log.d("BUTTONFINDRESULT","Button 0 NOT FOUND acording to Tag");
        }

        //Will not find button as text will not be o but will instead be My Button #1 (for the first button)
        button_to_use = findButtonByTagOrText("0", false,mButtons);
        if (button_to_use != null) {
            Log.d("BUTTONFINDRESULT","Button 0 Found according to the Text");
        } else {
            Log.d("BUTTONFINDRESULT","Button 0 NOT FOUND acording to Text");
        }
    }

    /**
     * Find the button according to it's TAG or Text
     * @param value_to_find     The String to find
     * @param look_for_tag      true if to look at the Tag, false if to look at the Text
     * @param button_list       The ArrayList<Button> aka the list of buttons
     * @return                  null if not found, else the Button object
     */
    private Button findButtonByTagOrText(String value_to_find, boolean look_for_tag, ArrayList<Button> button_list) {
        Button rv = null;
        String compare_string;
        for (Button b: button_list) {
            if (look_for_tag) {
                compare_string = (String) b.getTag();
            } else {
                compare_string = b.getText().toString();
            }
            if (value_to_find.equals(compare_string)) {
                return b;
            }
        }
        return rv; // Note returned button will be null if text not found.
    }
}

结果是该应用程序在运行时显示为:-

enter image description here

  • 请注意,“完成”按钮位于布局中,因为上面的代码中没有使用或处理它,因此可以将其忽略。

单击按钮会根据单击的按钮显示Toast,例如:-

enter image description here

日志包括(如预期的那样):-

04-13 22:41:20.068 15617-15617/? D/BUTTONFINDRESULT: Button 0 Found according to the Tag
04-13 22:41:20.068 15617-15617/? D/BUTTONFINDRESULT: Button 0 NOT FOUND acording to Text
相关问题