Android - setOnClickListern in nav_header_menu - android

I would add event in nav_header_menu.
I added login and register section then when user click I would show the relative layout page:
https://ibb.co/wwmFzSk
I added fragment_layout_user.xml and ActivityLoginUser class with code:
public class ActivityLoginUser extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_login_user);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
}}
How can I implement this event in drawer menu?

You can follow below code to access the view of header.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerview = navigationView.getHeaderView(0);
TextView login= (TextView) headerview.findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
});

I solved it also with #SumitSingh suggestion. I paste here the correct way to solve that.
We need to add this code in the activity class where we added navigation view.
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View headerview = navigationView.getHeaderView(0);
TextView login= (TextView) headerview.findViewById(R.id.login);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Your code here
}
});
Replace // Your code here with:
Intent loginUserIntent = new Intent(getContext(), ActivityLoginUser.class);
/* Start the new activity */
startActivity(loginUserIntent);
If you get error for getContext() please replace it with MainActivity.this
It works for me.

Related

android.view.View.findViewById(int) on a null object reference (Android Lint)

I have a problem. I run Lint in android studio and it repaired some parts of my app, but after this app cant start. It writes:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cewe.martin.cewetracking/com.cewe.martin.cewetracking.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
and I can't find, where is the problem. I can't do Undo, because there are some changed files so i tried to remove parts, which are not typical for me, but it still won't start. Here is onCreate method of MainActivity:
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
if (savedInstanceState == null) {
Log.d("START","DO IFU");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new ScanFragment()).commit();
Log.d("START","ZA GETSUPP");
navigationView.setCheckedItem(R.id.nav_scan);
}
}
You can see Log.d. The first one "DO IFU" shows, the second one no, so I think, that it could be in ScanFragment(). Code here:
public class ScanFragment extends Fragment {
private final EditText rucneKod = (EditText) getView().findViewById(R.id.numberInput);
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_scan, container, false);
Button skenovaciTlacitko = view.findViewById(R.id.button2);
skenovaciTlacitko.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
zapnoutSkener();
}
});
Button rucne = view.findViewById(R.id.button3);
View.OnFocusChangeListener ofcListener = new MyFocusChangeListener();
rucneKod.setOnFocusChangeListener(ofcListener);
final InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
rucne.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (rucneKod.getText().length() != 0) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
odeslat(rucneKod.getText().toString());
} else {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
Snackbar snackbar = Snackbar.make(view, R.string.pozadovanKod, Snackbar.LENGTH_LONG);
View sbView = snackbar.getView();
TextView textView = sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.YELLOW);
snackbar.show();
}
}
});
return view;
}
Can somebody see the problematic code? Thanks
private final EditText rucneKod = (EditText)
getView().findViewById(R.id.numberInput);
is causing NPE. Put it inside OnCreateView and repace getView() with view
getView() return the view returned by onCreateView(LayoutInflater,
ViewGroup, Bundle))
Doing this : private final EditText rucneKod = (EditText) getView().findViewById(R.id.numberInput);
it calls getView before onCreateView function, it will be null wich is normal,
Try moving the instantiation inside onCreateView function
Hope this helps
I think the problem is here:
private final EditText rucneKod = (EditText) getView().findViewById(R.id.numberInput);
You should call findViewById inside onCreateView, right after inflating the fragment's layout.
getView() is null when the fragment is constructed, and the stored properties are initialized before onCreateView is called.

SeekBar on Navigation Drawer

I'm trying to use the seekbar in the navigation drawer. What's my mistake? In the application without the navigation drawer there is no problem. Thank you.
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
TextView textView;
SeekBar seekBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
seekBar = (SeekBar) findViewById(R.id.seekbar);
textView = (TextView) findViewById(R.id.txtView);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
textView.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SeekBar.setOnSeekBarChangeListener(android.widget.SeekBar$OnSeekBarChangeListener)' on a null object reference
I suppose your Seek bar is in Header View of Navigation Drawer in That Case You may :
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
profile_name = (TextView) header.findViewById(R.id.profile_name);
profile_email = (TextView) header.findViewById(R.id.profile_email);
profile_image = (ImageView) header.findViewById(R.id.imageView);
setNavigationHeader();
You need to get the view of Header first and then find your Seek bar in it
If your view is not in header then this won't work.
You need to create your own Custom Navigation Drawer

