0

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

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

大师活动

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);
    }
}

儿童活动

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。_ 如果是ChildActivityextends AppCompatActivity,则不会出现 NPE。

我该如何解决?

4

1 回答 1

1

How about

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

and then in ChildActivity

setContentView(R.layout.activity_child);
setupDrawer(findViewById(android.R.id.content));//use root view
于 2016-04-14T12:26:39.003 回答