如何为包含的布局设置java文件?

时间:2016-07-10 22:26:00

标签: java android xml

我在另一个中包含了这样的布局:

<include
    layout="@layout/_home"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

我想用onCreate方法创建一个java文件,当布局包含在任何地方时会触发。

我是android新手所以我可能会尝试做错事。

1 个答案:

答案 0 :(得分:1)

这有点困难,但是,就像@ emanuel-moecklin提到的那样,你可以使用自定义视图包装_home.xml布局,然后你可以在onAttachedWindow中添加一些代码, onMeasureonLayoutonDraw方法,如果您想了解有关自定义查看生命周期的更多信息,请查看this image

这将是您的 CustomView.java

public class CustomView extends View {

    private static final String TAG = "CustomViewTAG_";

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        Log.d(TAG, "This will get called everytime your CustomView gets attached");
    }
}

类似这样的 _home.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.example.CustomView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </com.example.CustomView>

    <!-- Your normal views -->

</FrameLayout>
相关问题