How to open the Sliding Navigation Drawer when ImageView is clicked?

I'm trying to implement the Navigation Drawer Activity on my Dashboard Activity. In my application, I have created a Theme where the 'Toolbar/ActionBar' is removed and just put an ImageView for my burger menu on a custom layout and include it on my dashboard layout. What I wanted is that when this ImageView is clicked the sliding drawer will display.
What I tried to do is add an Navigation Drawer Activity by com.project.projectname -> New -> activity -> 'Navigation Drawer Activity' and automatically it adds NavigationActivity class , activity_navigation.xml
app_bar_navigation.xml, etc.
But I was wondering how can I open the drawer?
In my Dashboard Activity I added this
public class DashboardActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
View side_tab = findViewById(R.id.side_tab);
expanded_menu = (ImageView) side_tab.findViewById(R.id.expanded_menu);
expanded_menu.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// open drawer here
}
});
Also, in NavigationActivity it uses ActionBarDrawerToggle, I must not use this because I don't apply an ActionBar. But what alternative can I use?
Here is my NavigationActivity
public class NavigationActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
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.navigation, 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();
Intent goToSreen;
if (id == R.id.nav_dashboard) {
goToSreen = new Intent(NavigationActivity.this, DashboardActivity.class);
startActivity(goToSreen);
} else if (id == R.id.nav_others) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Thank you for your kind help.
Update
So in my Dashboard Activity I added the following
NavigationActivity navigationActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dashboard);
View side_tab = findViewById(R.id.side_tab);
expanded_menu = (ImageView) side_tab.findViewById(R.id.expanded_menu);
expanded_menu.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
navigationActivity = new NavigationActivity() ;
navigationActivity.drawer.openDrawer(GravityCompat.START);
}
});
And in my Navigation Activity I add a global variable
public class NavigationActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
I have managed to call the drawer in my Dashboard Activity but the sliding menu still doesn't display when I clicked my burger menu. The app crashes and displays java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(int)' on a null object reference
Add this in your NavigationActivity
public class NavigationActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//Add this line
public static DrawerLayout drawer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_navigation);
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();
.......
And next change this
expanded_menu.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// open drawer here
NavigationActivity. drawer.openDrawer(GravityCompat.START);
}
});
Try this hope it will solve your problrm.
Add the following code in NavigationActivity:
DrawerLayout mDrawerLayout; // Declare globally
In onCreate() :
mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer);
expanded_menu = (ImageView) side_tab.findViewById(R.id.expanded_menu);
expanded_menu.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
// open drawer here
mDrawerLayout.openDrawer(Gravity.LEFT);
}
});
If the drawer is open, close it onBackPressed():
#Override
public void onBackPressed() {
if (mDrawerLayout.isDrawerOpen(Gravity.LEFT)) {
mDrawerLayout.closeDrawer(Gravity.LEFT);
return;
}
}
Hope this helps.
I extend my NavigationActivity to my DashboardActivity like below
public class DashboardActivity extends NavigationActivity {
side_tab = findViewById(R.id.side_tab);
expanded_menu = (ImageView) side_tab.findViewById(R.id.expanded_menu);
expanded_menu.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
side_tab.setVisibility(View.INVISIBLE);
drawer.openDrawer(GravityCompat.START);
}
});
and then follow the said answered by #Hassan Usman and #tahsinRupam
after that I added the DrawerLayout in my dashboard.xml

How to use nav drawer in multiple activities

