我有一个顶部的视图,几乎会在我的应用程序中的所有活动中显示。
这样做的最佳做法是什么?
我相信在每个活动上创建视图,它的布局不是最佳实践。
答案 0 :(得分:1)
创建具有您的视图的基本活动,并将所有活动从其中扩展。
答案 1 :(得分:0)
使用包含标记:
<强> header.xml:强>
<LinearLayout>
<!-- Your code -->
</LinearLayout>
<强> activity.xml:强>
<LinearLayout>
<!-- including your header.xml here -->
<include layout="@layout/header" />
<!-- Your code for other views -->
</LinearLayout>
答案 2 :(得分:0)
所以这是我的解决方案:
<强> CustomActivity 强>
public abstract class CustomActivity extends AppCompatActivity {
private RelativeLayout relativeLayout;
private CustomView customView;
@Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(getLayoutResourceId());
relativeLayout = (RelativeLayout) findViewById(R.id.customViewLayout);
addCustomView();
}
protected abstract int getLayoutResourceId();
private void addCustomView() {
customView = new CustomView(getApplicationContext());
relativeLayout.addView(customView);
}
}
<强> MainActivity 强>
public class MainActivity extends CustomActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
//No need to have setContentView here
}
@Override
protected int getLayoutResourceId() {
return R.layout.activity_main;
}
}
<强> activity_main.xml中强>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
android:id="@+id/toolbar"
layout="@layout/toolbar_back" />
<LinearLayout
android:id="@+id/contentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/toolbar" />
<RelativeLayout
android:id="@+id/mainLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/toolbar" />
</RelativeLayout>