How can i load data on specific tab in android? - java

My task is to load data on 50th screen out of 100 screens in one tab activity and also to increment date on forward swipe and decrement date on backward swipe.
I wrote code to increment date and made 50th screen as my current screen but i don't know how to load that current date in 50th screen and to decrement date on backward swipe.
Here is my main activity:
public class MainActivity extends AppCompatActivity {
public static Tab2 self;
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(50);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
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 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 PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new 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_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;
}
}
/**
* 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 int getCount() {
return 100;
}
#Override
public Fragment getItem(int position) {
//TabHost tabHost = Tab2.self.getTabHost();
//tabHost.setCurrentTab(0);
return Tab2.newInstance(position);
}
#Override
public CharSequence getPageTitle(int position) {
return "SECTION 3";
}
}
}
and my tab activity is
public class Tab2 extends Fragment {
private int position;
public Tab2() {
}
public static Tab2 newInstance(int position) {
Tab2 fragment = new Tab2();
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
position = getArguments().getInt("position");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab2, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.add(Calendar.DAY_OF_MONTH, position);
String dte = sdf.format(c.getTime()).toString();
TextView textView2 = getView().findViewById(R.id.textView2);
textView2.setText(dte);
}
}

If you want one tab to have specific data, you need to handle that case in the adapter
#Override
public Fragment getItem(int position) {
Fragment f = Tab2.newInstance(position);
if (position == specificPosition) {
Bundle args = new Bundle();
// put into args...
f.setArguments(args);
}
return f;
}
Regarding swipe direction, I think you need to attach the listener on the ViewPager.

This should work.
In your fragment:
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, position);
String dte = sdf.format(c.getTime()).toString();
TextView textView2 = getView().findViewById(R.id.textView2);
textView2.setText(dte);
}
Hope it helps

Related

Android: ViewPager displays only first fragment, other pages blank

I have a ViewPager that displays a series of FoodItem as Fragments. That part works just fine.
Now, I want to have a function such that if a user clicks on a button, they can view more information about that FoodItem.
For that, I want to replace the clicked Fragment with another Fragment. I modified this code here to suit my purpose. It works -- when I click the button, it replaces that certain Fragment. But it only displays and works for one Fragment. Other fragments are blank entirely.
Here's my adapter and fragments:
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
private ArrayList<FoodItem> items;
public SectionsPagerAdapter(FragmentManager fm, ArrayList<FoodItem> items) {
super(fm);
this.items = items;
}
#Override
public Fragment getItem(int position) {
System.out.println("PRINT: POS " + position);
RootFragment f = new RootFragment();
return f.newInstance(position);
}
#Override
public int getCount() {
return items.size();
}
public class PlaceholderFragment extends Fragment{
private final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
System.out.println("PRINT: INSTANCE" + sectionNumber);
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 view = inflater.inflate(R.layout.fragment_card_layout, container, false);
singleItem = items.get(getArguments().getInt(ARG_SECTION_NUMBER));
// populate views here
//Below is the button for replacing the Fragment with another Fragment.
Button testMore = (Button) view.findViewById(R.id.testMore);
testMore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentTransaction trans = getFragmentManager()
.beginTransaction();
trans.replace(R.id.root_frame, new MoreInfoFragment().newInstance(getArguments().
getInt(ARG_SECTION_NUMBER)));
trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
trans.addToBackStack(null);
trans.commit();
}
});
return view;
}
}
public class MoreInfoFragment extends Fragment {
private final String ARG_SECTION_NUMBER = "section_number";
public MoreInfoFragment newInstance(int sectionNumber) {
MoreInfoFragment fragment = new MoreInfoFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public MoreInfoFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.more_info_layout, container, false);
singleItem = items.get(getArguments().getInt(ARG_SECTION_NUMBER));
//populate views here
return view;
}
}
public class RootFragment extends Fragment {
private static final String TAG = "RootFragment";
private final String ARG_SECTION_NUMBER = "section_number";
public RootFragment newInstance(int sectionNumber) {
RootFragment fragment = new RootFragment();
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 view = inflater.inflate(R.layout.root_fragment, container, false);
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.replace(R.id.root_frame, new PlaceholderFragment().newInstance(getArguments().
getInt(ARG_SECTION_NUMBER)));
System.out.println("PRINT: ROOT" + getArguments().getInt(ARG_SECTION_NUMBER));
transaction.commit();
return view;
}
}
}
Here's my Main Activity:
private ViewPager mViewPager;
private static ArrayList<FoodItem> sample;
private PagerContainer mContainer;
public CardLayout(){
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
setContentView(R.layout.activity_card_layout);
//Sample array
sample = new ArrayList<>();
sample.add(new FoodItem("French Fries", "Super delicious and crispy!"))
sample.add(new FoodItem("Burger", "Made with real Krabby Patty"))
sample.add(new FoodItem("Pickles", "So green")) // This is the only one that displays
//PagerContainer is a FrameLayout that has a ViewPager as a child.
//I want my ViewPager to display edges of the previous and next part so
//PagerContainer is used for that purpose.
mContainer = (PagerContainer) findViewById(R.id.pager_container);
mViewPager = (ViewPager) findViewById(R.id.viewPager);
// This is to adjust the viewpager according to size of screen
mContainer.getViewTreeObserver().
addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
height = mContainer.getHeight();
double heightSize = height * 0.8;
height = (int) heightSize;
double widthSize = height*0.6;
width = (int) widthSize;
mViewPager.setLayoutParams(new FrameLayout.LayoutParams(width, height, Gravity.CENTER));
mViewPager.setPageMargin(width /30);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN)
mContainer.getViewTreeObserver().removeOnGlobalLayoutListener(this);
else
mContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
});
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), sample);
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setOffscreenPageLimit(mSectionsPagerAdapter.getCount());
mViewPager.setClipChildren(false);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
Oh, the Fragment that's displaying is not even the first one in my ArrayList! It's the last.
I feel like I'm missing something obvious but I've looked through this code about 10 times and I still couldn't find what could have prevented the other pages from displaying.
For example, this is how the first page looks like:
If I slide to the second page, it's totally white (my background color for root_fragment)
And that goes for every fragments after.
Do you guys have any ideas/suggestions?
Override the method getItem() in your SelectionsPageAdapter
#Override
public Fragment getItem(int position) {
// if the position is 0 we are returning the First tab
if (position == 0)
{
Fragment tab1 = new PlaceholderFragment ();
return tab1;
} else if (position == 1)
{
Fragment tab2 = new MoreInfoFragment ();
return tab2;
} else if (position == 2) {
Fragment tab3 = new RootFragment ();
return tab3;
}
}

Navigate back to a background activity Android

I have 3 activities:
1. The list of categories;
2. The news in this category;
3. Details about News
see the images below!
I implemented back button from the third activity to the second by setting the second activity as the parent activity for the third activity in the android manifest file, but it can not see the category that is chosen in the first activity so it doesn't display the list and crash, can anybody help me implementing back button?
here is the code of activity where i want to implement the back button
public class Categorii_LIst_Item_Clicked extends ActionBarActivity {
static Context context;
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_categorii__list__item__clicked);
context = this;
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#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_categorii__list__item__clicked, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
if (position == 0) {
return PlaceholderFragment.newInstance(position);
} else if (position == 1) {
return VideoFragment.newInstance1(position);
}
return PlaceholderFragment.newInstance(position);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "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_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText(extras.getString("pdate"));
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText(extras.getString("pText"));
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener() {
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
// i/ndicator.setVisibility(View.INVISIBLE);
// iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
imageLoader.displayImage(extras.getString("pImage"), iconImg, options, listener);
return rootView;
}
}
public static class VideoFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public static VideoFragment newInstance1(int sectionNumber) {
VideoFragment fragment = new VideoFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public VideoFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.video_fragment, container, false);
VideoView myVideoView = (VideoView) rootView.findViewById(R.id.videoView);
Uri video = Uri.parse(extras.getString("pVideo"));
myVideoView.setMediaController(new MediaController(context));
myVideoView.setVideoURI(video);
myVideoView.requestFocus();
//myVideoView.start();
return rootView;
}
}
}
When you specify parent activity in manifest for Up Navigation like this:
android:parentActivityName
and when you click on Up button in action bar, the parent activity gets restarted (in your case it is category activity), instead to avoid activity get restarted. just finish the top activity by putting this code in your 3rd activity (i.e Details about News).
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
and remove the parentActivityName from manifest.

add a parsed list item to another list

i am working on a xml parsing app- news app.
I've parsed the xml file and transformed it to the listView, and when i click the news i see more detailed info about it. I'd like to implement the "add to favorites" button so that it appears in a list in favorites tab (i've implemented the favorites tab in the tabhost in main activity), can anybody help me to do this? (I don't know how to implement action bar button (add to favorites) and how by clicking it to add it to a listview). Thanks!!!!
here is the code for listItemClicked
package com.example.andrian.jurnaltv;
public class ListItemClicked extends ActionBarActivity {
static Bundle extras;
SectionsPagerAdapter mSectionsPagerAdapter;
static ImageLoader imageLoader;
static DisplayImageOptions options;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_clicked);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
extras = getIntent().getExtras();
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#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_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return id == R.id.action_settings || super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section4).toUpperCase(l);
case 1:
return getString(R.string.title_section5).toUpperCase(l);
}
return null;
}
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "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_list_item_clicked, container, false);
TextView pDate = (TextView) rootView.findViewById(R.id.textView);
pDate.setText( extras.getString("pdate") );
TextView ptitle = (TextView) rootView.findViewById(R.id.section_label);
ptitle.setText(extras.getString("pname"));
TextView pnText = (TextView) rootView.findViewById(R.id.textView2);
pnText.setText( extras.getString("pText"));
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener(){
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
// i/ndicator.setVisibility(View.INVISIBLE);
// iconImg.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
//Load the image and use our options so caching is handled.
final ImageView iconImg = (ImageView) rootView.findViewById(R.id.imageView);
imageLoader.displayImage( extras.getString("pImage"), iconImg, options, listener);
return rootView;
}
}
}

onItemClickListener in ListView not working

I have a ListView within a ListFragment, and currently I just want a click on any of the items to go to ProblemActivity.class, which is currently a barebones 'HelloWorld' activity. Problem is I don't think the onItemClickListener is firing, and I'm not sure why, as I'm an Android novice. Any ideas?
public class MainActivity extends Activity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* 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).
switch (position) {
case 0:
return MainFragment.newInstance(position);
case 1:
return ProfileFragment.newInstance(position);
case 2:
return ReferenceFragment.newInstance(position);
default:
return MainFragment.newInstance(position);
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}
/**
* The default fragment containing a list view of problems.
*/
public static class MainFragment extends ListFragment {
/**
* 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 MainFragment newInstance(int sectionNumber) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public MainFragment() {
}
static final String[] PROBLEMS = new String[] { "Problem 1", "Problem 2", "Probelm 3",
"Problem 4", "Problem 5", "Problem 6", "Problem 7", "Problem 8",
"Problem 9" };
#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(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));*/
setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.list_probs,PROBLEMS));
ListView listView = (ListView) rootView
.findViewById(android.R.id.list);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Intent intent = new Intent(MainFragment.this.getActivity(), ProblemActivity.class);
startActivity(intent);
}
});
return rootView;
}
}
/**
* The profile fragment. To be completed later.
*/
public static class ProfileFragment 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 ProfileFragment newInstance(int sectionNumber) {
ProfileFragment fragment = new ProfileFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public ProfileFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_profile, container,
false);
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
/**
* The reference fragment. To be completed later.
*/
public static class ReferenceFragment 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 ReferenceFragment newInstance(int sectionNumber) {
ReferenceFragment fragment = new ReferenceFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public ReferenceFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_reference, container,
false);
TextView textView = (TextView) rootView
.findViewById(R.id.section_label);
textView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
}
list_probs.xml:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="20sp" >
</TextView>
Try this..
Change this..
ListView listView = (ListView) rootView.findViewById(android.R.id.list);
to
ListView listView = getListView();
EDIT
Add below code after onCreateView
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.list_probs,PROBLEMS));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Intent intent = new Intent(MainFragment.this.getActivity(), ProblemActivity.class);
startActivity(intent);
}
});
}
Apart for the other answer you directly add ListItem click event like
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(getActivity(), PROBLEMS[(int) id],Toast.LENGTH_SHORT).show();
}
For example go to
DemonstrationofusingListFragmenttoshowalistofitemsfromacannedarray.
android-custom-adapter-listview-with-listfragment-and-loadermanager-inside-fragmentactivity
try this,
Add this property in your adapter layout android:descendantFocusability="blocksDescendants" listener of Listview starts working.