I want to define a single nav drawer I can use throughout my application. I followed the instructions of the chosen answer here as my first approach: Same Navigation Drawer in different Activities
I made a few modifications, namely calling onCreateDrawer from inside an overridden onCreate. I updated my subsequent activity to extend DashboardActivity ("base activity" from the example). When I launch my second activity I get a null pointer exception complaining that the nav UI doesn't exist when onCreateDrawer tries to set the toggle listened on the drawer.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.setDrawerListener(android.support.v4.widget.DrawerLayout$DrawerListener)' on a null object reference
Here are the base (dashboard) and subsequent (log workout) activity - please ask if there is other code you want to see. The code for the UI of the drawer and associated activity are what came out of the box when creating a new Nav Drawer Activity in Android Studio.
DashboardActivity.java
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
onCreateDrawer();
Realm realm = Realm.getDefaultInstance();
RealmQuery<Exercise> query = realm.where(Exercise.class);
RealmResults<Exercise> result = query.findAll();
Log.d(TAG, "There are " + result.size() + " exercises ready for use.");
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent logWorkoutIntent = new Intent(getApplicationContext(), LogWorkoutActivity.class);
startActivity(logWorkoutIntent);
}
});
//TODO: Remove this sign out button
Button signOutButton = (Button) findViewById(R.id.button_sign_out);
signOutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FirebaseAuth.getInstance().signOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Signed out", Toast.LENGTH_LONG).show();
}
});
//TODO: Remove this data tester
updateUserName();
}
//#Override
protected void onCreateDrawer() {
Log.d(TAG, "onCreateDrawer called");
//super.onCreate(savedInstanceState);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, mDrawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
mDrawerLayout.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
...
-
LogWorkoutActivity.java
public class LogWorkoutActivity extends DashboardActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_log_workout);
setContentView(R.layout.activity_log_workout);
super.onCreateDrawer();
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();
}
});
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
I think you are missing a drawer with id drawer_layout in your activity_log_workout layout.
In order for this approach to work, you must have a DrawerLayout with id drawer_layout in all your activity layouts that should have the drawer.
I also noticed something peculiar with your code. In every activity that extends DashboardActivity you are first setting setContentView(R.id.activity_dashboard), then calling onCreateDrawer(), then you are changing the content view and creating the drawer again. I think this a very suboptimal approach.
I suggest you create a BaseDrawerActivity class to encapsulate the drawer creation and UI binding logic. Then you just extend it in the activities where you need a drawer. You can do it like this:
public abstract class BaseDrawerActivity extends AppCompatActivity {
// move all your drawer related fields here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
setContentView(getLayoutResId());
// the same method you have right now
onCreateDrawer();
}
/*
* Extending activities use this class to supply the
* id of their layout file. This way you can set the view
* only once and there is no need to create the drawer twice.
*/
#LayoutResId
public abstract int getLayoutResId();
}

Setup an imageview to open sidebar/menu android

Instead of using actionbar and setting up an icon, I could not use actionbar here. What I really want to do is to setup an imageview, which responds to user's click. When it is clicked, sidebar/menu will open or close, just like clicking on physical button at the button of android phone.
Is there any easy way to do so? (all the items in the sidebar are already done and work fine. I checked it by clicking on physical menu button on my phone)
Felt worthwhile to put the code for this example up on GitHub, as it was getting quite long:
Just set an OnClickListener to your ImageView, in the same way you would a Button.
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setOnClickListener(this);
//...
#Override
public void onClick(View v) {
if(!mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.openDrawer(GravityCompat.START);
} else {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
You may want to add android:clickable = "true" to the xml for your ImageView, and android:background="?android:attr/selectableItemBackground" to gain feedback when the item is clicked.
This assumes you've set up your DrawerLayout somewhat like the following:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout = null;
private ActionBarDrawerToggle mActionBarDrawerToggle = null;
private RecyclerView mRecyclerView = null;
private NavMenuAdapter adapter = null;
private ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, 0, 0);
mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);
mRecyclerView = (RecyclerView) findViewById(R.id.navigation_menu_recycler);
adapter = new NavMenuAdapter();
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
imageView = (ImageView) findViewById(R.id.image_view);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
mDrawerLayout.openDrawer(GravityCompat.START);
} else {
mDrawerLayout.closeDrawer(GravityCompat.START);
}
}
});
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mActionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mActionBarDrawerToggle.onConfigurationChanged(newConfig);
}
Edit:
If you would like more control, you can define various states for your ImageView with a state list drawable, and use it in android:background instead of the above suggestion. Create a new xml file in your drawable folder (i.e. custom_selector.xml) with the following template:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/image_pressed"
android:state_pressed="true" />
<item android:drawable="#drawable/image_focused"
android:state_focused="true" />
<item android:drawable="#drawable/image_normal" />
</selector>
And define relevant images for pressed, focused/hover and normal states. Apply it with:
android:background="#drawable/custom_selector"
Building on PPartisan's answer, and assuming your Activity is MainActivity:
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setOnClickListener(this);
//...
#Override
public void onClick(View v) {
MainActivity.this.openOptionsMenu();
}

Categories

Resources