为什么Android导航抽屉会创建两个标题?

4
我按照教程将Facebook登录信息推送到带有导航的活动中,并将其放在顶部,如图所示。经过数天的修改代码,我终于让它正常工作了。但现在我无法让原始标题消失。我尝试更改代码的每个部分,但最终要么全部都没有,要么全部都有。虽然两个人总比一个人聪明,但这是例外。

另外,我想我不能发布图片,所以原始标题在顶部,应该在那里。我的Facebook个人资料图片和信息的新标题位于其下方。在下面开始导航抽屉菜单。

public class HomeActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {


JSONObject response, profile_pic_data, profile_pic_url;
TextView user_name, user_email, tokens;
ImageView user_picture;
NavigationView navigation_view;

String name;

Button button2;

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

    tokens = (TextView)findViewById(R.id.textView17);

    button2 = (Button)findViewById(R.id.button2);

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

    Intent intent = getIntent();
    String jsondata = intent.getStringExtra("jsondata");
    final String uid = intent.getStringExtra("Uid");


    setNavigationHeader();    // call setNavigationHeader Method.
    setUserProfile(jsondata, uid);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setVisibility(View.INVISIBLE);

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");

            Tokens token = new Tokens("100");

            ref.setValue(token);

            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(this);

    //Toast.makeText(getApplicationContext(), uid, Toast.LENGTH_LONG).show();

    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

           // Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
        updateText();

        }
    });


    Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
    Firebase tokRef = ref.child("tokens");


    //tokRef.setValue(mAuthData.getProvider());

    //Tokens token = new Tokens(100);

    //ref.setValue(token);

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            if (dataSnapshot.child("tokens").getValue() != null) {
                name = (String) dataSnapshot.child("tokens").getValue().toString();
                tokens.setText(name);
                //tokens.setText(dataSnapshot.getValue().toString());
                //  Toast.makeText(getApplicationContext(), name, Toast.LENGTH_LONG).show();
                // System.out.println(dataSnapshot.getValue());
                // String woot = dataSnapshot.getValue().toString();
                // tokens.setText(woot);
            }

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

            Toast.makeText(getApplicationContext(), "couldnt update token text", Toast.LENGTH_LONG).show();

        }
    });



}

public void updateText(){

    Firebase ref = new Firebase("https://luckycashslots.firebaseio.com/data/users/" + MainActivity.uID + "/");
    Firebase tokRef = ref.child("tokens");


    //tokRef.setValue(mAuthData.getProvider());

   // Tokens token = new Tokens(100);

  //  ref.setValue(token);

    ref.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

        for (DataSnapshot tokenSnapshot: dataSnapshot.getChildren()){

            Tokens token = tokenSnapshot.getValue(Tokens.class);
             System.out.println(token.toString());
            name = token.toString();
           // name = (String) dataSnapshot.child("tokens").getValue();
            tokens.setText(name);

        }

       // name = (String) dataSnapshot.child("tokens").getValue().toString();
       // tokens.setText(name);

        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

            Toast.makeText(getApplicationContext(), "couldnt update token text", Toast.LENGTH_LONG).show();

        }
    });


}

public void setNavigationHeader(){
    navigation_view = (NavigationView) findViewById(R.id.nav_view);
    navigation_view.removeHeaderView(null);
    View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
            navigation_view.addHeaderView(header);
    user_name = (TextView) header.findViewById(R.id.username);
    user_picture = (ImageView) header.findViewById(R.id.profile_pic);
    user_email = (TextView) header.findViewById(R.id.email);
}

public void setUserProfile(String jsondata, String uid){
    try
    {

        response = new JSONObject(jsondata);
        user_email.setText(response.get("email").toString());
       // user_email.setText(MainActivity.uEmail);

         user_name.setText(response.get("name").toString());
       // user_name.setText(MainActivity.uName);
        profile_pic_data = new JSONObject(response.get("picture").toString());
        profile_pic_url = new JSONObject(profile_pic_data.getString("data"));


        Picasso.with(this).load(profile_pic_url.getString("url")).into(user_picture);
    }
    catch
            (Exception e) {
        e.printStackTrace();
    }
}