Pass parameters between viewpager fragments

I have an activity that holds 2 fragments, one for list and one for detail. What I would like to do is, whenever a list item is clicked the related parameters will be sent to detail fragment. But I couldn't achieve it.
Here is activity:
public class ActivityMain extends ActionBarActivity{
/**
* 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}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
List<String> naviList = new ArrayList<String>();
ViewPager mViewPager;
private ActionBarDrawerToggle drawerToggle;
private DrawerLayout drawer;
ListView navList;
DrawerAdapter naviAdapter;
private static final int GRAVITY = Gravity.LEFT;
private static final String jsonURL = "";
List<String> categories = new ArrayList<String>();
int check = -1, listCheck = 0;
Dialog d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//some methods (e.g. navi-drawer etc.)
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.medicalendar_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.
switch (item.getItemId()) {
case R.id.action_settings:
return true;
}
if (drawerToggle.onOptionsItemSelected(item)) {
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) {
switch (position) {
case 0:
return ListFragment.newInstance("FirstFragment, Default");
case 1:
return DetailFragment.newInstance("DetailFragment, Detail");
default:
return ListFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
private boolean version() {
if (Build.VERSION.SDK_INT > 11) {
return true;
} else {
return false;
}
}
My List Fragment:
public class ListFragment extends Fragment {
ListView list;
LazyAdapter adapter;
List<String> naviList = new ArrayList<String>();
RelativeLayout loading;
EventsParser parser;
List<Event> events = new ArrayList<Event>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.fragment_list, container, false);
parser = new EventsParser("");
events = parser.getITEMS();
list = (ListView) v.findViewById(R.id.list);
adapter = new LazyAdapter(getActivity(), events);
list.setAdapter(adapter);
return v;
}
public static ListFragment newInstance(String text) {
ListFragment f = new ListFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ViewPager vp = (ViewPager) getActivity().findViewById(R.id.pager);
//clicked item's data to pass next page.
vp.setCurrentItem(1);
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
My Detail Fragment:
public class DetailFragment extends Fragment {
View v;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_detail, container, false);
ImageButton imageButton = (ImageButton) v.findViewById(R.id.d_map);
imageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity().getApplicationContext(), "Navigating...", Toast.LENGTH_LONG).show();
}
});
return v;
}
public static DetailFragment newInstance(String text) {
DetailFragment f = new DetailFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
}
If you could help me I would be greatly appriciated.
Best,
Basically you don't need ViewPager for navigating from one fragment to another. This should be achieved with replacing fragments using FragmentTransaction class, that will allow you to pass parameters in transaction. http://developer.android.com/reference/android/app/FragmentTransaction.html
If you still need ViewPager, you should set tag for each fragment with
fragment.setTag("detail_fragment");
and than your onListItemClick method should look like this:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//get detail fragment instance by it's tag
DetailFragment detail = (DetailFragment) getActivity().getFragmentManager().findFragmentByTag("detail_fragment");
detail.setParam("data"); //you should define this method in your detail fragment
ViewPager vp = (ViewPager) getActivity().findViewById(R.id.pager);
//clicked item's data to pass next page.
vp.setCurrentItem(1);
}

Categories