I tried to create some button on my home activity, but I do not know what is the problem with the button that I created. It does not appear in my home activity.
I am totally new to Android Studio, so I donĀ“t know how to write my code that it will work the way I want it. Can you help me please...
This is the XML code (design)
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/sos"
android:layout_centerHorizontal="true"
android:layout_marginStart="50dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:textStyle="bold"
android:backgroundTint="#df2c14"
android:textColor="#color/teal_200"
android:textSize="18dp"
android:text="Emergency"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/danger"
android:layout_centerHorizontal="true"
android:layout_marginStart="50dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:textStyle="bold"
android:backgroundTint="#df2c14"
android:textColor="#color/teal_200"
android:textSize="18dp"
android:text="Emergency danger"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/accident"
android:layout_centerHorizontal="true"
android:layout_marginStart="50dp"
android:layout_marginTop="30dp"
android:layout_marginEnd="30dp"
android:layout_marginBottom="30dp"
android:textStyle="bold"
android:backgroundTint="#df2c14"
android:textColor="#color/teal_200"
android:textSize="18dp"
android:text="Emergency accident"
/>
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
app:title="SOS"
app:titleTextColor="#color/material_dynamic_neutral_variant20"
app:titleMarginStart="150dp"
app:titleMarginBottom="600dp"
android:background="#color/material_dynamic_neutral_variant20"
/>
<com.google.android.material.navigation.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/nav_view"
app:headerLayout="#layout/header"
app:menu="#menu/navigation_menu"
android:layout_gravity="start"
/>
And this is Home code :
public class Home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer_Layout;
NavigationView navigationView;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
drawer_Layout = findViewById(R.id.drawerLayout);
navigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
navigationView.bringToFront();
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer_Layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer
_close);
drawer_Layout.addDrawerListener(toggle);
toggle.syncState();
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.menuHome:
break;
case R.id.menuPhone:
Intent intent = new Intent(Home.this, phone.class);
startActivity(intent);
break;
case R.id.menuMsos:
Intent intent1 = new Intent(Home.this, Msos.class);
startActivity(intent1);
break;
}
return true;
}
}
Related
I want to add ScrollView to my navigation drawer, I first tried to but the linear layout as a child under Scrollview, but when I opened my fragment, the navigation drawer shows under my fragment. I want to have my fragments untouched, whereas the navigation drawer does now show behind the fragments, and the navigation drawer has scrollview.
drawer code:
public class drawer_home extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
private DrawerLayout drawer;
Toolbar toolbar;
TextView mStartDate, mEndDate, mPlan, mDays;
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_drawer_home);
toolbar = findViewById(R.id.tb);
mStartDate = findViewById(R.id.startDateTV);
mEndDate = findViewById(R.id.endDateTV);
mPlan = findViewById(R.id.planTV);
mDays = findViewById(R.id.daysTV);
setSupportActionBar(toolbar);
/*TextView textView = (TextView)toolbar.findViewById(R.id.toolbartv);
textView.setText("No Excusas");
getSupportActionBar().setDisplayShowTitleEnabled(false);*/
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) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new androidx.fragment.app.Fragment()).commit();
navigationView.setCheckedItem(R.id.nav_homeMain);
}
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference("Users");
Query query = databaseReference.orderByChild("email").equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//checkc until requiered data get
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String startdate = "Fecha de Inicio = " + ds.child("Start Date").getValue();
String enddate = "Fecha de Salida = " + ds.child("End Date").getValue();
String plan = "Plan = " + ds.child("Plan").getValue();
String days = "Tu plan acaba en " + ds.child("Days Left").getValue() +" dias ";
mStartDate.setText(startdate);
mEndDate.setText(enddate);
mPlan.setText(plan);
mDays.setText(days);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_homeMain:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new androidx.fragment.app.Fragment()).commit();
break;
case R.id.nav_qr:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new QRcodeFragment()).commit();
break;
case R.id.nav_profile:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new UserProfile()).commit();
break;
case R.id.nav_order:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new OrdersActivity()).commit();
break;
case R.id.nav_nutrition:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new NutritionActivity()).commit();
break;
case R.id.nav_chat:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new ContactActivity()).commit();
break;
case R.id.nav_coach:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new CoachesActivity()).commit();
break;
case R.id.nav_information:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new AboutUsActivity()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
xml:
<androidx.drawerlayout.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"
android:background="#drawable/homebcgself"
tools:context=".drawer_home"
tools:openDrawer="start">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/tb"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:popupTheme="#style/ThemeOverlay.AppCompat.Light"
android:background="#drawable/toolbar_bg"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar">
<TextView
android:id="#+id/toolbartv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="cursive"
android:layout_gravity="center"
android:ellipsize="end"
android:gravity="center"
android:maxLines="1"
android:text="No Excusas"
android:textAlignment="center"
android:textAllCaps="true"
android:textColor="#ffffff"
android:textSize="40sp"
android:textStyle="bold" />
</androidx.appcompat.widget.Toolbar>
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/startDateTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="200dp"
android:textColor="#color/colorWhite"
android:textSize="30sp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorWhite" />
<TextView
android:id="#+id/endDateTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textStyle="bold"
android:layout_marginStart="5dp"
android:textColor="#color/colorWhite"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorWhite" />
<TextView
android:id="#+id/planTV"
android:layout_width="match_parent"
android:textSize="30sp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginStart="5dp"
android:textColor="#color/colorWhite"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorWhite" />
<TextView
android:id="#+id/daysTV"
android:layout_width="match_parent"
android:textSize="30sp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginStart="5dp"
android:textColor="#color/colorWhite"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorWhite" />
</LinearLayout>
<com.google.android.material.navigation.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" />
</androidx.drawerlayout.widget.DrawerLayout>
example of scrolling I want for the main content:
when the main content is scrollable, it shows under the first fragment
I think you have to set
<com.google.android.material.navigation.NavigationView
...
android:fitsSystemWindows="true"
android:isScrollContainer="true"
... />
Had a lot of help and figured it out.
Add scrollview to separate fragment and incorporate in the onCreate.
'''
ScrollView
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">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/startDateTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="5dp"
android:layout_marginTop="200dp"
android:textColor="#color/colorWhite"
android:textSize="30sp"
android:textStyle="bold" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorWhite" />
<TextView
android:id="#+id/endDateTV"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textStyle="bold"
android:layout_marginStart="5dp"
android:textColor="#color/colorWhite"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorWhite" />
<TextView
android:id="#+id/planTV"
android:layout_width="match_parent"
android:textSize="30sp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginStart="5dp"
android:textColor="#color/colorWhite"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorWhite" />
<TextView
android:id="#+id/daysTV"
android:layout_width="match_parent"
android:textSize="30sp"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginStart="5dp"
android:textColor="#color/colorWhite"/>
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/colorWhite" />
</LinearLayout>
I know this issue has been put out there 100 times, but nothing I've seen solves this. I have a button in a layout called fragment_main which is shown to another layout: activity_main. That button opens a fragment called AddEditFragment, which allows users to add info to a form that then spits it into a recyclerview(fragment_main) that is shown in MainActivity.
I have both layouts due to having a navigation drawer in a linearlayout in activity_main and the recyclerview and button in fragment_main constraintlayout. However I have onDelete/Edit/Save methods already up and going in MainActivity, so it only makes sense to me to put the button onClickListener there as well. Except since the button isn't in the main layout, activity_main, I get a fatal null object exception.
Even though fragment_main is shown in activity_main is there a way around this so the OnClick method can be put into MainActivity for a button in a linked layout?
MainActivity.java
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.OnVehicleClickListener,
FragmentAddEdit.OnSaveClicked,
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();
// Launcher view
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
navigationView.setCheckedItem(R.id.nav_garage);
}
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});
}
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.nav_garage:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentMainActivity()).commit();
break;
case R.id.nav_history:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentHistory()).commit();
break;
case R.id.nav_upcoming:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentUpcoming()).commit();
break;
case R.id.nav_about:
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container,
new FragmentAbout()).commit();
break;
}
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onSaveClicked() {
FragmentManager fragmentManager = getSupportFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
if (AddEditFragment != null) {
getSupportFragmentManager().beginTransaction()
.remove(AddEditFragment)
.commit();
}
}
public void onEditClick(#NonNull Vehicle vehicle) {
AddEditRequest(vehicle);
}
#Override
public void onDeleteClick(#NonNull Vehicle vehicle) {
}
private void AddEditRequest(Vehicle vehicle) {
Intent detailIntent = new Intent(this, FragmentAddEdit.class);
if (vehicle != null) {
detailIntent.putExtra(Vehicle.class.getSimpleName(), vehicle);
startActivity(detailIntent);
}
}
#Override
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
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:context=".com.carupkeep.MainActivity"
tools:openDrawer="start">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:elevation="4dp"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:headerLayout="#layout/nav_header"
app:menu="#menu/drawer_menu" />
</android.support.v4.widget.DrawerLayout>
fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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/content_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".com.carupkeep.FragmentMainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:id="#+id/no_vehicles"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="#string/no_vehicle_message"
android:textSize="22sp"
android:textStyle="normal|bold"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1"/>
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
<android.support.v7.widget.RecyclerView
android:id="#+id/vehicle_list"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="#+id/no_vehicles"
app:layout_constraintVertical_bias="0.0" />
</android.support.constraint.ConstraintLayout>
UPDATE
I got close but still feel so far. I've given up on trying to keep it in MainActivity and put it in FragmentMainAcitivity as suggested. Except now I have 2 can't resolve errors. The first being on view in view.findViewById button initialization AND on fragment_container in the callback method. Any thoughts on how to resolve this?
public class FragmentMainActivity extends Fragment {
Button button_add = view.findViewById(R.id.button_add);
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager fragmentManager = getFragmentManager();
Fragment AddEditFragment = fragmentManager.findFragmentById(R.id.fragment_container);
getFragmentManager().beginTransaction().replace(fragment_container, AddEditFragment).commit();
}
});
}
}
easier way to do it is to put
onClick="AddEditRequestView"
in your fragment_main.xml
so it will be
<Button
android:id="#+id/button_add"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:drawableLeft="#drawable/ic_add"
android:drawablePadding="10dp"
android:drawableTint="#color/colorAdd"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:text="#string/addVehicle"
android:onClick="AddEditRequestView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/vehicle_list" />
and in your MainActivity.java
add this method
public void AddEditRequestView(View viewc){
AddEditRequest(null);
}
and delete these code from your activity
Button button_add = findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AddEditRequest(null);
}
});
I'm developing an application (as my first one) and In this app I've declared my navigationView like this:
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_drawer"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:menu="#menu/drawer_menu"
app:headerLayout="#layout/drawer_header">
In my mainactivity.java I have:
public class MainActivity extends AppCompatActivity implements
NavigationView.OnNavigationItemSelectedListener{
...
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Log.d("Navigation","Item selected : "+ item.getItemId());
int id = item.getItemId();
switch (id){
case R.id.about:
Toast.makeText(getApplicationContext(),"About Us
elected",Toast.LENGTH_SHORT).show();
break;
case R.id.help:
Toast.makeText(getApplicationContext(),
"Help",Toast.LENGTH_SHORT).show();
break;
case R.id.setting:
Toast.makeText(getApplicationContext(),
"Settings",Toast.LENGTH_SHORT).show();
break;
case R.id.EditProfile:{
Intent intent= new Intent(this , EditProfile.class);
startActivity(intent);
}
default:
break;
}
DrawerLayout drawerLayout= (DrawerLayout)
findViewById(R.id.drawer_layout);
drawerLayout.closeDrawer(GravityCompat.START);
return false;
}
And according to this I've extended ActionBarDrawerToggle and in it's onDrawerOpened function I've don
drawerView.bringToFront();
drawerView.getParent().requestLayout();
But still when I click on navigation view Items onNavigationItemSelected function doesn't fire.
Is it because of header view I have added??
This method worked before I add header view to navigationView( I didn't test it just before adding header to navigationView.
And also I think it's useful to note that I have some buttons and TextViews in navigationView header.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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:orientation="vertical"
android:id="#+id/drawer_header"
android:background="#drawable/drawer_bg"
android:layout_width="match_parent"
android:padding="4dp"
android:layout_height="200dp">
<RelativeLayout
android:gravity="center_vertical"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_marginTop="50dp"
android:layout_gravity="center"
android:layout_height="wrap_content">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="80dp"
android:layout_height="80dp"
android:src="#drawable/avatar"
android:id="#+id/AvatarImageView"
android:layout_centerHorizontal="true" />
<Button
android:text="Signup"
android:layout_width="55dp"
android:layout_height="55dp"
android:layout_alignParentRight="true"
android:id="#+id/header_signup"
android:textSize="12sp"
android:background="#drawable/signup_button"
android:textStyle="normal|bold" />
</RelativeLayout>
<TextView
android:textColor="#color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:id="#+id/header_username"
android:textAlignment="center" />
<TextView
android:text="Logout"
android:textColor="#color/colorPrimaryDark"
android:layout_width="match_parent"
android:layout_centerHorizontal="true"
android:textAlignment="center"
android:layout_height="wrap_content"
android:id="#+id/header_logout"
/>
</LinearLayout>
You should add following line of code in onCreate for click listener for menu item,
NavigationView navigationView = (NavigationView) findViewById(R.id. navigation_drawer);
navigationView.setNavigationItemSelectedListener(this);
You can set click listener to the header of the NavigationView like this:
View headerLayout = navigationView.getHeaderView(0);
headerLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent= new Intent(this , EditProfile.class);
startActivity(intent);
});
and for the elements inside the header
CircleImageView userPicture = (CircleImageView) headerLayout.findViewById(R.id.AvatarImageView);
Edit
navigationView.setNavigationItemSelectedListener(this);
This is the solution:
path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/WhatsApp/Media/.Statuses/";
File f= new File(path);
When I change the layout of a fragment within an activity, the menu options in the action bar seem to stop working. The buttons (Search icon and NavDrawer icon) become unresponsive.
This is the layout file of the fragment with the working menu options:
activity_login.xml (working)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginFragment"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Login."
android:id="#+id/login_title_text"
android:layout_alignParentTop="true"
android:textSize="40sp"
android:layout_marginTop="100dp"
android:fontFamily="sans-serif-light"
android:textColor="#color/colorAlt"
android:layout_centerHorizontal="true" />
<!-- E-mail section -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="E-mail address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:ems="10"
android:id="#+id/login_emailField"
android:layout_above="#+id/login_passwordField" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/register_email_icon"
android:layout_alignBottom="#id/login_emailField"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"/>
<!-- Password section -->
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/register_password_icon"
android:layout_alignBottom="#id/login_passwordField"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:layout_marginTop="10dp"
android:hint="Password"
android:id="#+id/login_passwordField"
android:layout_centerVertical="true"
android:layout_marginLeft="50dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="25dp" />
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_login_button"
android:layout_gravity="center_vertical"
android:layout_below="#+id/login_passwordField"
android:layout_marginBottom="29dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
card_view:cardBackgroundColor="#E91E63"
card_view:cardCornerRadius="2dp"
card_view:cardElevation="6dp">
<TextView
android:id="#+id/material_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="13dp"
android:paddingBottom="13dp"
android:layout_gravity="center_horizontal"
android:textColor="#FFF"
android:textSize="19sp"
android:fontFamily="sans-serif-medium"
android:text="Login" />
</android.support.v7.widget.CardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Forgotten your username or password?"
android:layout_below="#id/login_login_button"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/login_footer_text"
android:layout_marginTop="40dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tap here"
android:textColor="#000000"
android:layout_below="#id/login_footer_text"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/loginForgottenTapText"
android:layout_marginTop="20dp"/>
</RelativeLayout>
</LinearLayout>
This is the layout file that seems to break the buttons:
activity_login.xml (non-working)
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".LoginFragment"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Login."
android:id="#+id/login_title_text"
android:layout_alignParentTop="true"
android:textSize="40sp"
android:layout_marginTop="100dp"
android:fontFamily="sans-serif-light"
android:textColor="#color/colorAlt"
android:layout_centerHorizontal="true" />
<!-- E-mail section -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:hint="E-mail address"
android:layout_marginLeft="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="20dp"
android:ems="10"
android:id="#+id/login_emailField"
android:layout_below="#+id/login_title_text" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/register_email_icon"
android:layout_alignBottom="#id/login_emailField"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"/>
<!-- Password section -->
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:layout_marginTop="10dp"
android:hint="Password"
android:layout_below="#id/login_emailField"
android:id="#+id/login_passwordField"
android:layout_marginLeft="50dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="25dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/register_password_icon"
android:layout_alignBottom="#id/login_passwordField"
android:layout_marginLeft="15dp"
android:layout_marginBottom="10dp"/>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/login_login_button"
android:layout_gravity="center_vertical"
android:layout_below="#+id/login_passwordField"
android:layout_marginBottom="29dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
card_view:cardBackgroundColor="#E91E63"
card_view:cardCornerRadius="2dp"
card_view:cardElevation="6dp">
<TextView
android:id="#+id/material_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="13dp"
android:paddingBottom="13dp"
android:layout_gravity="center_horizontal"
android:textColor="#FFF"
android:textSize="19sp"
android:fontFamily="sans-serif-medium"
android:text="Login" />
</android.support.v7.widget.CardView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Forgotten your username or password?"
android:layout_below="#id/login_login_button"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/login_footer_text"
android:layout_marginTop="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Tap here"
android:textColor="#000000"
android:layout_below="#id/login_footer_text"
android:gravity="center"
android:layout_centerHorizontal="true"
android:id="#+id/loginForgottenTapText"
android:layout_marginTop="10dp"/>
</RelativeLayout>
</ScrollView>
MainActivity.java
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, LoginFragment.OnLoginCallback {
MenuItem register;
MenuItem login;
MenuItem logout;
MenuItem completeListing;
MenuItem expiredListing;
MenuItem activeListing;
NavigationView navigationView;
UserCredentialHandler userStatus;
protected static final String KEY_USER_STATUS = "USER_STATUS";
protected static final String USER_PREFS = "userNamePrefs";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userStatus = new UserCredentialHandler();
final HomeFragment homeFragment = new HomeFragment();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
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();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), CreateListingActivity.class);
startActivity(i);
}
});
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
getMenuItems(navigationView);
if(userStatus.checkIfUserIsLoggedIn(getApplicationContext())){
userStatus.setNavHeaderOnLogin(getApplicationContext(), navigationView);
updateNavDrawer("login", register, login, logout, expiredListing, completeListing, activeListing);
} else {
userStatus.setNavHeaderOnLogout(navigationView);
updateNavDrawer("logout", register, login, logout, expiredListing, completeListing, activeListing);
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.main_container,homeFragment);
fragmentTransaction.commit();
}
#Override
public void onLoginSuccess() {
HomeFragment homeFragment = new HomeFragment();
userStatus.setNavHeaderOnLogin(getApplicationContext(), navigationView);
updateNavDrawer("login",register,login,logout, expiredListing, completeListing, activeListing);
register.setVisible(false);
login.setVisible(false);
logout.setVisible(true);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
fragmentTransaction.replace(R.id.main_container,homeFragment);
fragmentTransaction.commit();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
getSupportFragmentManager().popBackStack();
}
}
#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_activity_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;
} else if (id == R.id.search_mag_icon){
SearchFragment searchFragment = new SearchFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_container, searchFragment)
.addToBackStack(null)
.commit();
}
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_register) {
final RegisterFragment registerFragment = new RegisterFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_container, registerFragment)
.addToBackStack(null)
.commit();
} else if (id == R.id.nav_login) {
final LoginFragment loginFragment = new LoginFragment();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_container, loginFragment)
.addToBackStack(null)
.commit();
} else if(id == R.id.nav_logout) {
userStatus.logoutUser(getApplicationContext());
userStatus.setNavHeaderOnLogout(navigationView);
updateNavDrawer("logout",register,login,logout, expiredListing, completeListing, activeListing);
} else if (id == R.id.nav_my_listings) {
// navigate to my listings
} else if (id == R.id.nav_how) {
// navigate to how it works page
} else if (id == R.id.nav_help) {
// navigate to help page
} else if (id == R.id.nav_contact_us) {
// navigate to contact page,
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
private void updateNavDrawer(String action, MenuItem register, MenuItem login, MenuItem logout, MenuItem expiredListing, MenuItem completeListing, MenuItem activeListing){
if(action=="login"){
register.setVisible(false);
login.setVisible(false);
logout.setVisible(true);
completeListing.setVisible(true);
activeListing.setVisible(true);
expiredListing.setVisible(true);
} else {
register.setVisible(true);
login.setVisible(true);
logout.setVisible(false);
completeListing.setVisible(false);
activeListing.setVisible(false);
expiredListing.setVisible(false);
}
}
private void getMenuItems(NavigationView nv){
register = nv.getMenu().getItem(0);
login = nv.getMenu().getItem(1);
logout = nv.getMenu().getItem(2);
activeListing = nv.getMenu().getItem(3);
completeListing = nv.getMenu().getItem(4);
expiredListing = nv.getMenu().getItem(5);
}
}
I cannot seem to workout why changing the layout is breaking the ActionBar menu options, any help would be appreciated.
Edit:
Changing the <ScrollView> element to <LinearLayout> seems to solve it but I need a ScrollView. The ScrollView seems to overlap the ActionBar and is on the top.
Try setting android:layout_height on the ScrollView to "match_parent" instead of "wrap_content"
I made a drawer navigation based on a tutorial on the internet and I followed everything but when I open my app everything is working correctly except my onclick event. I'm pretty new to android (2 weeks) and tried to figure it out by myself but it didn't work out. I tries onclicklistener but that one didn't give any possitive feedback for me.
How do I make a click event that will take me to another activity?
my code:
public class LayoutOneActivity extends ActionBarActivity {
String[] menu;
DrawerLayout dLayout;
ListView dList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_one);
Resources res = getResources();
String [] menu_items = res.getStringArray(R.array.menu_items); // String array where the menu items will be stored
menu = menu_items; // Variable for the menu items
dLayout = (DrawerLayout) findViewById(R.id.drawer_layout); // Looking for the id "drawer_layout" and apply as layout
dList = (ListView) findViewById(R.id.left_drawer); // Looking for the listview where the items will be stored
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,menu);// Making a new adapter
dList.setAdapter(adapter);// Give the list-layout the variable "adapter" which is an adapter (obviously)
dList.setSelector(R.drawable.back);// Sets the colour of the list-layout
dList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long id)
{
dLayout.closeDrawers();// The layout will be clossed when clicked outside the layout
Bundle args = new Bundle();// New bundle which will parse the data between various activities
args.putString("Menu", menu[position]);
Fragment detail = new DetailFragment();
detail.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, detail).commit();
}
});
}
layout_one
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="48dp"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="90dp"
android:orientation="horizontal">
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity1"
android:text="#string/clickActivity1" />
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity2"
android:text="#string/clickActivity2" />
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity3"
android:text="#string/clickActivity3" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="90dp"
android:orientation="horizontal">
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity4"
android:text="#string/clickActivity4"/>
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity5"
android:text="#string/clickActivity5"/>
<Button
android:layout_width="80dp"
android:layout_height="85dp"
android:background="#drawable/button"
android:onClick="openNewActivity6"
android:text="#string/clickActivity6"/>
</LinearLayout>
</LinearLayout>
</RelativeLayout> </FrameLayout>
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#fff"/> </android.support.v4.widget.DrawerLayout>
menu_detail_fragment
<?xml version="1.0" encoding="utf-8"?> <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:gravity="center"
android:background="#5ba4e5"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40px"
android:textColor="#ffffff"
android:layout_gravity="center"
android:id="#+id/detail"/> </LinearLayout>
To set a navigation menu onClickListener you have to implement the NavigationView.OnNavigationItemSelectedListener interface on the Activity.
On the onCreate method you have to define the navigation onClickListener to the context Activity like this:
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
Then you have to Override the method
#Override
public boolean onNavigationItemSelected(MenuItem item)
I write an example of how to implement the method below:
#Override
public boolean onNavigationItemSelected(MenuItem item){
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
EventFragment eventFragment = new EventFragment();
Bundle bundle = new Bundle();
bundle.putString("selectedEvent", "Urban");
eventFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame,eventFragment).commit();
} else if (id == R.id.nav_gallery) {
EventFragment eventFragment = new EventFragment();
Bundle bundle = new Bundle();
bundle.putString("selectedEvent", "Cosmos");
eventFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame,eventFragment).commit();
} else if (id == R.id.nav_slideshow) {
EventFragment eventFragment = new EventFragment();
Bundle bundle = new Bundle();
bundle.putString("selectedEvent", "Sink");
eventFragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame,eventFragment).commit();
} else if (id == R.id.nav_share) {
ShopListFragment intent = new ShopListFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.mainFrame, intent).commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(START);
return true;
}