Android从按钮获取文本

时间:2014-06-09 20:24:51

标签: android button text get

我的屏幕上有6 Buttons

我需要检查每个Button上的文字,如果结果是大写“X”,那么我需要让Button隐身

我可以在使用此

点击Button时获取文字
Button b = (Button)view;
String text = b.getText().toString();

但是如何在不点击Button的情况下获得它?

任何帮助表示赞赏

标记

2 个答案:

答案 0 :(得分:0)

在活动的onCreate(或片段的onCreateView)中,您需要使用findViewById来获取应用上的视图。

获得视图后,您可以查询其内容并设置侦听器以查看它们何时更改。

答案 1 :(得分:0)

有不同的选择。如果这是View的唯一类型,那么您可以使用类似

的内容遍历布局的子项
for (int i=0; i<myLL.getChildCount(); i++) // assuming you have  a LinearLayout named myLL
{
     Button btn = (Button) myLL.getChildAt(i);  // cast the View to a Button
     String text = btn.getText().toString();
     // check the text here and do what you need
}

或者您可以在开头将它们放在ArrayList中,然后迭代它并使用类似

的内容检查文本
ArrayList<Button> myBtns = new ArrayList<Button>();
myBtns.add(R.id.someBtnId);
// iterate through them when needed.

听众可能会有更简单的方式,但没有更多信息,这是我能给你的最佳方式。