如何扩展AppCompatActivity以集中代码,例如DrawerLayout?

时间:2016-04-14 11:48:26

标签: android drawerlayout appcompatactivity

我想扩展AppCompatActivity以集中代码,以便共享代码,例如DrawerLayout等等。

然而,我遇到NullPointerException。这是我的代码:

MasterActivity

public class MasterActivity extends AppCompatActivity {
    public static final String TAG = "MasterActivity";
    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    protected void setupDrawer() {
        // Drawer
        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open_drawer, R.string.close_drawer) {
            @Override
            public void onDrawerOpened(View drawerView) {

            }

            @Override
            public void onDrawerClosed(View drawerView) {

            }
        };
        mDrawerLayout.addDrawerListener(mDrawerToggle);
    }
}

ChildActivity

public class ChildActivity extends MasterActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_child);
        setupDrawer();
    }
}

activity_child.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".ChildActivity">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <!-- Main Content -->

    </LinearLayout>

    <LinearLayout android:id="@+id/llv_left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:orientation="vertical"
        android:background="#888" >

        <!-- Drawer Content -->

    </LinearLayout>
</android.support.v4.widget.DrawerLayout>

NPE出现在:

mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);

错误信息是:

  

尝试在空对象引用上调用虚方法'void android.support.v4.widget.DrawerLayout.setDrawerShadow(int,int)'

显然,变量mDrawerLayout为空,因为findViewById()无法从布局XML中找到它。 R.id.drawer_layout位于R.layout.activity_child。如果ChildActivity延伸AppCompatActivity,NPE就不会出现。

我该如何解决?

1 个答案:

答案 0 :(得分:1)

怎么样

 protected void setupDrawer(View v) {
   mDrawerLayout = (DrawerLayout)v.findViewById(R.id.drawer_layout);
   ...

然后在ChildActivity

setContentView(R.layout.activity_child);
setupDrawer(findViewById(android.R.id.content));//use root view