BaseActivity

    xiaoxiao2021-03-25  136

    在同一个项目当中,很多的页面都是类似的,可以把这些相同的内容提取出来做成一个父类,

    然后不同的页面去继承父类,只需要对不同的内容进行修改就可以了。

    以下是我的Baseactivity的类。

    首先来看一下BaseActivity的布局,如下图所示

    红色部分是自定义的TitleBar,如果不清楚,可以参考我的博客 :TitleBar

    蓝色部分是FrameLayout容器,用于填充各个页面不同的内容。

    XML布局文件如下:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/backgroundColor"> <date.hb.com.wdiget.TitleBar android:id="@+id/titlebar" android:layout_width="match_parent" android:layout_height="wrap_content"/> <FrameLayout android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent"> </FrameLayout> </LinearLayout>

    BaseActivity的源码如下:

    public abstract class BaseActivity extends AppCompatActivity { protected TitleBarI titlebar; private FrameLayout container; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); onInitView(savedInstanceState); onSetEvent(); onInitData(); } public void setContentViewWithActionBar(int layoutResID){ setContentView(R.layout.base_activity); titlebar = (TitleBarI) findViewById(R.id.titlebar); container = (FrameLayout) findViewById(R.id.container); LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(layoutResID,container,true); } public TitleBarI getTitlebar(){ return this.titlebar; } protected abstract void onInitView(Bundle args0); protected abstract void onSetEvent(); protected abstract void onInitData(); }

    BaseActivity是一个抽象类,包含三个抽象函数:

    onInitView(Bundle args0)初始化界面,onSetEvent()设置事件,onInitData()初始化数据。

    setContentViewWithActionBar(int layoutResID)函数就是将子页面填充进container当中。

    举例:

    TestActivity界面只包含两个Button,布局文件很简单,这里就不写了。

    让TestActivity继承BaseActivity,具体代码如下:

    public class TestActivity extends BaseActivity implements View.OnClickListener{ private Button button1; private Button button2; @Override protected void onInitView(Bundle args0) { this.setContentViewWithActionBar(R.layout.test_activity); //设置title this.titlebar.setLeftBack(); this.titlebar.setTitle("标题"); this.titlebar.setRightVisible(false); button1 = (Button) findViewById(R.id.button1); button2 = (Button) findViewById(R.id.button2); } @Override protected void onSetEvent() { button1.setOnClickListener(this); button2.setOnClickListener(this); } @Override protected void onInitData() { } @Override public void onClick(View v) { if(v==button1){ Toast.makeText(this,"button1",Toast.LENGTH_SHORT).show(); }else if(v==button2){ Toast.makeText(this,"button2",Toast.LENGTH_SHORT).show(); } } }

    这样TestActivity的界面就变成了如下图所示,同时可以在onSetEvent()函数里面给TitleBar加上响应事件。

    转载请注明原文地址: https://ju.6miu.com/read-12517.html

    最新回复(0)