This is my MainActivity.java File.
I got error while MainActivity is running in app. What should i do ?
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
private Button btnTutor;
private Button btnStudent;
private TextView repIssue;
private TextView appVersion;
/**
* 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);
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
setContentView(R.layout.activity_main);
OnClickListener socialsClickListener = new OnClickListener(){
#Override
public void onClick(View v) {
Intent viewIntent = null;
viewIntent = new Intent(getApplicationContext(), MainActivity.class);
viewIntent.putExtra("PAGE", getSocialClicked(v.getId()));
startActivity(viewIntent);
}
};
// Loading Font Face
Typeface tfTitle = Typeface.createFromAsset(getAssets(), "Roboto-Light.ttf");
Typeface tfButtons = Typeface.createFromAsset(getAssets(), "Eraser.ttf");
((TextView) findViewById(R.id.txt_title)).setTypeface(tfTitle);
btnTutor = (Button)findViewById(R.id.btn_tutor);
btnTutor.setOnClickListener(socialsClickListener);
btnTutor.setTypeface(tfButtons);
btnStudent = (Button)findViewById(R.id.btn_student);
btnStudent.setOnClickListener(socialsClickListener);
btnStudent.setTypeface(tfButtons);
repIssue = (TextView) findViewById(R.id.txt_report);
repIssue.setOnClickListener(socialsClickListener);
appVersion = (TextView) findViewById(R.id.txt_app_version);
appVersion.setOnClickListener(socialsClickListener);
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
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);
break;
case 3:
mTitle = getString(R.string.title_section3);
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.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);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(getArguments().getInt(
ARG_SECTION_NUMBER));
}
}
private String getSocialClicked(int id){
switch (id) {
case R.id.btn_tutor:
return "http://m.getedgeucated.com/sshs/dashboard/login.html";
case R.id.btn_student:
return "http://m.getedgeucated.com/sshs/timecheck.html";
case R.id.txt_app_version:
return "http://m.getedgeucated.com/sshs/appsupport.html";
case R.id.txt_report:
return "http://sshs.getedgeucated.com/chatsupport_redirect.html";
default:
return "";
}
}
}
`
This is my activity_main.xml.
`
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/activity_vertical_margin"
android:layout_gravity="center"
android:src="#drawable/getedgeucated_logo"
android:adjustViewBounds="true"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:textStyle="bold"
android:text="#string/logo_desc"
android:textColor="#android:color/darker_gray"
android:textAppearance="?android:attr/textAppearanceMedium"/>
<TextView
android:id="#+id/txt_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/dp_margin"
android:layout_gravity="center"
android:gravity="center"
android:textStyle="bold"
android:text="#string/subtitle"
android:textColor="#android:color/darker_gray"
android:textAppearance="?android:attr/textAppearanceLarge"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dip"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:orientation="vertical">
<Button
android:id="#+id/btn_student"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/half_padding"
android:background="#drawable/btn_home"
android:gravity="center"
android:text="I am a student"
android:textColor="#ffffff"
android:textSize="#dimen/text_size_large"
android:textStyle="bold" />
<Button
android:id="#+id/btn_tutor"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="I am a tutor"
android:textStyle="bold"
android:textColor="#ffffff"
android:textSize="#dimen/text_size_large"
android:background="#drawable/btn_home"
android:layout_margin="#dimen/half_padding"/>
</LinearLayout>
<TextView
android:id="#+id/txt_report"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:textStyle="bold"
android:text="#string/report_issue"
android:textColor="#color/background"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<TextView
android:id="#+id/txt_app_version"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:text="#string/app_version"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#color/background"
android:textStyle="bold" />
`
I still get error of FATAL EXCEPTION: main Java.io.NullpointerException error in debugger.
Begin with these steps :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
//The rest of your code
Related
Here is error
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.support.v7.widget.Toolbar.setNavigationOnClickListener(android.view.View$
OnClickListener)' on a null object reference
it happen on
toolBar.setNavigationOnClickListener(new View.OnClickListener()
imageView.setOnClickListener(new View.OnClickListener()
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener()
have the same problem "null object reference".
my team separate file to fragment and all action listener in MainActivity is broke down but we want to separate to fragment like this, but I can't find why separate file to fragment it will null object reference
Here XML fragment_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="0dp"
android:layout_height="56dp"
android:background="#color/colorPrimary"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
tools:layout_editor_absoluteY="0dp"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
<ImageView
android:id="#+id/pamba_icon_id"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="0dp"
app:layout_constraintLeft_toLeftOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="#drawable/pambaicon"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
android:layout_marginBottom="0dp"
app:layout_constraintVertical_bias="0.0" />
<ImageView
android:id="#+id/filter_icon_id"
android:clickable="true"
android:layout_width="25dp"
android:layout_height="25dp"
android:layout_marginBottom="8dp"
android:layout_marginRight="48dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="#+id/toolbar"
app:layout_constraintRight_toRightOf="#+id/toolbar"
app:layout_constraintTop_toTopOf="#+id/toolbar"
app:srcCompat="#drawable/filter"
app:layout_constraintVertical_bias="0.533" />
<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/viewPaper_id"
android:layout_below="#id/toolbar">
</android.support.v4.view.ViewPager>
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.design.widget.BottomNavigationView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bottomNavigation_id"
android:layout_gravity="bottom"
android:background="?android:attr/windowBackground"
app:menu="#menu/bottom_navigation_menu"
app:theme="#style/BottomNavigationTheme"
app:itemBackground="#color/colorGray"/>
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
Here activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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:layoutDirection="rtl"><!--set tool bar right to left set drawer to right-->
<android.support.constraint.ConstraintLayout
android:id="#+id/contentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.constraint.ConstraintLayout>
Here MainFragment
import...
public class MainFragment extends Fragment {
public MainFragment() {
super();
}
public static MainFragment newInstance() {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
initInstances(rootView);
return rootView;
}
private void initInstances(View rootView) {
// Init 'View' instance(s) with rootView.findViewById here
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
/*
* Save Instance State Here
*/
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save Instance State here
}
/*
* Restore Instance State Here
*/
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore Instance State here
}
}
}
and MainActivity
import...
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{
Toolbar toolBar;
DrawerLayout drawerLayout;
NavigationView navigationView;
ImageView imageView;
BottomNavigationView bottomNavigationView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigation_drawer);
setTitle(R.string.title);
drawerLayout = (DrawerLayout) findViewById(R.id.drawe_layout);
navigationView = (NavigationView) findViewById(R.id.navigation_view);
imageView = (ImageView) findViewById(R.id.filter_icon_id);
navigationView.setNavigationItemSelectedListener(this);
final ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolBar, R.string.open_drawer, R.string.close_drawer);
drawerLayout.setDrawerListener(toggle);
toggle.syncState();
// set own toolbar
toolBar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolBar);
toolBar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (drawerLayout.isDrawerOpen(Gravity.RIGHT)) {
drawerLayout.closeDrawer(Gravity.RIGHT);
} else {
drawerLayout.openDrawer(Gravity.RIGHT);
}
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "filter click", Toast.LENGTH_SHORT).show();
}
});
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigation_id);
// select item from bottom navigation
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.firstpage_id:
Toast.makeText(getApplicationContext(), "home", Toast.LENGTH_SHORT).show();
break;
case R.id.offergape_id:
Toast.makeText(getApplicationContext(), "offer", Toast.LENGTH_SHORT).show();
break;
case R.id.needpage_id:
Toast.makeText(getApplicationContext(), "need", Toast.LENGTH_SHORT).show();
break;
case R.id.searchpage_id:
Toast.makeText(getApplicationContext(), "search", Toast.LENGTH_SHORT).show();
break;
}
return true;
}
});
}
//close drawer when click back
#Override
public void onBackPressed() {
if(drawerLayout.isDrawerOpen(GravityCompat.END)){
drawerLayout.closeDrawer(GravityCompat.END);
}else {
super.onBackPressed();
}
}
// select item from drawer
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.account_detail_id:
Toast.makeText(getApplicationContext(), "account", Toast.LENGTH_SHORT).show();
break;
case R.id.trip_detail_id:
Toast.makeText(getApplicationContext(), "detail", Toast.LENGTH_SHORT).show();
break;
case R.id.mail_id:
Toast.makeText(getApplicationContext(), "mail", Toast.LENGTH_SHORT).show();
break;
case R.id.logout_id:
Toast.makeText(getApplicationContext(), "logout", Toast.LENGTH_SHORT).show();
break;
}
drawerLayout.closeDrawer(GravityCompat.END);
return true;
}
}
edit add navigation_drawer.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:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/drawe_layout"
android:fitsSystemWindows="true"
tools:openDrawer="end">
<!--set drawer open from right-->
<include layout="#layout/activity_main"/>
<android.support.design.widget.NavigationView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="#+id/navigation_view"
android:background="#color/colorGray"
android:fitsSystemWindows="true"
app:headerLayout="#layout/navigation_header"
app:menu="#menu/navigation_menu"
app:theme="#style/NavigationDrawerStyle"
android:layout_gravity="end"/>
<!--set drawer open from right-->
</android.support.v4.widget.DrawerLayout>
Your setContentView in onCreate is setting it to R.layout.navigation_drawer. You didn't provide an example of that, but instead provided an example of R.layout.fragment_main. I'm thinking you want that one to be your layout instead. So in onCreate in your activity set your content view to that layout instead:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
... // The rest of your code here
}
The Problem:
In my onCreate() on my main activity, I am trying to set the text value of a TextView in my fragment which is displayed by a viewpager. When I try to get my fragment instance, It always returns null.
Solutions I Tried:
Almost every solution related to this problem on SO gives me the same result(NPE).
My Code is below as well as some explanation...
Home.java Activity (My Main Activity):
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Show the home layout
setContentView(R.layout.home);
// Setup the toolbar
Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Now setup our tab bar
TabLayout tabLayout = (TabLayout)findViewById(R.id.homeTabs);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
// Setup the view pager
ViewPager viewPager = (ViewPager)findViewById(R.id.viewPager);
PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager);
// Start our service controller
Intent startServiceController = new Intent(this, ServiceController.class);
startService(startServiceController);
Fragment viewFragment = pagerAdapter.getRegisteredFragment(viewPager.getCurrentItem());
if(viewFragment == null){
Log.v("Fragment", "NULL");
}
}
After setting up the pageAdapter and viewpager, I try to access the fragment thats being shown. The code for my PagerAdapter is below...
PagerAdapter:
public class PagerAdapter extends SmartFragmentStatePagerAdapter {
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new ParkListFragment();
case 1:
return new MapFragment();
default:
return null;
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
CharSequence title;
switch (position){
case 0:
title = "Spaces Near You";
break;
case 1:
title = "Map";
break;
default:
title = "N/A";
break;
}
return title;
}
}
SmartFragmentStatePagerAdapter:
public abstract class SmartFragmentStatePagerAdapter extends FragmentStatePagerAdapter {
// Sparse array to keep track of registered fragments in memory
private SparseArray<Fragment> registeredFragments = new SparseArray<>();
public SmartFragmentStatePagerAdapter(FragmentManager fragmentManager) {
super(fragmentManager);
}
// Register the fragment when the item is instantiated
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
// Unregister when the item is inactive
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
// Returns the fragment for the position (if instantiated)
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
I really don't understand what the issue is. I have tried many things. What I don't want to use is this:
String tag="android:switcher:" + viewId + ":" + index;
ParkListFragment.java:
public class ParkListFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.park_list_fragment, container, false);
}
}
ParkList Fragment Layout:
<?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:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/confidenceText"
android:textAlignment="center"
android:textSize="24sp"
android:textColor="#android:color/primary_text_light"
android:padding="10dp"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_centerInParent="true">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/activityText"
android:textAlignment="center"
android:textSize="24sp"
android:textColor="#android:color/primary_text_light"
android:padding="10dp"/>
</LinearLayout>
</RelativeLayout>
</LinearLayout>
Stack Trace: Pastebin
So after hours of trial and error, the only thing that worked for me was this SO post:
ViewPager Fragments are not initiated in onCreate
I've implemented TabLayout from the support library, but it overwrites the ActionBar that i need.
This is the activity that sets it up and inflates the tabs and loads the fragment for the tab.
public class TabsActivity extends android.support.v4.app.FragmentActivity {
FloatingActionButton fab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
setTitle("Fuel Logger");
ActionBar a = getActionBar();
ViewPager vp = (ViewPager) findViewById(R.id.viewpager);
vp.setAdapter(new FragmentPagerAdapter(
getSupportFragmentManager(), TabsActivity.this
));
TabLayout tabLayout = (TabLayout) findViewById(R.id.fuel_sliding_tabs);
tabLayout.setupWithViewPager(vp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.fuel_menu, menu);
MenuItem refresh = menu.findItem(R.id.action_settings);
refresh.setEnabled(true);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id){
case R.id.action_settings:
break;
case R.id.action_favorite:
return true;
default:
}
return super.onOptionsItemSelected(item);
}
}
and the xml is just the view pager and tab layout
<?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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.TabLayout
style="#style/FuelTabLayout"
android:id="#+id/fuel_sliding_tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabMode="scrollable"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1.27"
android:background="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_below="#+id/fuel_sliding_tabs" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#android:drawable/ic_menu_set_as"
app:layout_anchorGravity="bottom|right|end"
app:backgroundTint="#color/colorAccent"
android:layout_gravity="right"
android:cropToPadding="true"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginRight="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp" />
</RelativeLayout>
and an example of fragments code which is more or less the same for each fragments class
Public class SummaryFragment extends android.support.v4.app.Fragment {
public static final String ARG_PAGE = "SUMM_PAGE";
private int mTab;
public static SummaryFragment newInstance(int page){
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SummaryFragment frag = new SummaryFragment();
frag.setArguments(args);
return frag;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTab = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_tab_summary, null);
return view;
}
first add ToolBar , and use LinearLayout witch have horizontal orientation
and set the in the style NoActionBar
hope its help you
Im trying to go from MainFragment to AddPostFragment with an ImageButton.
How is this possible...I tried a lot of things...
I want to use a fragment to keep my navigation drawer on top instead of a new activity.
MainFragment:
public class MainFragment extends Fragment implements View.OnClickListener{
ImageButton floatButton;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
floatButton = (ImageButton)rootView.findViewById(R.id.postButtonMain);
floatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent post = new Intent(getActivity(), AddPostFragment.class);
startActivity(post);
}
});
return rootView;
}
#Override
public void onClick(View v) {
}
}
AddPostFragment:
public class AddPostFragment extends Fragment {
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.frag_add_post, container, false);
return rootView;
}
}
XML MainFragment:
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Home"
android:id="#+id/frag_home"
android:layout_gravity="center_horizontal|top" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/postButtonMain"
android:src="#drawable/rsz_add_car"
android:background="?android:attr/selectableItemBackground"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_gravity="right|bottom" />
XML AddPostFragment:
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Add Post"
android:id="#+id/add_post"
android:layout_gravity="center_horizontal|top"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Airport"
android:id="#+id/text_airport"
android:layout_marginTop="88dp"
android:layout_below="#+id/add_post"
android:layout_toLeftOf="#+id/add_post"
android:layout_toStartOf="#+id/add_post" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Date"
android:id="#+id/text_date"
android:layout_below="#+id/text_airport"
android:layout_alignRight="#+id/text_airport"
android:layout_alignEnd="#+id/text_airport"
android:layout_marginTop="36dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Time"
android:id="#+id/text_time"
android:layout_centerVertical="true"
android:layout_alignRight="#+id/text_date"
android:layout_alignEnd="#+id/text_date" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Persons"
android:id="#+id/text_persons"
android:layout_marginTop="43dp"
android:layout_below="#+id/add_time"
android:layout_toLeftOf="#+id/add_time"
android:layout_toStartOf="#+id/add_time" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Address"
android:id="#+id/text_address"
android:layout_marginTop="48dp"
android:layout_below="#+id/text_persons"
android:layout_alignLeft="#+id/text_persons"
android:layout_alignStart="#+id/text_persons" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="time"
android:ems="10"
android:id="#+id/add_time"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/text_time"
android:layout_alignRight="#+id/add_post"
android:layout_alignEnd="#+id/add_post" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="date"
android:ems="10"
android:id="#+id/add_date"
android:layout_alignTop="#+id/text_date"
android:layout_toRightOf="#+id/text_date"
android:layout_alignRight="#+id/add_time"
android:layout_alignEnd="#+id/add_time" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="#+id/add_persons"
android:layout_above="#+id/text_address"
android:layout_toRightOf="#+id/text_persons"
android:layout_alignRight="#+id/add_post"
android:layout_alignEnd="#+id/add_post" />
<android.support.v7.widget.SearchView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/add_search"
android:layout_above="#+id/text_date"
android:layout_toRightOf="#+id/text_airport"
android:layout_toEndOf="#+id/text_airport" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/add_address"
android:layout_alignBottom="#+id/text_address"
android:layout_alignRight="#+id/add_post"
android:layout_alignEnd="#+id/add_post"
android:layout_toRightOf="#+id/text_address"
android:layout_toEndOf="#+id/text_address" />
MainMenu with navigation drawer:
public class MainMenu extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Fragment someFragment;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
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();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
FragmentManager fm = getFragmentManager();
fm.beginTransaction().replace(R.id.content_main, new MainFragment()).commit();
}
#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, 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
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fm = getFragmentManager();
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_home) {
// Handle the home action
fm.beginTransaction().replace(R.id.content_main, new MainFragment()).commit();
} else if (id == R.id.nav_demand) {
fm.beginTransaction().replace(R.id.content_main, new DemandFragment()).commit();
} else if (id == R.id.nav_posts) {
fm.beginTransaction().replace(R.id.content_main, new PostsFragment()).commit();
} else if (id == R.id.nav_messages) {
fm.beginTransaction().replace(R.id.content_main, new MessagesFragment()).commit();
} else if (id == R.id.nav_settings) {
fm.beginTransaction().replace(R.id.content_main, new SettingsFragment()).commit();
} else if (id == R.id.nav_logout) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
You have to do just the same thing you're doing on the onNavigationItemSelected
floatButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fm = getActivity().getFragmentManager();
fm.beginTransaction().replace(R.id.content_main, new PostsFragment()).commit();
}
});
I'm developing a material design app.
I wanted to place the title of the Toolbar in the center of the Toolbar.
I somehow achieved the above task, but the problem is that there are two titles now as shown in the screenshot below:
What I want is that I want to remove the title which is appearing at the bottom of the toolbar, but I am unable to figure out how to do so!
Here's activity_main.xml file's code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="128dp"
android:minHeight="?attr/actionBarSize"
android:gravity="bottom"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:layout_scrollFlags="scroll|enterAlways">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Title"
android:textSize="20sp"
android:textColor="#fff"
android:layout_gravity="center" />
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
<android.support.v4.view.ViewPager
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email"/>
</android.support.design.widget.CoordinatorLayout>
Here's MainActivity.java file's code:
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Typeface typeFace = Typeface.createFromAsset(getAssets(),"fonts/Pacifico.ttf");
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);
mTitle.setTypeface(typeFace);
toolbar.setTitle(mTitle.getText().toString());
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Section 1";
case 1:
return "Section 2";
}
return null;
}
}
/**
* 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);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}
}
Please let me know how can do this.
Thanks in advance.
I got the solution!
Adding just getSupportActionBar().setDisplayShowTitleEnabled(false); to the code did the job.