I am just starting to learn how to program, so sorry if this is a weird or dumb question.
I am making SlideingScreen using a ViewPager. I copied the code from here (http://developer.android.com/training/animation/screen-slide.html), but I keep getting the errors located here.
Here is the code with the two thingies:
package com.example.ryanfolz.gridgame;
import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
public class ScreenSlideActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//invalidateOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
menu.findItem(R.id.action_previous).setEnabled(mPager.getCurrentItem() > 0);
// Add either a "next" or "finish" button to the action bar, depending on which page
// is currently selected.
MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,
(mPager.getCurrentItem() == mPagerAdapter.getCount() - 1)
? R.string.action_finish
: R.string.action_next);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
case R.id.action_previous:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
The fragment is here
package com.example.ryanfolz.gridgame;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ScreenSlidePageFragment extends Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
ViewGroup rootView;
private int mPageNumber;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
if(mPageNumber == 1){
rootView = (ViewGroup) inflater
.inflate(R.layout.test, container, false);
((TextView) rootView.findViewById(R.id.test)).setText("Hello");
}else {
rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_screen_slide_page, container, false);
// Set the title view to show the page number.
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.title_template_step, mPageNumber + 1));
}
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
}
Delete these line from your import
import android.app.FragmentManager;
import android.app.Fragment;
When your IDE ask for which class to import, you should choose these classes from support package instead, like this:
android.support.v4.app.FragmentStatePagerAdapter;
Instead of using getFragmentManager(), you should call getSupportFragmentManager()
I am making SlideingScreen using a ViewPager. I copied the code from here (http://developer.android.com/training/animation/screen-slide.html), but I keep getting the errors
If you check the example properly they have imported
import android.support.v4.app.FragmentManager;
and not
import android.app.FragmentManager;
And also they have used
getSupportFragmentManager()
and not
getFragmentManager()
This changes is required because you are using the android support library for your fragment.
In your ScreenSlideActivity file, change
import android.app.FragmentManager;
to
import android.support.v4.app.FragmentManager;
And for ScreenSlidePageFragment, change this line
import android.app.Fragment;
into this
import android.support.v4.app.Fragment;
At last. Change all
getFragmentManager()
to
getSupportFragmentManager()
Related
what should I change? because I find so many errors if I change it to Fragment .. check out my code and help me fix it please
this is the package:
package com.example.ashraf.myapplication;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.view.PagerAdapter;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.widget.TextView;
and this is my class:
public class machinemessage extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
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);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(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_tab, 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 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";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static tab.PlaceholderFragment newInstance(int sectionNumber) {
tab.PlaceholderFragment fragment = new tab.PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab, 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;
}
}
/**
* 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 tab.PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
}
}
I recommend you to step by step copy the code of your Activity into a Fragment. See this Stackoverflow answer to get instructions in how to convert an Activity to a Fragment.
I'm new beginner using Android studio I have currently watched a couple tutorials on setting up a basic swipe view which generates up to 3 all which replicate the original page known in my code as page_fragment_layout.xml. I want to take this a step further a be able to link different pages containing a range of content. In this case I want to be able to link my Activity_main.xml and page_fragment_layout.xml together by swipe. I have added my code so far I would be most appreciative of any input.
MainActivity.java
package socialdeveloper.swipecard;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends FragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager)findViewById(R.id.view_pager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager());
viewPager.setAdapter(swipeAdapter);
}
}
PageFragment.java
package socialdeveloper.swipecard;
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.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class PageFragment extends android.support.v4.app.Fragment {
TextView textView;
public PageFragment() {
// 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.page_fragment_layout,container,false);
textView = (TextView)view.findViewById(R.id.TestText);
Bundle bundle = getArguments();
String message = Integer.toString(bundle.getInt("count"));
textView.setText("This is the "+message+ "Swipe View Page...");
return view;
}
}
SwipeAdapter.java
package socialdeveloper.swipecard;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by Hadleigh on 07/12/2015.
*/
public class SwipeAdapter extends FragmentStatePagerAdapter {
public SwipeAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle bundle = new Bundle();
int i = 0;
bundle.putInt("count",i+1);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
in your SwipeAdapter.java use this
` public Fragment getItem(int position) {
Fragment fragment = null;//Creates a fragment variable to hold the fragment class i create and make it a null so i can catch the error
if (position == 0) {
fragment = new PUT_THE_TITLE_OF_YOUR_ACTIVITY_YOU_WANT_TO_USE();//Calls the fragment.
}
if (position == 1) {
fragment = new CALL_A_DIFFERENT_FRAGMENT_OR_ACTIVITY();//Calls the fragment;
}
if (position == 2) {
fragment = new CALL_A_DIFFERENT_FRAGMENT_OR_ACTIVITY();//Calls the fragment.
}
return fragment;
}`
in the getItem() method to call other fragments or activities.
I created simple application in android studio. Im using NavigationDrawerFragment.. Im insert date picker coding but i got an error in getSupportFragmentManager() method
Here my full Main Activity code:
package com.example.clive.mydatepickerapp;
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.support.v4.app.DialogFragment;
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.support.v4.app.FragmentActivity;
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_my);
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));
}
public void doDatePicker(View view) {
DialogFragment myDatePickerFragment = new MyDatePickerFragment();
myDatePickerFragment.show(getSupportFragmentManager(), "datePicker");
}
#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);
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();
//noinspection SimplifiableIfStatement
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));
}
}
}
Please anyone help!!
instead of Activity:
public class MainActivity extends Activity
extend FragmentActivity:
public class MainActivity extends FragmentActivity
and make sure that you are importing SupportLibrary:
import android.support.v4.app.Fragment;
in order to use getSupportFragmentManager()
I was having the same problem. Then I replaced getSupportFragmentManager() with getFragmentManager(), and it worked!
I was using these 2 imports:
import android.support.v4.app.Fragment;
import android.app.FragmentTransaction;
And my MainActivity extended the Activity class.
Had these issues many times . What worked for me was :
Simply extend the Main class with AppCompatActivity than the usual ACTIVITY
In short :
replace Acivity with AppCompatActivity
Instead of
public class MainActivity extends Activity
do
public class MainActivity extends AppCompatActivity it supports fragment manager
This will work only if you are using support fragment class i.e. you have to
import android.support.v4.app.Fragment;
Can someone help me how to handle button clicks on fragments? I'm having an error when I go to my fragment in profile. When I click the button on fragment_profile, I always get an error.
Here's my code:
For my Main Activity Class:
package com.the.healthescort;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentTransaction;
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.util.Log;
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.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends ActionBarActivity
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;
Context CTX = this;
public int see;
public String cc="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Mod();
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));
//
}
public void Mod(){
DatabaseOperation DOp = new DatabaseOperation(CTX);
Cursor cr = DOp.getInformation(DOp);
if (cr != null && cr.getCount()>0){
cr.moveToFirst();
startManagingCursor(cr);
for(int i=0;i<cr.getCount();i++){
String x = cr.getString(3);
String y = cr.getString(4);
String c = x.replace("\"", "");
String r = c.replace("' ", ".");
double get = Double.parseDouble(r);
int z = (int) get;
double w = get % z;
double roundOff = Math.round(w*10);
int ans = (z*12)+ (int)roundOff;
String g = y.replace(" lbs","");
double h = Double.parseDouble(g);
double total = (h/(ans*ans))*703;
}
}else{
Intent k = new Intent(MainActivity.this, Add_Profile.class);
startActivity(k);
finish();
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); // For AppCompat use getSupportFragmentManager
switch(position) {
case 0:
mTitle = getString(R.string.title_section1);
tx.replace(R.id.container,PlaceholderFragment.newInstance(position + 1));
tx.commit();
break;
case 1:
mTitle = getString(R.string.title_section2);
tx.replace(R.id.container,new profile_fragment());
tx.commit();
break;
case 2:
fragment = PlaceholderFragment.newInstance(position + 1);
break;
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
break;
case 2:
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();
//noinspection SimplifiableIfStatement
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";
public int check;
/**
* 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));
}
}
}
My Fragment code:
package com.the.healthescort;
import android.content.Context;
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;
public class profile_fragment extends Fragment {
public static Fragment newInstance(Context context) {
profile_fragment f = new profile_fragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View root = (View) inflater.inflate(R.layout.fragment_profile_fragment, container, false);
Button a = (Button) root.findViewById(R.id.sana);
a.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
TextView b = (TextView) view.findViewById(R.id.gumana);
b.setText("Click!");
}
});
return root;
}
}
public void onClick(View view){
TextView b = (TextView) view.findViewById(R.id.gumana);
b.setText("Click!");
}
in this case, view is the object on which you called setOnClickListener, the button you called a. If you call view.findViewById(R.id.yourid), on a View's subclass, what the system does is to check if the id you passed as parameter is equal to the one of the view on which you are calling findViewById. It the view is subclass of ViewGroup's, then the system looks for the provided id among the ViewGroup's children. In your case the view's id is R.id.sana, and you are passing R.id.gumana as parameter. Since the ids don't match the system returns null. You probably have declared the TextView, inside fragment_profile_fragment.xml.
Change
TextView b = (TextView) view.findViewById(R.id.gumana);
with
TextView b = (TextView) getView().findViewById(R.id.gumana);
I am trying to convert all my code from activities to fragments in order to use a navigation drawer and eventualy some sliding tabs.
Currently I have a semi working navigation drawer that opens and displays a list. BUt I am new to fragments and am confused because it seems to reload my first fragment everytime I close the navigation drawer and do not select anything.
MainDrawer.java :
package com.beerportfolio.beerportfoliopro;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by Mike on 1/3/14.
*/
public class MainDraw extends FragmentActivity {
final String[] data ={"Statistics","two","three"};
final String[] fragments ={
"com.beerportfolio.beerportfoliopro.StatisticsPage",
"com.beerportfolio.beerportfoliopro.FragmentTwo",
"com.beerportfolio.beerportfoliopro.FragmentThree"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//todo: load statistics fragment
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main, Fragment.instantiate(MainDraw.this, fragments[pos]));
tx.commit();
}
});
drawer.closeDrawer(navList);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main,Fragment.instantiate(MainDraw.this, fragments[0]));
tx.commit();
}
}
StatisticsPage.java :
package com.beerportfolio.beerportfoliopro;
import android.app.ActionBar;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by Mike on 1/3/14.
*/
public class StatisticsPage extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String url = "http://www.beerportfolio.com/app_getStatistics.php?";
String userURLComp = "u=" + userID;
url = url + userURLComp ;
Log.d("basicStats", url);
new getBasicStats(getActivity()).execute(url);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.statistics_pagelayout, container, false);
}
}
The issue is that your DrawerListener is set in your OnClickListener when it shouldn't be:
#Override public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener(
new DrawerLayout.SimpleDrawerListener(){
#Override public void onDrawerClosed(View drawerView){...}
}
);
}
The scope of your pos integer is such that, every time the drawer closes, onDrawerClose thinks that the value of pos hasn't changed. Since there isn't a condition checking that an item was clicked, then the same Fragment is recreated each time the drawer closes (unless you click on a different item).
Set a member boolean to true when an item is clicked and set a member int to its position. Use the boolean to differentiate between an item click and a drawer close:
private boolean mNavItemClicked = false;
private int mNavPosition = 0;
...
#Override protected void onCreate(Bundle savedInstanceState) {
...
navList.setOnItemClickListener(new ListView.OnItemClickListener {
#Override public void onItemClick(AdapterView parent, View view, int position, long id) {
mNavItemClicked = true;
mNavPosition = position;
drawerLayout.closeDrawer(navList);
}
});
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(...) {
public void onDrawerClosed(View view) {
if (mNavItemClicked) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, Fragment.instantiate(MainDraw.this
, fragments[mNavPosition])
.commit();
}
mNavItemClicked = false;
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
If you decide to use the ActionBarDrawerToggle then follow its design guidelines and call through to the Activity callback methods onConfigurationChanged and onOptionsItemSelected.