【问题标题】:Android get text from buttonAndroid从按钮获取文本
【发布时间】:2014-06-09 20:24:51
【问题描述】:

我的屏幕上有 6 个Buttons

我需要检查每个Button 上的文本,如果结果是大写“X”,那么我需要使Button 不可见

我可以在点击Button 时获取文本

Button b = (Button)view;
String text = b.getText().toString();

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

任何帮助表示赞赏

标记

【问题讨论】:

  • 你是什么意思:但是没有它你怎么得到它?
  • 你是想说不被点击吗?
  • 如果您需要对我的回答进行更多说明,请告诉我。
  • 感谢大家的帮助,我现在理解并得到了它的工作

标签: android button text get


【解决方案1】:

有不同的选择。如果这是 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.

对于听众等可能有更简单的方法,但如果没有更多信息,这是我能给你的最好的。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这是我的创建 - super.onCreate(savedInstanceState); setContentView(R.layout.firstscreen); - 无法找出上面的其他答案
    • 很高兴你能弄明白。如果对您有帮助,您应该回复您的确切解决方案或接受其他人的回答。
    猜你喜欢
    • 2014-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-05
    • 1970-01-01
    • 2021-03-18
    • 2013-09-12
    相关资源
    最近更新 更多