2017-06-09 22 views
-4

我有一個頂部視圖,總是顯示在我應用程序的所有活動中。在所有活動中擁有相同視圖的最佳實踐?

這樣做的最佳做法是什麼?

我相信在每個活動上創建視圖,它的佈局不是最佳實踐。

+0

您可以創建一次,[](https://developer.android。 COM /培訓/改善,LAYO uts/reusing-layouts.html)所有活動中的佈局,或者您只是用碎片替換不同部分 – Redman

+0

我找到了解決方案。工作後會在這裏發佈。 – Rendy

回答

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