与其他活动共享导航抽屉(高级)

时间:2015-11-20 22:42:21

标签: android android-activity android-navigation-drawer

这是我的第一个问题。我发誓我研究并尝试了很多,但没有结果,我有点沮丧没有结果和错误。 :)

我在Android Studio创建了一个导航抽屉项目,现在我正在尝试与其他活动共享菜单(MainActivity)。

我的主要活动:

package br.com.pmarx.ihamster;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.design.widget.NavigationView.OnNavigationItemSelectedListener;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(menuItemListener);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
private OnNavigationItemSelectedListener menuItemListener = new OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.my_larder_general_activity) {
            Intent myLarderViewActivity = new Intent(getApplicationContext(), MyLarderGeneralActivity.class);
            startActivity(myLarderViewActivity);
        } else if (id == R.id.my_plan_activity) {
            Intent myPlanActivity = new Intent(getApplicationContext(), MyPlanActivity.class);
            startActivity(myPlanActivity);
        } else if (id == R.id.ins_item_larder) {
            Intent insItemLarderActivity = new Intent(getApplicationContext(), InsItemLarderActivity.class);
            startActivity(insItemLarderActivity);
        } else if (id == R.id.ins_item_plan) {
            Intent insItemPlanActivity = new Intent(getApplicationContext(), InsItemPlanActivity.class);
            startActivity(insItemPlanActivity);
        } else if (id == R.id.my_larder_kept_activity) {
            Intent myLarderKeptActivity = new Intent(getApplicationContext(), MyLarderKeptActivity.class);
            startActivity(myLarderKeptActivity);
        } else if (id == R.id.my_larder_use_activity) {
            Intent myLarderUseActivity = new Intent(getApplicationContext(), MyLarderUseActivity.class);
            startActivity(myLarderUseActivity);
        } else if (id == R.id.my_shopping_list_activity) {
            Intent myShoppingListActivity = new Intent(getApplicationContext(), MyShoppingListActivity.class);
            startActivity(myShoppingListActivity);
        //Populando a Database Daqui
        } else if (id == R.id.database_populate) {
            DatabaseDAO crud = new DatabaseDAO(getBaseContext());
            crud.popularDatabase();
        //Populando a Database Até Aqui
        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;

    }

};
}

我的新活动以扩展MainActivity(和菜单):

package br.com.pmarx.ihamster;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class MyShoppingListActivity extends MainActivity {

private ListView listItem;
private CreateDatabase database;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_plan);

    listItem = (ListView)findViewById(R.id.listView);
    listItem.setOnItemClickListener(listItemListener);

};

@Override
protected void onResume() {

    super.onResume();

    DatabaseDAO crud = new DatabaseDAO(getBaseContext());
    Cursor cursor = crud.loadShoppingList();

    String[] fieldNames = new String[] {database.PROD_NOME, "volume3"};
    int[] idViews = new int[] {R.id.tvProd, R.id.tvVolum};

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getBaseContext(), R.layout.sel_item_plan, cursor, fieldNames, idViews, 0);

    listItem = (ListView)findViewById(R.id.listView);
    listItem.setAdapter(adapter);

};

private OnItemClickListener listItemListener = new OnItemClickListener(){

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id){

        //Passando parametro para a outra tela
        Intent insertItemActivity = new Intent(getBaseContext(), InsItemLarderActivity.class);
        insertItemActivity.putExtra("PROD_ID", String.valueOf(id));
        startActivity(insertItemActivity);


    }

};

}

首先,我收到错误“此活动已经有窗口装饰提供的操作栏”。所以,我改变了这样的风格:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
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"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">

<include layout="@layout/app_bar_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:headerLayout="@layout/nav_header_main"
    app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

我的app_bar_main.xml

   
   <android.support.design.widget.CoordinatorLayout
    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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">
    <android.support.design.widget.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.AppBarOverlay">
        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_main" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>

我的my_plan

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#fdb46d"
android:weightSum="1">

<GridLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:rowCount="1"
    android:columnCount="4"
    android:layout_gravity="center_horizontal">

</GridLayout>

<include
    android:id="@+id/toolbar"
    layout="@layout/activity_main" />

<ListView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/listView"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:choiceMode="singleChoice"
    android:clickable="false"
    android:contextClickable="false" />

</LinearLayout>

但是,我开始得到错误“java.lang.NullPointerException:尝试在空对象引用上调用虚方法'boolean android.support.v4.widget.DrawerLayout.isDrawerOpen(int)'。

经过一些更改后,现在我收到错误“java.lang.NullPointerException:尝试在空对象引用上调用虚方法'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()'”

让我们一步一步来做。我真的很困惑。

先谢谢!

1 个答案:

答案 0 :(得分:0)

启动create or replace PROCEDURE procPrintOutput IS -- var declarations .... BEGIN DECLARE -- Get the list of Materialized views. CURSOR LIST_OF_MatViews IS select * from user_mviews where MVIEW_NAME = 'TEAM_AUD_MV_NR'; CURSOR CREATE_MatViews IS SELECT * FROM temp; BEGIN FOR Mat_View IN LIST_OF_MatViews LOOP BEGIN DBMS_OUTPUT.PUT_LINE('owner : ' || Mat_View.OWNER || ' - name : ' || Mat_View.MVIEW_NAME); -- save the create script of views to temp table. l_stmt := 'insert into temp SELECT SYS.DBMS_METADATA.get_ddl (''MATERIALIZED_VIEW'', ''' || Mat_View.MVIEW_NAME || ''') from dual'; EXECUTE IMMEDIATE (l_stmt); DBMS_OUTPUT.PUT_LINE('inserted ... '); -- drop the view. --EXECUTE IMMEDIATE (drop_mat_view_logs_stmt || Mat_View.MVIEW_NAME); --DBMS_OUTPUT.PUT_LINE('view log dropped ... '); END; END LOOP; -- recreate view using the create script generated in the previous step. FOR MV_CREATE_SCRIPT IN CREATE_MatViews LOOP BEGIN DBMS_OUTPUT.PUT_LINE('SCRIPT : ' || MV_CREATE_SCRIPT.matViewLogQuery); replace_stmt := 'select replace(''' || MV_CREATE_SCRIPT.matViewLogQuery || ''','';'','' '') from dual'; DBMS_OUTPUT.PUT_LINE('replace_stmt : ' || replace_stmt); EXECUTE IMMEDIATE (replace_stmt) INTO updated_stmt; DBMS_OUTPUT.PUT_LINE('Updated SCRIPT ?? ' || updated_stmt); --EXECUTE IMMEDIATE(updated_stmt); --DBMS_OUTPUT.PUT_LINE('view recreated ... '); END; END LOOP; END; END;

首先,调用onCreate方法并执行此行。

MyShoppingListActivity

调用父类的onCreate方法,它是MainActivity的onCreate方法。

所以super.onCreate(savedInstanceState); 在超级电话中执行。

然后执行setContentView(R.layout.activity_main);,将布局设置为setContentView(R.layout.my_plan)

因此,如果您的R.layout.my_plan xml文件中没有定义标识为R.id.toolbar的工具栏,则查找工具栏行将返回null。

R.layout.my_plan

解决方案是在没有布局的情况下创建BaseActivity,而无需调用setContentView(...)方法。将所有设置视图代码放入Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 块。

然后使用相同的Id在子类Activities的layout.xml文件中定义Widgets。