【问题标题】:How to get ids of widget without setcontent view?如何在没有 setcontent 视图的情况下获取小部件的 ID?
【发布时间】:2014-05-21 06:29:54
【问题描述】:

我是 android 新手。我有一个简单的疑问,有没有办法从某个布局中获取小部件的 id 而无需将其设置为内容视图?我希望从一个类中隐藏一个视图。我使用了代码

 View  b = findViewById(R.id.id2);
 b.setVisibility(View.GONE);

但是“id”中的错误,如果没有设置为 contentview 的 java 类中的小部件是否可以获取 id?请帮我。在此先感谢:)

【问题讨论】:

    标签: android layout setcontentview


    【解决方案1】:

    您可以单独扩展视图,然后在扩展布局的根上使用findViewById

    // inside of Activity, you can use 'this' for the context
    LayoutInflater inflater = LayoutInflater.from(context);
    View root = inflater.inflate(R.layout.some_layout);
    // from your example
    View b = root.findViewById(R.id.id2);
    b.setVisibility(View.GONE);
    

    然而,此时这些视图不是 Activity 视图层次结构的一部分,用户不会看到。您必须通过使用setContentView(root) 或在当前视图层次结构中找到ViewGroup 并调用viewGroup.addView(root) 来添加它们。

    【讨论】:

      【解决方案2】:

      你可以这样做

      Button filterButton = new Button(YourActivity.this);
      filterButton.setVisibility(filterButton.GONE);
      

      【讨论】:

        【解决方案3】:

        onCreate(Bundle) 是您初始化活动的地方。最重要的是,在这里您通常会调用 setContentView(view) 并使用定义 UI 的布局资源,并使用 findViewById(int) 来检索该 UI 中需要以编程方式与之交互的小部件。

        见以下链接:-

        Why findViewById() is returning null if setcontentview() is not called?

        '但是“id”中的错误,如果没有设置为 contentview 的 java 类中的小部件是否可以获取 id? '

        你必须创建动态视图然后你不需要调用 setcontentview。

        how to set setContentView?

        Is there a way to set setContentView(int id) dynamically?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多