【问题标题】:Check if a view belongs to a linearlayout or not检查视图是否属于线性布局
【发布时间】:2012-07-31 16:36:19
【问题描述】:

我需要一点帮助。 如何检查视图是否属于线性布局?

我有一个 ImageButton,我需要一个条件来验证是否属于线性布局。

【问题讨论】:

    标签: android android-layout android-linearlayout android-view


    【解决方案1】:

    没试过,但应该可以。 假设您的 ImageButton 始终是您的 LinearLayout 的直接子级。

    View parent = (View)mContent.getParent();
    if (parent instanceof LinearLayout) {
        // do stuff
    }
    

    【讨论】:

    • 嗨,sblom,坦率地说。感谢您的回复。我的大脑崩溃了。 XDXD。我发布我的解决方案。感谢您的帮助
    • 您的解决方案会告诉您您是否在特定的 ViewGroup 中。该解决方案会告诉您您是否在任何 LinearLayout 中(这是问题:)
    【解决方案2】:

    您可以在 LinearLayout 上使用findViewById 方法。从 JavaDoc 中“查找具有给定 id 的子视图。如果此视图具有给定 id,则返回此视图。”

    LinearLayout layoutWithButton = (LinearLayout)findViewById(R.id.layout_with_button);
    ImageButton buttonInLayout = (ImageButton)layoutWithButton.findViewById(R.id.button_in_layout);
    
    if (buttonInLayout != null) {
      // Found
    }
    

    【讨论】:

      【解决方案3】:

      尝试通过 getParent() 方法搜索 UI 树

      【讨论】:

      • 嗨,comodoro。感谢您的回复。这很简单,但是我累了,我的大脑崩溃了 XDXD。 LinearLayout contentLayoutAddressPostal = (LinearLayout)findViewById(R.id.se_contentAdressPostal); ImageButton imbtRemoveAddress2 = (ImageButton)findViewById(R.id.sfsp2_ivHide); if(imbtRemoveAddress2.getParent()==contentLayoutAddressPostal){ imbtRemoveAddress2.performClick();
      【解决方案4】:

      解决方案.....

            LinearLayout contentLayoutAddressPostal = (LinearLayout)findViewById(R.id.se_contentAdressPostal);
      
           ImageButton imbtRemoveAddress2 = (ImageButton)findViewById(R.id.sfsp2_ivHide);
      
             if(imbtRemoveAddress2.getParent()==contentLayoutAddressPostal){
                imbtRemoveAddress2.performClick();
                                          ............................
      

      【讨论】:

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