How to write button click event in ViewPager - android

Here my activity_main.xml present in /res/layout
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
Here is my MainActivity.java file
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
public class MainActivity extends FragmentActivity {
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);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* 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 DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "POS 0"; // getString(R.string.title_section1).toUpperCase();
case 1:
return "POS 1";// getString(R.string.title_section2).toUpperCase();
case 2:
return "POS 2";// getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view;
String i = Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER));
if (i.toString() == Integer.toString(1)) {
view = inflater.inflate(R.layout.section2, container, false);
} else {
view = inflater.inflate(R.layout.section1, container, false);
// Button button = (Button) view.findViewById(R.id.button1);
// button.setOnClickListener(new OnClickListener() {
// if i uncomment this code, button click works but i want it to handle in section1.java file
// #Override
// public void onClick(View v) {
// Activity activity = getActivity();
//
// if (activity != null) {
// Toast.makeText(activity, "sdfsdfsdfds",
// Toast.LENGTH_LONG).show();
// }
// }
//
// });
}
return view;
}
}
}
I have an activity named "Section1" which is displayed when i swipe to right side. It has a button on it.
How do i handle the button click event in section1.java file ?
here is my section.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Section1" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="sendMessage"
android:text="Button" />
</RelativeLayout>
Here is the Section1.Java file. Here button click even it not fired.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class Section1 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.section1);
}
public void sendMessage(View view) {
Toast t = Toast.makeText(getApplicationContext(), "sdfsdfsdf",
Toast.LENGTH_LONG);
t.show();
}
}

I was having the same issue as you and I finally figured it out today so I thought I would share it with you
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 2:
// The first section of the app is the most interesting -- it offers
// a launchpad into the other demonstrations in this example application.
return new LessonFragment();
default:
// The other sections of the app are dummy placeholders.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, i + 1);
fragment.setArguments(args);
return fragment;
}
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0: return getString(R.string.title_section1).toUpperCase();
case 1: return getString(R.string.title_section2).toUpperCase();
case 2: return getString(R.string.title_section3).toUpperCase();
case 3: return getString(R.string.title_section4).toUpperCase();
}
return null;
}
}
/**
* A fragment that launches other parts of the demo application.
*/
public static class LessonFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.lesson, container, false);
// Demonstration of a collection-browsing activity.
rootView.findViewById(R.id.button1)
.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent intent = new Intent(getActivity(), Test.class);
startActivity(intent);
}
});
return rootView;
}
}

#Override
public Fragment getItem(int position) {
switch(position){
case 0 :
case 1 :
// and so on.
}
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}

Related

Unable to interact with views in fragment activity

Hi I am given an assignment to create contents in the fragment basic layout. However having create a swipe activity with tab action bar, i am unable to edit the fragment layout within each given tab. Here is the codes as follow :
MainActivity.java : method i use to refer to the fragment layout
(created a default swipe activity with action tab)
package com.example.clement.testingfragments;
public class MainActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
// action bar
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();
}
});
//manage the fractions
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, new BlankFragment());
fragmentTransaction.commit();
}
#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);
}
public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
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) {
if(getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
return rootView;
}else {
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;
}
}
}
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 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
}
}
I then created the BlankFragment.java :
(Default creation of a fragment basic layout)
public class BlankFragment extends Fragment {
TextView mtv;
public BlankFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.i("hello","hello");
View viewRoot = inflater.inflate(R.layout.fragment_blank, container, false);
mtv = (TextView)viewRoot.findViewById(R.id.testy);
mtv.setText("hello");
return viewRoot;
}
}
The problem with this is that i am a unable to change textview that is inside of the fragment_blank.xml. i have research all across the internet and the suggestions given were to create void methods, using getActivity(), onViewCreated(), Onstart(). All of these have seem to not work.
i have included a if else loop to return a null under the condition that the method works, but it still runs without returning a null and i have no clue as to why this is happening.
My fragment_blank.xml:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.clement.testingfragments.BlankFragment">
<TextView
android:id="#+id/testy"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="#string/hello_blank_fragment" />
</FrameLayout>
Do let me know if more information is needed. I sincerely seek your suggestions and advice. Thanks in advance!
As per your question your textview is inside basicfragmentlayout.xml, while you are inflating fragment_blank inside your onCreateView. You need to change your code as below:
MyActivity.java
public class MyActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction =
fragmentManager.beginTransaction();
fragmentTransaction.replace(android.R.id.content, new MyFragment());
fragmentTransaction.commit();
}
}
MyFragment.java
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;
public class MyFragment extends Fragment {
View myView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_my, container, false);
TextView mtv = (TextView) myView.findViewById(R.id.testy);
mtv.setText("hello");
return myView;
}
}
fragment_my.java
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/testy"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="TempText" />
</FrameLayout>

