I need some help. I've done some extensive searching for the past 4 hours and I'm not sure if it's because I have errors in my code, or if I'm not doing something correctly.
Basically, this is what's going on. I have my main activity 'homepage' which opens to a second activity with a navigation drawer. I assume that the navigation drawer is also an 'activity'. I am trying to open a fragment within that activity with the button, but I keep getting a fatal exception:
10-14 21:36:54.469 799-799/com.example.workstation.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.workstation.app/com.example.workstation.app.navigation_drawer}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.workstation.app.navigationdrawer.onCreate(navigationdrawer.java:57)
Here is the code I am working with, this one is for the navigation_drawer activity (I believe):
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.workstation.app.navigation_drawer_activity$PlaceholderFragment">
<TextView
android:id="#+id/cctr_ct_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cctr_ct"
android:textSize="40sp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cctr_search"
android:drawableTop="#drawable/search"
android:layout_below="#+id/cctr_ct_home"
android:layout_alignLeft="#+id/cctr_ct_home"
android:layout_alignStart="#+id/cctr_ct_home"
android:layout_marginTop="95dp"
android:text="Search"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cctr_favorites"
android:drawableTop="#drawable/favorites"
android:layout_alignTop="#+id/cctr_search"
android:layout_alignRight="#+id/cctr_ct_home"
android:layout_alignEnd="#+id/cctr_ct_home"
android:text="Favorite"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cctr_recent"
android:drawableTop="#drawable/recent"
android:layout_below="#+id/cctr_search"
android:layout_alignLeft="#+id/cctr_search"
android:layout_alignStart="#+id/cctr_search"
android:layout_marginTop="37dp"
android:text="Recent"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/cctr_contactus"
android:drawableTop="#drawable/email"
android:layout_alignTop="#+id/cctr_recent"
android:layout_alignLeft="#+id/cctr_favorites"
android:layout_alignStart="#+id/cctr_favorites"
android:text="Contact Us" />
<fragment android:name="com.example.workstation.cctrmobileapp.cctrct_search"
android:id="#+id/cctr_ct_search"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</RelativeLayout>
Now, the navigation drawer works fine, it's opening the fragment from the button I'm having trouble with. I get the error above. Here is the java code from the activity that comes with the navigation drawer:
package com.example.workstation.cctrmobileapp;
import android.app.Activity;
import android.support.v4.app.FragmentTransaction;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
public class cctr_clinical_trials extends ActionBarActivity implements NavigationDrawerFragment.NavigationDrawerCallbacks, cctrct_search.OnFragmentInteractionListener {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
Button cctrct_searchButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cctr_clinical_trials);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
cctrct_searchButton = (Button)findViewById(R.id.cctr_search);
cctrct_searchButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
cctrct_search newFragment = new cctrct_search();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
/* cctrct_searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FragmentManager searchFragment = getSupportFragmentManager();
searchFragment.beginTransaction()
.replace(R.id.container, cctrct_search.newInstance("test1", "test2"))
.commit();
}
});*/
}
and for the heck of it, here is the xml for the fragment that I want to appear after I press the button:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.workstation.cctrmobileapp.cctrct_search">
<!-- TODO: Update blank fragment layout -->
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:id="#+id/cctrct_search_submit"
android:layout_below="#+id/cctrct_p1"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp"
android:layout_gravity="center_horizontal|bottom" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Only the submit button works"
android:id="#+id/cctr_search_logo"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="43dp"
android:layout_gravity="center_horizontal|top" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phase III"
android:id="#+id/cctrct_p3"
android:layout_toEndOf="#+id/cctrct_search_dsite"
android:layout_below="#+id/cctrct_search_pnum"
android:layout_toRightOf="#+id/cctrct_search_dsite"
android:layout_marginTop="28dp"
android:layout_gravity="center" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phase II"
android:id="#+id/cctrct_p2"
android:layout_toEndOf="#+id/cctrct_p1"
android:layout_alignTop="#+id/cctrct_p3"
android:layout_alignLeft="#+id/cctrct_search_keyword"
android:layout_alignStart="#+id/cctrct_search_keyword"
android:layout_alignRight="#+id/cctrct_search_dsite"
android:layout_alignEnd="#+id/cctrct_search_dsite"
android:layout_gravity="center" />
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Phase I"
android:id="#+id/cctrct_p1"
android:layout_toStartOf="#+id/cctrct_search_pnum"
android:layout_alignTop="#+id/cctrct_p2"
android:layout_toLeftOf="#+id/cctrct_search_pnum"
android:layout_gravity="center" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Keyword"
android:id="#+id/cctrct_search_keyword"
android:layout_below="#+id/cctrct_search_dsite"
android:layout_alignRight="#+id/cctrct_search_submit"
android:layout_alignEnd="#+id/cctrct_search_submit"
android:layout_marginTop="26dp"
android:layout_gravity="left|center_vertical" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Disease Site"
android:id="#+id/cctrct_search_dsite"
android:layout_below="#+id/cctr_search_logo"
android:layout_centerHorizontal="true"
android:layout_marginTop="22dp"
android:layout_gravity="right|center_vertical" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Protocol Number"
android:id="#+id/cctrct_search_pnum"
android:layout_below="#+id/cctrct_search_keyword"
android:layout_centerHorizontal="true"
android:layout_marginTop="31dp"
android:layout_gravity="left|center_vertical" />
</RelativeLayout>
</FrameLayout>
I just figured I would add the rest of the code from my class:
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
switch (position) {
case 0: fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit(); break;
case 1: fragmentManager.beginTransaction()
.replace(R.id.container, cctrct_search.newInstance("test1", "test2"))
.commit(); break;
case 2: fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit(); break;
case 3: fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit(); break;
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.cctr_ct_home);
break;
case 2:
mTitle = getString(R.string.cctr_ct_search);
break;
case 3:
mTitle = getString(R.string.cctr_ct_saved);
break;
case 4:
mTitle = getString(R.string.cctr_ct_recent);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.cctr_clinical_trials, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onFragmentInteraction(Uri uri) {
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_cctr_clinical_trials, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((cctr_clinical_trials) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
It looks like cctrct_searchButton is null which means it is not being found in the view. Is a Button with the id cctr_search present in the activity_cctr_clinical_trials layout xml file?
For future users, Mr. Spidy was 100% correct, the onClickListener should have been in the onCreateView and not in the onCreate section:
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_cctr_clinical_trials, container, false);
Button cctrct_searchButton;
cctrct_searchButton = (Button)rootView.findViewById(R.id.cctr_search);
cctrct_searchButton.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
Fragment newFragment = new cctrct_search();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, newFragment);
transaction.addToBackStack(null);
transaction.commit();
}
});
return rootView;
}
THANKS AGAIN MR. SPIDY
Related
I have got a working Navigation drawer in a blank project, however whenever I try to implement the navigation drawer in to an existing project, it doesn't seem to be working properly.
The navigation drawer displays fine, however, when items inside are selected, it doesn't seem to redirect to the fragment selected.
I have tried using many resources, however, I am still unable to progress.
Thanks in advance.
Here is my code below:
NavigationDrawer Class
import android.net.Uri;
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
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.AbsListView;
public class NDrawer extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener,
About.OnFragmentInteractionListener, Home.OnFragmentInteractionListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Fragment fragment;
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
Fragment fragment;
if (id == R.id.nav_home) {
fragment = new Home();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.detach(fragment);
ft.attach(fragment);
ft.commit();
} else if (id == R.id.nav_rooms) {
} else if (id == R.id.nav_account) {
} else if (id == R.id.nav_settings) {
} else if (id == R.id.nav_help) {
} else if (id == R.id.nav_about) {
fragment = new About();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.detach(fragment);
ft.attach(fragment);
ft.commit();
} else if (id == R.id.nav_signout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
}
About Fragment Class
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link About.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link About#newInstance} factory method to
* create an instance of this fragment.
*/
public class About extends Fragment {
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public About() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment About.
*/
public static About newInstance(String param1, String param2) {
About fragment = new About();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.activity_about, container, false);
}
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
void onFragmentInteraction(Uri uri);
}
}
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">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:gravity="center"
android:orientation="vertical"
android:padding="10dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
tools:context=".UserActivity">
<TextView
style="#style/Base.TextAppearance.AppCompat.Headline"
android:id="#+id/displayUsername"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:layout_margin="5dp"/>
<Button
android:id="#+id/listen_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Listen"
android:onClick="buttonClicked"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:id="#+id/textView"
/>
<TextView
android:id="#+id/status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="" />
<TextView
style="#style/Base.TextAppearance.AppCompat.Headline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="#string/signed_in_header" />
<Button android:id="#+id/btn_settings"
android:text="#string/settings"
android:layout_marginTop="40dp"
android:layout_width="190dp"
android:layout_height="45dp"
android:onClick="buttonClicked" />
<Button android:id="#+id/btn_sign_out"
android:text="#string/sign_out"
android:layout_marginTop="40dp"
android:layout_width="190dp"
android:layout_height="45dp"
android:onClick="buttonClicked" />
<TextView
android:id="#+id/displayUsername2"
android:layout_width="242dp"
android:layout_height="34dp"
android:padding="5dp"
android:layout_margin="5dp"/>
</LinearLayout>
<include
layout="#layout/app_bar_nav"
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_nav"
app:menu="#menu/activity_nav_drawer" />
</android.support.v4.widget.DrawerLayout>
activity_nav_drawer.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
+6 <group android:checkableBehavior="single">
<item
android:id="#+id/nav_home"
android:icon="#drawable/ic_home"
android:checked="true"
android:title="Home" />
<item
android:id="#+id/nav_rooms"
android:icon="#drawable/ic_room_black"
android:title="All Rooms" />
<item
android:id="#+id/nav_account"
android:icon="#drawable/ic_account_box_black"
android:title="Account" />
<item
android:id="#+id/nav_settings"
android:icon="#drawable/ic_settings_black"
android:title="Settings" />
<item
android:id="#+id/nav_help"
android:icon="#drawable/ic_help_black"
android:title="Help" />
<item
android:id="#+id/nav_about"
android:title="About" />
<item
android:id="#+id/nav_signout"
android:icon="#drawable/ic_input_black"
android:title="Logout" />
</group>
</menu>
content_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:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".NDrawer"
tools:showIn="#layout/app_bar_nav">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/content_frame"
android:orientation="horizontal" />
</android.support.constraint.ConstraintLayout>
app_bar_nav.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"
tools:context="aviraj.firebaseapp.NDrawer">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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_main" />
</android.support.design.widget.CoordinatorLayout>
But in all honesty - have one more try at this and implement the navigation drawer class from scratch from a template class and put our other main clases in method by method to see any possible conflicts.
i just needed some quick help. I got a nav drawer setup, and i use activity main as my welcome screen, so I put a text box on the activity_main, but the problem is that when I chose other nav drawer pages, i see the text box from the activity main.
What one of my activity pages should look like: http://puu.sh/nQFkc/1ed83811cc.png
What it ends up looking like: http://puu.sh/nQF93/785c9eee45.png
Need to mention im new to android?
Main Activity
package nota.outlawsindex;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class MainActivity extends AppCompatActivity {
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
Toolbar toolbar;
Scrollview scrollView;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
android.support.v7.app.ActionBarDrawerToggle mDrawerToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
ScrollView scrollView = (ScrollView) findViewById(R.id.scrollView);
setupToolbar();
DataModel[] drawerItem = new DataModel[4];//need to update this if you add start counting at 0
drawerItem[0] = new DataModel(R.drawable.ic_connect, "Calculate Sentence");
drawerItem[1] = new DataModel(R.drawable.ic_fixtures, "Felonies");
drawerItem[2] = new DataModel(R.drawable.ic_table, "Misdemeanors");
drawerItem[3] = new DataModel(R.drawable.ic_drawer, "Infractions");
//add on to the list to create more pages
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setHomeButtonEnabled(true);
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.list_view_item_row, drawerItem);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLayout.setDrawerListener(mDrawerToggle);
setupDrawerToggle();
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
scrollView.setVisibility(View.GONE);
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ConnectFragment();
break;
case 1:
fragment = new FixturesFragment();
break;
case 2:
fragment = new TableFragment();
break;
case 3:
fragment = new SelfAddedFragment();
break;
//add more cases if you add more pages
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
//
int id = item.getItemId();
//
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
} else if (id == R.id.action_settings) {
Toast.makeText(getApplicationContext(), "Settings", Toast.LENGTH_SHORT).show();
return true;
}
Toast.makeText(getApplicationContext(), "Search", Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
void setupToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayShowHomeEnabled(true);
}
void setupDrawerToggle() {
mDrawerToggle = new android.support.v7.app.ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
//This is necessary to change the icon of the Drawer Toggle upon state change.
mDrawerToggle.syncState();
}
}
Activity_Main
<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"
android:background="#color/backgroundColor">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/relativeLayout"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<RelativeLayout
android:id="#+id/container_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</RelativeLayout>
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/container_toolbar"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</FrameLayout>
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
android:layout_gravity="right|top"
android:layout_below="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="26dp"
android:layout_marginStart="26dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/scrollView"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/content_frame"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/relativeLayout2"
android:focusable="false">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="? android:attr/textAppearanceSmall"
android:text=" Welcome to The Outlaw's Index! An app designed for individuals who want to educate themselves with knowledge regarding different types of offenses in the United States. Currently this app is directed towards individuals in the United States, but a Canadian version may be released in upcoming months. This app gives users the tools and resources to research different classes of offenses and the repercussions one would receive if convicted. Although this app is informative, advice from law enforcement, attorneys, and other members of the law should be considered more accurate as it may suit your personal needs regarding a specific case. To start off, choose any of the classes on the left hand side, or calculate a sentence and the repercussions that would follow."
android:id="#+id/textView2"
android:textColor="#ffffff"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:password="false"
android:phoneNumber="false"
android:singleLine="false"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="33dp" />
</RelativeLayout>
</ScrollView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Welcome"
android:id="#+id/textView"
android:textColor="#ffffff"
android:layout_above="#+id/scrollView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginLeft="27dp"
android:layout_marginStart="27dp" />
</RelativeLayout>
</RelativeLayout>
<ListView
android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:background="#color/menuBackgroundColor"
android:choiceMode="singleChoice"
android:divider="#color/colorAccent"
android:dividerHeight="1dp"
android:paddingTop="15dp"/>
<!-- because there is no header in this one I am using android:paddingTop="15dp"
to push the menu below the level of the translucent top bar.-->
One of my Navdrawer pages (Same one as in screenshots)
Fragment
package nota.outlawsindex;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class TableFragment extends Fragment {
Button MisdemeanorClassAButton = null;
Button MisdemeanorClassBButton = null;
Button MisdemeanorClassCButton = null;
Button MisdemeanorClassDButton = null;
TextView MisdemeanorText;
public TableFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_table, container, false);
init(rootView);
return rootView;
}
public void init(View view) {
MisdemeanorClassAButton = (Button) view.findViewById(R.id.MisdemeanorClassAButton);
MisdemeanorText = (TextView) view.findViewById(R.id.MisdemeanorText);
MisdemeanorClassAButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MisdemeanorText.setText(R.string.MA);
}
}
);
MisdemeanorClassBButton = (Button) view.findViewById(R.id.MisdemeanorClassBButton);
MisdemeanorText = (TextView) view.findViewById(R.id.MisdemeanorText);
MisdemeanorClassBButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MisdemeanorText.setText(R.string.MB);
}
}
);
MisdemeanorClassCButton = (Button) view.findViewById(R.id.MisdemeanorClassCButton);
MisdemeanorText = (TextView) view.findViewById(R.id.MisdemeanorText);
MisdemeanorClassCButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MisdemeanorText.setText(R.string.MC);
}
}
);
MisdemeanorClassDButton = (Button) view.findViewById(R.id.MisdemeanorClassDButton);
MisdemeanorText = (TextView) view.findViewById(R.id.MisdemeanorText);
MisdemeanorClassDButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MisdemeanorText.setText(R.string.MD);
}
}
);
}
}
The Activity Page of one of the NavDrawer Pages
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/backgroundColor">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="#string/MTB"
android:id="#+id/MisdemeanorText"
android:textColor="#ffffff"
android:layout_row="6"
android:layout_column="1"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Class A"
android:id="#+id/MisdemeanorClassAButton"
android:layout_marginTop="34dp"
android:layout_row="0"
android:layout_column="0"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Class B"
android:id="#+id/MisdemeanorClassBButton"
android:layout_row="0"
android:layout_column="1"
android:layout_alignTop="#+id/MisdemeanorClassAButton"
android:layout_toRightOf="#+id/MisdemeanorClassAButton"
android:layout_toEndOf="#+id/MisdemeanorClassAButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Class C"
android:id="#+id/MisdemeanorClassCButton"
android:layout_alignTop="#+id/MisdemeanorClassBButton"
android:layout_toLeftOf="#+id/MisdemeanorClassDButton"
android:layout_toStartOf="#+id/MisdemeanorClassDButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Class D"
android:id="#+id/MisdemeanorClassDButton"
android:layout_alignBottom="#+id/MisdemeanorClassCButton"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
The issue is with your layout.
Two approaches to fix your problem -
Whenever you instantiate any fragment by selecting any option from the navigation drawer, you can set ScrollView (containing the welcome text) visibility to GONE.
Scrollview scrollView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
scrollView = (ScrollView) findViewById(R.id.scrollView);
}
private void selectItem(int position) {
scrollView.setVisibility(View.GONE);
....
}
Create a one more fragment with the layout where you only show your welcome text and launch this fragment in onCreate() of your activity. So this will show the welcome text when user starts your app. and when user selects any item from Navdrawer, you can launch another fragment of your choice. But for this you should remove welcome text from activity layout xml.
How to change fragments when button is clicked? I'm using android studio 1.5 and using the new navigation drawer.
This is my MainActivity.java
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
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.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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, "bryanposvoc1339.garcia#gmail.com", 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) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
Fragment fragment;
if (id == R.id.nav_cough) {
fragment = new first();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
else if (id == R.id.nav_colds) {
fragment = new second();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
else if (id == R.id.nav_fever) {
fragment = new third();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
else if (id == R.id.nav_vegetables) {
fragment = new fourth();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
} else if (id == R.id.nav_fruits) {
fragment = new fifth();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
} else if (id == R.id.nav_about) {
fragment = new sixth();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is my 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>
content_main.xml this is where my framelayout is
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="appnaturemedicine.com.example.posvoc.naturesmedicine.MainActivity"
tools:showIn="#layout/app_bar_main"
android:background="#drawable/background">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent" android:id="#+id/mainFrame">
</FrameLayout>
</RelativeLayout>
I am able to go to the fragment i want, the problem is that how can i make the buttons in the fragment im in at to change the current fragment when clicked
here's my first fragment when i click one of the menu in the navigationdrawer
fragment_first.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="appnaturemedicine.com.example.posvoc.naturesmedicine.first">
<ImageView
android:layout_width="80dp"
android:layout_height="80dp"
android:id="#+id/imageView2"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#mipmap/ic_launcher_cough" />
<Button
android:layout_width="80dp"
android:layout_height="30dp"
android:id="#+id/button"
android:layout_alignBottom="#+id/textView3"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:onClick="onButtonClicked"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Lagundi (Vitex negundo)"
android:id="#+id/textView3"
android:textColor="#ff4081"
android:layout_below="#+id/imageView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Honey"
android:id="#+id/textView4"
android:textColor="#ff4081"
android:layout_alignBottom="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="80dp"
android:layout_height="30dp"
android:id="#+id/button3"
android:layout_below="#+id/button"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Probiotics"
android:id="#+id/textView5"
android:layout_alignBottom="#+id/button4"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toLeftOf="#+id/button4"
android:textColor="#ff4081"
android:layout_toStartOf="#+id/button4" />
<Button
android:layout_width="80dp"
android:layout_height="30dp"
android:id="#+id/button4"
android:layout_below="#+id/textView4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="80dp"
android:layout_height="30dp"
android:id="#+id/button5"
android:layout_below="#+id/button4"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="80dp"
android:layout_height="30dp"
android:id="#+id/button6"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/button5" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Bromelain"
android:id="#+id/textView6"
android:textColor="#ff4081"
android:layout_alignBaseline="#+id/button5"
android:layout_alignBottom="#+id/button5"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Peppermint"
android:id="#+id/textView7"
android:textColor="#ff4081"
android:layout_alignBaseline="#+id/button6"
android:layout_alignBottom="#+id/button6"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ImageView
android:layout_width="250dp"
android:layout_height="110dp"
android:id="#+id/imageView3"
android:background="#drawable/ben"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
first.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* A simple {#link Fragment} subclass.
*/
public class first extends Fragment {
public first() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false);
}
}
Can you make it something like when you click btn1 it goes to fragmentOne and when click btn2 it goes to fragmentTwo an if-else statement?
What do I put in here?
You can use OnfragmentInteractionListener for this. It is a interface that your activity should implement. You can call the methods from your fragments and it will be like it is calling a method from the activity.
In the following example, first fragment has a button which when clicked calls the method changeFragment(2) and similarly the second fragment calls method changeFragment(1). This method is implemented in the main activity and through if .. else it figures out which fragment to replace.
OnFragmentInteractionListener.java
public interface OnFragmentInteractionListener {
public void changeFragment(int id);
}
FragmentA:
public class first extends Fragment {
private OnFragmentInteractionListener mListener;
public first() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
Button btn = (Button) view.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.changeFragment(2);
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
FragmentB:
public class first extends Fragment {
private OnFragmentInteractionListener mListener;
public first() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_first, container, false);
Button btn = (Button) view.findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mListener.changeFragment(1);
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, OnFragmentInteractionListener {
//Rest of the code
#Override
public void changeFragment(int id){
if (id == 1) {
fragment = new first();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
else if (id == 2) {
fragment = new second();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.mainFrame, fragment);
ft.commit();
}
}
}
Hope it helps!!
I'm developing Android app with fragment. If I add setText in MainActivity.java inside onCreateView method, I will get Force Close error when running the app.
MainActivity.java
package com.example.app02;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.content.Intent;
public class MainActivity extends Activity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment) getFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
TextView t = (TextView)findViewById(R.id.result);
t.setText("weewoufzklfo");
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
PlaceholderFragment.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
Intent i = new Intent(this,SecondActivity.class);
startActivity(i);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
//set the text of textView
TextView txvMain = (TextView) rootView.findViewById(R.id.result);
txvMain.setText("afsewtrwe");
//set a drawable as the background of the textView
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
}
activity_main.xml
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.app02.MainActivity" >
<!--
As the main content view, the view below consumes the entire
space available using match_parent in both dimensions.
-->
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!--
android:layout_gravity="start" tells DrawerLayout to treat
this as a sliding drawer on the left side for left-to-right
languages and on the right side for right-to-left languages.
If you're not building against API 17 or higher, use
android:layout_gravity="left" instead.
-->
<!--
The drawer is given a fixed width in dp and extends the full height of
the container.
-->
<fragment
android:id="#+id/navigation_drawer"
android:name="com.example.app02.NavigationDrawerFragment"
android:layout_width="#dimen/navigation_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="left"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.app02.MainActivity$PlaceholderFragment" >
<EditText
android:id="#+id/search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Search" />
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_world" />
</RelativeLayout>
How to add setText method correctly?
You are trying to access your fragment layout's textView R.id.result in the onCreate() of your activity, which at that point might not even exist. Try setting the value of your textView in the fragment class itself.
public class YourFragmentClass extends Fragment
{
TextView textView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
textView =(TextView) view.findViewById(R.id.result);
textView.setText("weewoufzklfo");
return view;
}
}
Take a look at fragment lifecycle with respect to Activity lifecycle here.
I created a menu with 5 items in a navigation drawer, the 5 items represent 5 different fragments, each time an item gets clicked it should show the related fragment.
Another click on a different item, fragment should be replaced and so on.
I created 5 seperate classes for the fragments.
When i start the app and click an item the very first time, the related fragment gets shown but after i click another item in the menu nothing happens (the fragment gets not replaced), i also get no errors and the app does not crash.
I don`t know where the problem is hopefully somebody can help, here is my code:
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
private MyAdapter myAdapter;
public ListView mainMenuList;
public Fragment_Android fAndroid;
public Fragment_Latest_Releases fLatest;
public Fragment_My_Applications fMyapps;
public Fragment_Platforms fPlatforms;
public Fragment_Settings fSettings;
public android.support.v4.app.FragmentManager fragmanager;
public android.support.v4.app.FragmentTransaction fragtrans;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
mainMenuList = (ListView) findViewById(R.id.testList);
myAdapter = new MyAdapter(this);
mainMenuList.setAdapter(myAdapter);
toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
NavigationDrawerFragment drawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.fragment_navigation_drawer);
drawerFragment.setUp((R.id.fragment_navigation_drawer), (DrawerLayout) findViewById(R.id.drawer_layout), toolbar);
fAndroid = new Fragment_Android();
fLatest = new Fragment_Latest_Releases();
fMyapps = new Fragment_My_Applications();
fPlatforms = new Fragment_Platforms();
fSettings = new Fragment_Settings();
mainMenuList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0: {
Toast.makeText(getApplicationContext(), "Android has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fAndroid);
fragtrans.commit();
drawer.closeDrawers();
break;
}
case 1: {
Toast.makeText(getApplicationContext(), "Latest Releases has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fLatest);
fragtrans.commit();
drawer.closeDrawers();
break;
}
case 2: {
Toast.makeText(getApplicationContext(), "Platforms has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fPlatforms);
fragtrans.commit();
drawer.closeDrawers();
break;
}
case 3: {
Toast.makeText(getApplicationContext(), "My Applications has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fMyapps);
fragtrans.commit();
drawer.closeDrawers();
break;
}
case 4: {
Toast.makeText(getApplicationContext(), "Settings has been clicked.", Toast.LENGTH_SHORT).show();
fragmanager = getSupportFragmentManager();
fragtrans = fragmanager.beginTransaction();
fragtrans.replace(R.id.fragment_container, fSettings);
fragtrans.commit();
drawer.closeDrawers();
break;
}
}
}
});
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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(this, "Just hit settings.." + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
Example of 1 class (in this case Android):
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class Fragment_Android extends Fragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View fragandroid = inflater.inflate(R.layout.layout_android, null);
return fragandroid;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
Example of 1 fragment xml (Android fragment):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Android"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
My main activity xml:
<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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="android.kadas.org.teka.MainActivity">
<include
android:id="#+id/my_toolbar"
layout="#layout/app_bar" />
<android.support.v4.widget.DrawerLayout
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<fragment
android:id="#+id/fragment_navigation_drawer"
android:name="android.kadas.org.teka.NavigationDrawerFragment"
android:layout_width="#dimen/nav_drawer_width"
android:layout_height="match_parent"
android:layout_gravity="start"
app:layout="#layout/fragment_navigation_drawer"
tools:layout="#layout/fragment_navigation_drawer" />
</android.support.v4.widget.DrawerLayout>
</LinearLayout>
In the click listener you are actually replacing the entire layout of the activity with the desired fragment.
In your main activity's xml add the following layout, inside the RelativeLayout:
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Change your
fragtrans.replace(R.id.drawer_layout, fragmentX);
statements to
fragtrans.replace(R.id.container, fragmentX);
Finally solved due to the big help of Alexandru Rosianu.
The code has been amended with the correct one.