getParent返回错误的ViewGroup

时间:2013-11-15 12:11:53

标签: android view android-linearlayout android-framelayout viewgroup

当执行下面的代码时,我可以在我的LogCat中验证getParent返回另一个ViewGroup然后是FrameLayout(它返回LinearLayout)。通常我希望getParent会返回framelayout ...

有谁知道为什么会这样?

的java:

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button button = (Button) findViewById(R.id.actionbar_btn);
        if (button.getParent() instanceof FrameLayout) {
            Log.v("TAG", "parent was framelayout");
        } else {
            Log.v("TAG", "parent was no framelayout");
        }

    }

的xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00FF00"
        android:orientation="horizontal" >

        <FrameLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <Button
                android:id="@+id/actionbar_home"
                android:layout_width="33dp"
                android:layout_height="32dp"
                android:background="@drawable/ic_launcher" 
                />


        </FrameLayout>

        .....

    </LinearLayout>

</RelativeLayout>

2 个答案:

答案 0 :(得分:2)

您不应该将R.id.actionbar_btn更改为R.id.actionbar_home吗?

答案 1 :(得分:0)

我认为你的错误ID是Button:

 <Button
                    android:id="@+id/actionbar_home"
                    android:layout_width="33dp"
                    android:layout_height="32dp"
                    android:background="@drawable/ic_launcher" 
                    />


final Button button = (Button) findViewById(R.id.actionbar_btn);

"R.id.actionbar_btn"android:id="@+id/actionbar_home" 应该相同