Switch fragment within designated space

I have a layout, MainScreen.java which has following design.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include layout="#layout/toolbar"
/>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:id="#+id/tab_and_view" />
</LinearLayout>
toolbar will be the title of the app. tab_and_view will consist of a tabview and framelayout
Here's the layout file of tab_and_view.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.android.luftschlafer.engdictionary.Tab.SlidingTabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorAccent"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" />
</LinearLayout>
I have made some tabs: Home,Search, Settings and About app. All of them will display their content in the ViewPager.
In Home page, there is only a ListView item.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Corr_Pages.HomePage">
<!-- TODO: Update blank fragment layout -->
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/home_function_list"/>
</RelativeLayout>
And codes of HomePage.java:
public class HomePage extends BaseFragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "Home";
private static final String ind_color="IndicatorColor";
private static final String div_color="DividerColor";
// TODO: Rename and change types of parameters
private String mParam1;
private int mParam2,mParam3;
private OnFragmentInteractionListener mListener;
public HomePage() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param tab_name Parameter 1.
* #return A new instance of fragment HomePage.
*/
// TODO: Rename and change types and number of parameters
public static HomePage newInstance(String tab_name, int indicatorColor,int
dividerColor,int iconResId) {
HomePage fragment = new HomePage();
fragment.setTitle(tab_name);
fragment.setIndicatorColor(indicatorColor);
fragment.setDividerColor(dividerColor);
fragment.setIconResId(iconResId);
//Pass out data
Bundle args = new Bundle();
args.putString(ARG_PARAM1, tab_name);
args.putInt(ind_color,indicatorColor);
args.putInt(div_color,dividerColor);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2=getArguments().getInt(ind_color);
mParam3=getArguments().getInt(div_color);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_home_page, container, false);
}
//This method will be done by
#Override
public void onViewCreated(View v, final Bundle savedInstanceState){
//Initialize all visual elements here
final LayoutInflater inflater= LayoutInflater.from(getContext());//Test
ListView lv=(ListView) v.findViewById(R.id.home_function_list);
//Initialize the list items and their corresponding adapter
String[] SampleSelections=new String[] {"New things","Most common words","Recommendation from Wilson"};
ArrayAdapter<String> adapter= new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, SampleSelections);
lv.setAdapter(adapter);
//Declare the events
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position){
//Toasts will be replaced by appropriate methods soon
case 0:
Toast.makeText(getContext(),"New Contents are coming",Toast.LENGTH_SHORT).show();
declare_new_content_page();
break;
case 1:
Toast.makeText(getContext(),"There are some most common words",Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(getContext(),"Wilson's recommendation",Toast.LENGTH_SHORT).show();
break;
default:
//Nothing is selected
break;
}
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p/>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
//Handles the operation of new content page.
private void declare_new_content_page(){
//Declare widgets here
FragmentManager fm=getFragmentManager();
FragmentTransaction ftran=fm.beginTransaction();
ftran.replace(R.id.tab_and_view,NewContent.newInstance("NewContent"));
ftran.commit();
}
}
In the ListView of MainScreen.java, it has three choices: What's new, most common words and recommendation. Now if I press What's new, a new fragment should be displayed in the ViewPager with a name NewContent.java. I tried to do this by using following codes:
FragmentManager fm=getFragmentManager();
FragmentTransaction ftran=fm.beginTransaction();
ftran.replace(R.id.tab_and_view,NewContent.newInstance("NewContent"));
ftran.commit();
However, after the transaction is completed, the new fragment does not remain in viewPager anymore, it also used the spaces for tabview too.
Therefore I want to know how to switch fragment within this designated ViewPager space.
In the new fragment, NewContent.java, it also has a button for users to go back to home page. I would also like to ask how to finish this operation?
I'm new to stackoverflow, so I hope you know what problem i'm facing.... Thank you.
Another fragment file, TabFragment.java, i used it to build the tabs.
package com.android.luftschlafer.engdictionary;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.android.luftschlafer.engdictionary.Corr_Pages.AboutPage;
import com.android.luftschlafer.engdictionary.Corr_Pages.SearchPage;
import com.android.luftschlafer.engdictionary.Corr_Pages.SettingPage;
import com.android.luftschlafer.engdictionary.Tab.BaseFragment;
import com.android.luftschlafer.engdictionary.Tab.SlidingTabLayout;
import com.android.luftschlafer.engdictionary.Corr_Pages.HomePage;
import java.util.LinkedList;
/**
* Created by LuftSchlafer on 6/17/2016.
*/
//Configurations of all fragments
public class TabFragment extends Fragment {
private SlidingTabLayout tabs;
private ViewPager pager;
private FragmentPagerAdapter adapter;
public static Fragment newInstance(){
TabFragment f = new TabFragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.tab_and_view, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//adapter
final LinkedList<BaseFragment> fragments = getFragments();
adapter = new TabFragmentPagerAdapter(getFragmentManager(), fragments);
//pager
pager = (ViewPager) view.findViewById(R.id.pager);
pager.setAdapter(adapter);
//tabs
tabs = (SlidingTabLayout) view.findViewById(R.id.tabs);
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return fragments.get(position).getIndicatorColor();
}
#Override
public int getDividerColor(int position) {
return fragments.get(position).getDividerColor();
}
});
tabs.setBackgroundResource(R.color.colorAccent);
tabs.setCustomTabView(R.layout.tab_title, R.id.txtTabTitle,
R.id.imgTabIcon);//REMEMBER THE SEQUENCE!
tabs.setViewPager(pager);
}
//Produce the fragments and corresponding tabs.
private LinkedList<BaseFragment> getFragments(){
int indicatorColor = Color.parseColor("RED");
int dividerColor = Color.TRANSPARENT;
LinkedList<BaseFragment> fragments = new LinkedList<>();
//Add fragments here
fragments.add(HomePage.newInstance("Home", indicatorColor,
dividerColor,R.drawable.ic_home_black_24dp));
fragments.add(SearchPage.newInstance("Search", indicatorColor,
dividerColor,R.drawable.ic_book_black_24dp));
fragments.add(SettingPage.newInstance("Settings", indicatorColor,
dividerColor,R.drawable.ic_build_black_24dp));
fragments.add(AboutPage.newInstance("About
app",indicatorColor,dividerColor,R.drawable.ic_info_outline_black_24dp));
return fragments;
}
}

Viewpager cannot change imageView background programmatically

I am trying to initialize a ViewPager. I've failed to set image of programmatically to the viewpager. This is what I've come up with:
TutorialActivity.class
package app.trial.com;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
public class TutorialActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 3;
/**
* 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);
setContentView(R.layout.activity_tutorial);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TutorialFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
TutorialFragment.class
package app.trial.com;
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.ImageView;
public class TutorialFragment extends Fragment {
public static final String ARG_PAGE = "page";
private int mPageNumber;
public static TutorialFragment create(int pageNumber) {
TutorialFragment fragment = new TutorialFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public TutorialFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mPageNumber = getArguments().getInt(ARG_PAGE);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_tutorial, container, false);
switch(mPageNumber) {
case 1:
((ImageView) rootView.findViewById(R.id.tutorialImage)).setImageResource(R.drawable.tutorial_03);
break;
case 2:
((ImageView) rootView.findViewById(R.id.tutorialImage)).setImageResource(R.drawable.tutorial_02);
break;
case 3:
((ImageView) rootView.findViewById(R.id.tutorialImage)).setImageResource(R.drawable.tutorial_03);
break;
default:
break;
}
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
}
When I try to change R.id.tutorialImage using rootView.findViewById(R.id.tutorialImage).setImageResource() it doesn't change the background image. Also, it doesn't return null.
By the way my fragmentTutorial layout is:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context="app.trial.com.TutorialFragment">
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tutorialImage" />
</ScrollView>
</FrameLayout>

Error inflating class fragment in activity layout

I have the layout for the activity:
<fragment
android:name="com.myapp.fragment1"
android:id="#+id/fragment1"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment1" />
<fragment
android:name="com.myapp.listfragment1"
android:id="#+id/fragment2"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</RelativeLayout>
The first fragment (fragment1) extends Fragment, whilst the second fragment extends ListFragment. I don't have a layout for the listfragment.
The activity code is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
}
An exception is thrown on setContentView:
Error inflating class fragment
The ListFragment code is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new MyListAdapter(getActivity(), prices));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setDivider(null);
}
What is the correct way to have multiple fragments in an activity?
You can do it by using SectionsPagerAdapter (Swipe View) or by NavigationDrawer (Navigation drawer). I have used swipe view for one of my applications. Here is the codes.
MainActivity.java
public class MainActivity extends AppCompatActivity 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 = getSupportActionBar();
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(getSupportFragmentManager());
// 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);
}
});
//Getting icons in icons veriable
final int[] ICONS = new int[]{
R.drawable.chat,
R.drawable.friends,
R.drawable.profile,
};
// 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()
.setIcon(getResources().getDrawable(ICONS[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.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_search:
// search action
return true;
default:
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 index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new ChatFragment();
case 1:
return new FriendsFragment();
// Games fragment activity
//return new ProfileFragment();
case 2:
// Movies fragment activity
//return new FriendsFragment();
return new ProfileFragment();
}
return null;
}
#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.chat_tab).toUpperCase(l);
case 1:
return getString(R.string.friends_tab).toUpperCase(l);
case 2:
return getString(R.string.profile_tab).toUpperCase(l);
}
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);
return rootView;
}
}
}
FriendsFragment.java
public class FriendsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_friends, container, false);
return rootView;
}
}
activity_main.xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/pager"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" />
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment">
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
fragment_friends.xml
<?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">
<TextView
android:id="#+id/email_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="#string/friends_tab"
android:layout_gravity="center"
android:gravity="center"/>
</LinearLayout>
This is just a sample code of my project. You can use your own code for java or xml. Here i tried to show how to call the fragments in your MainActivityusing swipe view. Hope it helps.

Android : Fragment code causes crash of the application

This is my Menu java code that include fragments in a swipe view interface where i had separate activity for each fragment. I encounter a application class by calling this activity and i wish that someone could help me to solve my problem as i'm a beginner in android programming. Your help is very appreciated.
package com.example.lazynumber;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
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.widget.Button;
import android.widget.TextView;
public class MainMenu extends FragmentActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.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.
*/
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#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;
}
/**
* 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 DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
switch(position){
case 0:
Fragment fragment = new GetNumberFragment();
return fragment;
case 1:
Fragment fragment2 = new QRFragment();
return fragment2;
case 2:
Fragment fragment3 = new ProfileFragment();
return fragment3;
default:
return null;
}
}
#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;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class GetNumberFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public GetNumberFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_get_number_intro,
container, false);
return rootView;
}
}
#SuppressLint("ValidFragment")
public class QRFragment extends Fragment{
public QRFragment(){};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView2 = inflater.inflate(R.layout.qrintro, container, false);
Button testingButton = (Button)findViewById(R.id.goinQRPay);
testingButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goTesting();
}
});
return rootView2;
}
}
private void goTesting(){
Intent goTesting = new Intent(this, Testingbutton.class);
startActivity(goTesting);
}
public static class ProfileFragment extends Fragment{
public ProfileFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView3 = inflater.inflate(R.layout.activity_profile_setting, container, false);
return rootView3;
}
}
}
These are my xml codes for reference if needed.
first one is the mainmenu xml
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainMenu" >
<!--
This title strip will display the currently visible page title, as well as the page
titles for adjacent pages.
-->
<android.support.v4.view.PagerTitleStrip
android:id="#+id/pager_title_strip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#33b5e5"
android:paddingBottom="4dp"
android:paddingTop="4dp"
android:textColor="#fff" />
</android.support.v4.view.ViewPager>
And this next xml is the one that i needed to have a function which is QRFragment activity xml interface.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".QRIntro" >
<ImageView
android:id="#+id/qrintropic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/qrlazy" />
<Button
android:id="#+id/goinQRPay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/qrintropic"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:text="#string/buttontoqr" />"
</RelativeLayout>
The fragments need to be inserted into some kind of container layout like a FrameLayout. if you add that then you can use this method to replace the fragment
public static void replaceFragment(Activity activity, int containerlayoutId, Fragment newFragment) {
FragmentTransaction transaction = activity.getFragmentManager().beginTransaction().replace(containerlayoutId, newFragment);
transaction.commit();
activity.getFragmentManager().executePendingTransactions();
}

Categories

Resources