Android開(kāi)發(fā):基本框架搭建前置

toolbar的使用(突發(fā)奇想)

網(wǎng)上toolbar相關(guān)介紹已經(jīng)很多了,這里呢就記錄一下一點(diǎn)新的想法。每次新建一個(gè)頁(yè)面總要include一個(gè)toolbar進(jìn)去,其實(shí)已經(jīng)很方便了但寫(xiě)的次數(shù)多了還是想偷點(diǎn)懶,于是生出了一個(gè)在BaseActivity中手動(dòng)添加的方法。

大致代碼如下:


//Toolbar的布局文件

xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:app="http://schemas.android.com/apk/res-auto"

xmlns:tools="http://schemas.android.com/tools"

tools:ignore="UnusedAttribute"

android:id="@+id/toolbar"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:background="@color/colorPrimary"

android:fitsSystemWindows="true"

android:minHeight="?attr/actionBarSize"

android:popupTheme="@style/Widget.AppCompat.ActionBar"

app:theme="@style/ToolbarTheme"/>


public class BaseActivity extends AppCompatActivity implements ? ? ? ? ??

? ? Toolbar.OnMenuItemClickListener { ? ?

? ? private LinearLayout mContentLayout;

? ? private Toolbar mToolbar;

? ? //首先重寫(xiě)布局,改變層級(jí),并重寫(xiě)setContentView方法,將新建的布局放進(jìn)mContentLayout ? 中;

? ? private void initContentView() {

? ? ? ? ViewGroup content = (ViewGroup) findViewById(android.R.id.content);

? ? ? ? content.removeAllViews();

? ? ? ? mContentLayout = newLinearLayout(this);

? ? ? ? mContentLayout.setOrientation(LinearLayout.VERTICAL);

? ? ? ? content.addView(view);

? ? ? ? view.addView(mContentLayout); ?

? ? }

? ? @Override

? ? public void setContentView(int layoutResID) {

? ? ? ? LayoutInflater.from(this).inflate(layoutResID, mContentLayout, true);

? ? }

? ? //這是主要方法,需要在setContentView方法前調(diào)用。這里傳入之前做好的Toolbar布局id,如果有menu則傳入

? ? protected void setToolbar(int resId) {

? ? ? ? setToolbar(resId, DEFAULT);

? ? }

? ? protected void setToolbar(int resId, int menuId) {

? ? ? ? LayoutInflater.from(this).inflate(resId, mContentLayout, true);

? ? ? ? mToolbar = (Toolbar) findViewById(R.id.toolbar);

? ? ? ? if(menuId != DEFAULT) {

? ? ? ? ? ? mToolbar.inflateMenu(menuId);

? ? ? ? }

? ? ? ? setSupportActionBar(mToolbar); ?

? ? ? ? mToolbar.setOnMenuItemClickListener(this);

? ? }

? ? @Override

? ? public booleanonMenuItemClick(MenuItem item) {

? ? ? ? return false;

? ? }

}

主要就是BaseActivity中對(duì)布局的重寫(xiě),而對(duì)于所有繼承了BaseActivity的Activity則可以省去布局中toolbar的添加和少點(diǎn)代碼里。不過(guò)還有標(biāo)題設(shè)置,自定義布局設(shè)置等方法需要完善,我覺(jué)得這些就屬于個(gè)人定制范疇了,因此省去了這部分的代碼。PS:第一次用這個(gè)文本編輯器,文章結(jié)構(gòu)沒(méi)調(diào)好,只能將就看看了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容