当前位置: 首页 > 知识库问答 >
问题:

实现导航抽屉时出错

司马钱明
2023-03-14
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentManager;
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.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener, AdapterView.OnItemSelectedListener, AdapterView.OnItemClickListener {


    private Toolbar toolbar;
    private DrawerLayout drawer;
    public String emailRegistration;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_business);

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


        //toolbar.setTitle("toolbar");
        setSupportActionBar(toolbar);



        //Set adapter to AutoCompleteTextView

      //  FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

//        if (!emailRegistration.matches("[a-zA-Z0-9._-]+@[a-z]+.[a-z]+")) {
//
//            email.setError("Invalid Email Address");
//
//        }

//        fab.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Snackbar.make(v, "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.addDrawerListener(toggle);
        toggle.syncState();

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

    @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")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
        setTitle("Home");
           Intent i = new Intent(MainActivity.this, HomeFragment.class);
            startActivity(i);
        } else if (id == R.id.nav_gallery) {
            setTitle("Edit Profile");
            EditFragment editFragment = new EditFragment();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment,editFragment).commit();

        } else if (id == R.id.nav_slideshow) {
            setTitle("Business");
            BusinessFragment businessFragment = new BusinessFragment();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment,businessFragment).commit();

        } else if (id == R.id.nav_manage) {
            setTitle("Message");
            MessageFragment messageFragment = new MessageFragment();
            FragmentManager fragmentManager = getSupportFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.fragment,messageFragment).commit();

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

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        // TODO Auto-generated method stub
        //Log.d("AutocompleteContacts", "onItemSelected() position " + position);

    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        InputMethodManager imm = (InputMethodManager) getSystemService(
                INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        // TODO Auto-generated method stub

        // Show Alert
        Toast.makeText(getBaseContext(), "Position:"+i+" Country:"+adapterView.getItemAtPosition(i),
                Toast.LENGTH_LONG).show();

        Log.d("AutocompleteContacts", "Position:"+i+" Country:"+adapterView.getItemAtPosition(i));

    }
}
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;



public class LoginActivity extends AppCompatActivity {
    public EditText email, password;
    public TextView textView;
    public Button login;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);

        email = (EditText) findViewById(R.id.email);
//        if( email.getText().toString().length() == 0 )
//            email.setError("Email is required!" );
        password = (EditText) findViewById(R.id.text_input_password_toggle);
//        if( password.getText().toString().length() == 0 )
//            password.setError("Password is required!" );
        textView = (TextView) findViewById(R.id.text2);
        login = (Button) findViewById(R.id.login);

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(LoginActivity.this,signupactivity.class);
                startActivity(i);
            }
        });
    }



    }
<?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>
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.addDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;


public class signupactivity extends AppCompatActivity {
    public EditText firstname, lastname, email;
    private AutoCompleteTextView actv;
    public Button signup;
    String[] languages={"Indore","Ujjain","Bhopal","Delhi","Bangalore","Chennai"};
    List<CharSequence> list = new ArrayList<CharSequence>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_main);
        for (int i=0;i<20;i++){
            list.add("test " + i);  // Add the item in the list
        }
        firstname = (EditText)findViewById(R.id.firstname);
        lastname = (EditText)findViewById(R.id.lastname);
        actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
        email = (EditText) findViewById(R.id.email);
        signup = (Button)findViewById(R.id.signup);
        ArrayAdapter adapter = new
                ArrayAdapter(this,android.R.layout.simple_list_item_1,languages);
        actv.setAdapter(adapter);
        actv.setThreshold(1);

        signup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(signupactivity.this, LoginActivity.class);
                startActivity(i);
            }
        });
    }

}

当我单击home,edit profile时,我想要一个空白片段,但它显示无处不在的注册活动,因为我的content_main framelayout id是fragment,它在mainactivity中的调用也是my signup页面(fragmentmanager.begintransaction().replace(r.id.fragment,editFragment).commit();)那么如何解决这个问题呢

共有1个答案

慕容宏邈
2023-03-14

在您使用的MainActivity.java中

setContentView(R.layout.fragment_business);

但是您的抽屉在activity_main.xml中

因此,您的抽屉是一个null,您不能向null对象添加侦听器。

setContentView(R.layout.activity_main);
 类似资料:
  • 有人能告诉我如何创建活动到这个主要活动,导航抽屉将看到在所有他们?我需要使用这个特定的MainActivity代码。我不需要使用碎片,只要3个简单的活动将添加到这个抽屉。 NavDrawer布局:

  • 我尝试在我的应用程序中实现导航抽屉(材料设计)。我的活动包含带有片段的FrameLayout。当用户在导航抽屉FrameLayout中选择项目时,重新加载新片段: 当我点击项目时,一切正常。导航抽屉关闭不顺利,但冻结(抽搐,抽搐),因为片段在后台重新加载。 如何顺利关闭导航抽屉?

  • 我试图遵循谷歌最新的良好实践,用导航组件实现单个活动应用程序。 然而,在阅读了整个导航留档后,我仍然认为有很多情况下,他们没有解决。 例如,我应该如何实现以下情况: 应用程序在闪屏中启动。然后在加载后进入新闻片段。 注意:闪屏应该从后台弹出,因为它不应该再出现了。 然而,部分中的一些片段可以导航到一个新区域,该区域应该有一个后退按钮(而不是抽屉)。

  • 我在将与和组合时遇到布局问题。 问题是,NavigationDrawer及其内容隐藏在工具栏后面。我已经做了很多研究,尝试了很多重组,但没有一个“解决方案”能解决我的问题。 在这个Webm小视频中可以找到一个演示:https://www.dropbox.com/s/i5zfc2x2ts2fws7/navigation_drawer_stackoverflow32523188.webm?dl=0 基

  • 有人知道如何实现一个滑动菜单像一些顶级应用程序今天吗? 其他堆栈溢出问题还没有关于如何做到这一点的答案,所以我正在尝试收集尽可能多的信息来帮助其他人。我在下面提到的所有应用程序都很好地实现了幻灯片菜单。 只有点击左上角的G+标识,才能从第一屏进入第二屏。注意,整个屏幕从它的位置移动,并且get被推到屏幕的右侧(包括操作栏)。要回到第一个屏幕,您可以将右侧滑回焦点,也可以再次单击G+图标。 您可以使

  • 我有一个程序,我想实现一个滑动菜单。 首先,我尝试了导航抽屉导航抽屉,这是我想要的,因为: 1)它不推屏幕,它覆盖它2)当我点击按钮上左它打开菜单3)当我尝试点击屏幕上的另一个 我不想有一个按钮向上左边,我希望用户点击一个按钮从屏幕和每次不同的滑动菜单出现。 我也尝试了jfeinstein10滑动菜单,但它不覆盖屏幕,它只是推开它,他们告诉我,这是不可能改变的。但另一方面,它是容易的,在某些方面更