在所有活动中拥有相同视图的最佳实践?

时间:2017-06-09 05:19:08

标签: android

我有一个顶部的视图,几乎会在我的应用程序中的所有活动中显示。

这样做的最佳做法是什么?

我相信在每个活动上创建视图,它的布局不是最佳实践。

3 个答案:

答案 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>