@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.home, 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_slots) {
        // Handle the camera action1
        Intent intent2 = new Intent(this, SlotPageView.class);
        startActivity(intent2);

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

        Intent intent2 = new Intent(this, DailySpinActivity.class);
        startActivity(intent2);

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

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

        Intent intent2 = new Intent(this, PrizesActivity.class);
        startActivity(intent2);

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

        Intent intent2 = new Intent(this, WinnersActivity.class);
        startActivity(intent2);

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

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

        Intent intent2 = new Intent(this, AccountActivity.class);
        startActivity(intent2);

    }

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

activity_home.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_home" 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_home" app:menu="@menu/activity_home_drawer" />

应用程序工具栏主页xml

<?xml version="1.0" encoding="utf-8"?>
<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="learn2crack.learn2crackfb.HomeActivity">

<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_home" />

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

导航标题主页XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark" android:orientation="vertical"
android:gravity="bottom">

<de.hdodenhof.circleimageview.CircleImageView
    android:id="@+id/profile_pic"
    android:layout_width="80dp"
    android:layout_height="80dp"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:src="@android:drawable/sym_def_app_icon"
    />

<TextView android:id="@+id/username"
android:layout_width="match_parent" android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="Android Studio"
    android:textSize="14dp"
android:textAppearance="@style/TextAppearance.AppCompat.Body1"

android:textColor="#000000" />

<TextView
    android:id="@+id/email"
    android:layout_width="wrap_content" android:layout_height="wrap_content"
    android:text="android.studio@android.com" />

</LinearLayout>

展示activity_home的xml文件。 - Dhaval Parmar
添加了应用程序栏主页和导航头主页。抱歉一开始没有添加它们。 - JDKSoftDev
导航抽屉标头没有隐藏,您能解决这个问题吗? - AnmolTheDeveloper
3个回答

5
您需要将标题视图传递到:
navigation_view.removeHeaderView(navigation_view.getHeaderView(0);

并且不为空

navigation_view.removeHeaderView(null);

我应该用removeHeaderView具体删除什么,或者说,原始的header view叫什么?唯一让命令不出错的方法是在声明新的“header”之后调用删除“header”,这是多余的,因为我不想删除新的“header”。有什么建议吗? - JDKSoftDev

2
当您使用如下语句添加标题时 app:headerLayout="@layout/nav_header_home"
<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_home" app:menu="@menu/activity_home_drawer" />

那么就不需要再从代码中添加头文件了


setNavigationHeader()方法中删除以下行

navigation_view.removeHeaderView(null);
View header = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);
navigation_view.addHeaderView(header);

删除方法后,代码如下所示:

编辑 /

public void setNavigationHeader(){
    navigation_view = (NavigationView) findViewById(R.id.nav_view);

视图头部 = LayoutInflater.from(this).inflate(R.layout.nav_header_home, null);

意思是从当前上下文中加载一个名为nav_header_home的布局文件作为视图头部,并将其填充在指定的容器中。
    user_name = (TextView) navigation_view.findViewById(R.id.username);
    user_picture = (ImageView) navigation_view.findViewById(R.id.profile_pic);
    user_email = (TextView) navigation_view. findViewById(R.id.email);
}

不起作用。首先,"View header = LayoutInflator...等"这一行必须保留,否则它不知道接下来的header.findviewbyid中的"header"是什么。但是当我移除addHeaderView时,它只显示原始的导航头部,而不是由我的Facebook信息填充的那个。但非常感谢您付出努力来解决这个问题。 - JDKSoftDev
等等,你的答案基本正确。我已经让它工作了!在你的最终代码中,View header line必须保留,并且其余部分调用navigation_view.findviewbyid,而不是header.findviewbyid。但是非常棒的工作,谢谢! - JDKSoftDev

0

试试这个,它是可行的并且经过测试。

@Override
protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
                    navigationView.setNavigationItemSelectedListener(this);
                    navigationView.removeHeaderView(navigationView.getHeaderView(0));
                    View headerLayout = navigationView.inflateHeaderView(R.layout.nav_header_main);
                    ImageView user_dp = headerLayout.findViewById(R.id.user_dp);
                    TextView user_fullname = headerLayout.findViewById(R.id.user_fullname);
                    TextView user_email = headerLayout.findViewById(R.id.user_email);

                    user_dp.setBackgroundResource(R.drawable.user);
                    user_fullname.setText(fullName);
                    user_email.setText(uemail);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接