안드로이드 스튜디오 1.4.1에서 기본적으로 새로운 Navigation Drawer 프로젝트를 생성했는데,이 프로젝트에는 네비게이션 헤더 이미지와 이름을위한 nav_header_main.xml 파일이 있습니다. 이 이미지와 이름은 기본 수업 활동에서 프로그래밍 방식으로 설정되어야합니다. 이렇게하는 방법을 많이 시도했지만 앱이 충돌합니다.
nav_header_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:id="@+id/headerView"
android:layout_height="@dimen/nav_header_height"
android:background="@drawable/side_nav_bar"
android:gravity="bottom"
android:orientation="vertical"
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">
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:text="Android Studio"
android:textAppearance="@style/TextAppearance.AppCompat.Body1" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="android.studio@android.com" />
</LinearLayout>
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>
MainActivity.Class
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
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.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout headerImageView= (LinearLayout) findViewById(R.id.headerView);
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(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) {
Toast.makeText(getApplicationContext(),"working",Toast.LENGTH_LONG).show();
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_camara) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} 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;
}
}
답변
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View hView = navigationView.getHeaderView(0);
TextView nav_user = (TextView)hView.findViewById(R.id.nav_name);
nav_user.setText(user);
이 도움을 바랍니다!
답변
버그 190226 에서 언급했듯이 버전 23.1.0부터 헤더 레이아웃보기를 가져 오는 경우 :
navigationView.findViewById(R.id.navigation_header_text)
더 이상 작동하지 않습니다.
해결 방법은 헤더 뷰를 프로그래밍 방식으로 확장하고 확장 된 헤더 뷰에서 ID로 뷰를 찾는 것입니다.
예를 들면 :
View headerView = navigationView.inflateHeaderView(R.layout.navigation_header);
headerView.findViewById(R.id.navigation_header_text);
이상적으로는 방법이 있어야 getHeaderView()
하지만 이미 제안되어 있으므로 디자인 지원 라이브러리의 기능 릴리스에서 릴리스 될 때까지보고 기다립니다.
답변
레이아웃을 확장하여 코드를 사용하여 xml 추가에 헤더를 추가하지 마십시오.
View hView = navigationView.inflateHeaderView(R.layout.nav_header_main);
ImageView imgvw = (ImageView)hView.findViewById(R.id.imageView);
TextView tv = (TextView)hView.findViewById(R.id.textview);
imgvw .setImageResource();
tv.settext("new text");
답변
Kotlin에서
val hView = nav_view.getHeaderView(0)
val textViewName = hView.findViewById(R.id.textViewName) as TextView
val textViewEmail = hView.findViewById(R.id.textViewEmail) as TextView
val imgvw = hView.findViewById(R.id.imageView) as ImageView
imgvw.setImageResource(R.drawable.ic_menu_gallery)
답변
먼저 다음과 같이 MainActivity (또는 호출 활동)의 탐색 창에 액세스해야합니다.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
그런 다음 레이아웃이 MainActivity에서 프로그래밍 방식으로 확장되므로 activity_main.xml에서 헤더 레이아웃을 제거해야합니다. 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:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
그런 다음 MainActivity에서 nav_header_main 레이아웃을 확장하고 해당 뷰 (이 경우 ImageView 및 TextView)에 액세스합니다.
//inflate header layout
View navView = navigationView.inflateHeaderView(R.layout.nav_header_main);
//reference to views
ImageView imgvw = (ImageView)navView.findViewById(R.id.imageView);
TextView tv = (TextView)navView.findViewById(R.id.textview);
//set views
imgvw.setImageResource(R.drawable.your_image);
tv.setText("new text");
navigationView.setNavigationItemSelectedListener(this);
여기에서 더 많은 것을 읽을 수 있습니다
답변
다음은 완벽하게 작동하는 코드입니다. activity_main.xml의 NavigationView 태그에 헤더를 추가하지 마십시오.
<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:menu="@menu/activity_main_drawer"
app:itemBackground="@drawable/active_drawer_color" />
아래 코드를 사용하여 프로그래밍 방식으로 헤더 추가
View navHeaderView = navigationView.inflateHeaderView(R.layout.nav_header_main);
headerUserName = (TextView) navHeaderView.findViewById(R.id.nav_header_username);
headerMobileNo = (TextView) navHeaderView.findViewById(R.id.nav_header_mobile);
headerMobileNo.setText("+918861899697");
headerUserName.setText("Anirudh R Huilgol");
답변
nav = ( NavigationView ) findViewById( R.id.navigation );
if( nav != null ){
LinearLayout mParent = ( LinearLayout ) nav.getHeaderView( 0 );
if( mParent != null ){
// Set your values to the image and text view by declaring and setting as you need to here.
SharedPreferences prefs = getSharedPreferences("user_data", MODE_PRIVATE);
String photoUrl = prefs.getString("photo_url", null);
String user_name = prefs.getString("name", "User");
if(photoUrl!=null) {
Log.e("Photo Url: ", photoUrl);
TextView userName = mParent.findViewById(R.id.user_name);
userName.setText(user_name);
ImageView user_imageView = mParent.findViewById(R.id.avatar);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.ic_user_24dp);
requestOptions.error(R.drawable.ic_user_24dp);
Glide.with(this).load(photoUrl)
.apply(requestOptions).thumbnail(0.5f).into(user_imageView);
}
}
}
도움이 되었기를 바랍니다.