i've used the existing model of Tab menu (the action bar) , and now i'm having problem adding submenu to each tab , how can i do that ?
this is my code :
#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 app.
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);
}
});
// 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.
Tab tab = actionBar.newTab();
tab.setText(mSectionsPagerAdapter.getPageTitle(i));
tab.setTabListener(this);
actionBar.addTab(tab);
}
}
this is menu/main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:showAsAction="never"
android:title="#string/action_settings">
</item>
</menu>
here is the rest of code :
#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 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 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 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 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 rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
i'm waiting your answers , thanks
Assuming all your tabs having their own class extending fragments, you simply include:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.yourmenu, menu);
this.menu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
}
Edit: I just saw you are looking for a sub menu. Try this tutorial: http://www.mysamplecode.com/2011/07/android-options-menu-submenu-group.html
and take a look at "Options Menu Layout optionmenu.xml"
You will need to use fragments for each Tab.
Your MainActivity- Class:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//instantiate Fragments / Tabs
Fragment tabonefragment = new TabOneFragment();
Fragment tabtwofragment = new TabTwoFragment();
PagerAdapter mPagerAdapter = new PagerAdapter(getSupportFragmentManager());
mPagerAdapter.addFragment(tabonefragment);
mPagerAdapter.addFragment(tabtwofragment);
// 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);
}
});
//adding tabs to your action bar
ActionBar ab = getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab1 = ab.newTab().setText("tabonetext")
.setTabListener(new TabListener<TabOneFragment>(
this, "tab_one", TabOneFragment.class));
Tab tab2 = ab.newTab().setText("tabtwotext")
.setTabListener(new TabListener<TabTwoFragment>(
this, "tab_two", TabTwoFragment.class));
ab.addTab(tab1);
ab.addTab(tab2);
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/** Constructor used each time a new tab is created.
* #param activity The host Activity, used to instantiate the fragment
* #param tag The identifier tag for the fragment
* #param clz The fragment's Class, used to instantiate the fragment
*/
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
public void onTabReselected(Tab arg0,
android.app.FragmentTransaction arg1)
{
}
public void onTabSelected(Tab arg0, android.app.FragmentTransaction arg1)
{
mViewPager.setCurrentItem(arg0.getPosition());
}
public void onTabUnselected(Tab arg0,
android.app.FragmentTransaction arg1)
{
}
}
public class PagerAdapter extends FragmentPagerAdapter {
private final ArrayList<Fragment> mFragments = new ArrayList<Fragment>();
public PagerAdapter(FragmentManager manager) {
super(manager);
}
public void addFragment(Fragment fragment) {
mFragments.add(fragment);
notifyDataSetChanged();
}
#Override
public int getCount() {
return mFragments.size();
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
}
Your Fragment class:
public class TabOneFragment extends Fragment {
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
//inflate your layout from a tab_one_layout.xml file (or use the same xml of your R.layout.activitiy_main if you want)
View view = inflater.inflate(R.layout.tab_one_layout, container, false);
return view;
}
}
//HERE: individual options menu of TabOne
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.yourmenu, menu);
this.menu = menu;
//create some submenu if you want
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
}
That should do. The same/similiar code also for TabTwo ofc.
I think i should edit this code :
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 rootView = inflater.inflate(R.layout.fragment_main_dummy,
container, false);
TextView dummyTextView = (TextView) rootView
.findViewById(R.id.section_label);
dummyTextView.setText(Integer.toString(getArguments().getInt(
ARG_SECTION_NUMBER)));
return rootView;
}
}
and the XML file and replacte textview with a menu ?
<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=".MainActivity$DummySectionFragment" >
<TextView
android:id="#+id/section_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</RelativeLayout>
Related
When switching from one fragment to another fragment (within the second tab of my application), my second fragment is blank. I have tried the solutions linked here, but none seem to work:
Transaction of fragments in android results in blank screen
Android: Getting white screen with fragment transaction
MainActivity:
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_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter, and add pages.
mViewPager = (ViewPager) findViewById(R.id.container);
mSectionsPagerAdapter.addPage(new Received());
mSectionsPagerAdapter.addPage(new Send());
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#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_alert_partners, 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);
}
/**
* 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() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(getArguments().getInt(ARG_SECTION_NUMBER)==1) {
View rootView = inflater.inflate(R.layout.fragment_received, container, false);
return rootView;
}
else if(getArguments().getInt(ARG_SECTION_NUMBER)==2) {
View rootView = inflater.inflate(R.layout.fragment_send, container, false);
return rootView;
}
else {//main empty fragment in case of error. Never used in normal behaviour.
View rootView = inflater.inflate(R.layout.fragment_alert_partners, container, false);
return rootView;
}
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
//Create an Array list that will hold the pages.
ArrayList<Fragment> pages = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
return pages.get(position);
}
//Add a page
public void addPage(Fragment f) {
pages.add(f);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Received";
case 1:
return "Send";
}
return null;
}
}
}
SendFragment:
public class Send extends Fragment {
private OnFragmentInteractionListener mListener;
private TextView text1;
public Send() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_send, container, false);
//Need getView() for fragment since setContentView must be set first but is not possible in fragment.
text1 = (TextView)v.findViewById(R.id.textview1);
text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Send2 send2 = new Send2();
fragmentTransaction.addToBackStack(null);
fragmentTransaction.hide(Send.this);
fragmentTransaction.add(android.R.id.content, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
}
});
return v;
}
public interface OnFragmentInteractionListener {
}
}
Send2Fragment:
public class Send2 extends Fragment {
private OnFragmentInteractionListener mListener;
public Send2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_send2, container, false);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
}
}
Had to add a framelayout at the end of the layout code for the fragment I was replacing:
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/send1frameLayoutId">
</FrameLayout>
Then used this code to switch to a fragment in the same tab of the previous fragment:
Fragment send2 = new Send2();
FragmentManager fragmentManager = getChildFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.send1frameLayoutId, send2);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
I want in the Actionbar button click change my Fragment page textView Text.
I am using Activity and Fragment. in this Activity
How to call public void in Fragment from same Activity? Thank all~
Code
MainActivity.java
public class MainActivity extends ActionBarActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (getSupportActionBar() != null) {
getSupportActionBar().setElevation(0);
}
MaterialTabHost tabHost = (MaterialTabHost) findViewById(android.R.id.tabhost);
tabHost.setType(MaterialTabHost.Type.FullScreenWidth);
tabHost.addTab("one page");
tabHost.addTab("two page");
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOnPageChangeListener(tabHost);
tabHost.setOnTabChangeListener(new MaterialTabHost.OnTabChangeListener() {
#Override
public void onTabSelected(int position) {
viewPager.setCurrentItem(position);
}
});
}
#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 super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.name:
//in here call public void setItem, set the textView Text.
break;
}
return super.onOptionsItemSelected(item);
}
public static class PlaceholderFragment extends Fragment{
private static final String ARG_SECTION_NUMBER = "section_number";
TextView textView;
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.ge_layout, container, false);
textView = (TextView) rootView.findViewById(R.id.textView);
return rootView;
}
public void setItem() {
textView.setText("Test");
}
}
}
You need to have reference to that fragment, which you can obtain through FragmentManager:
If you add your fragment to the layout in xml file using the <fragment> tag, define its id:
<fragment android:id="#+id/placeholder_fragment"
android:name="com.your.package.PlaceholderFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
In your activity:
FragmentManager fm = getSupportFragmentManager();
PlaceholderFragment placeholderFragment = (PlaceholderFragment) fm.findFragmentById(R.id.placeholder_fragment);
placeholderFragment.setItem();
Other way to add fragment is to do it programatically:
private static final String TAG_PLACEHOLDER = "placeholder";
FragmentManager fm = getSupportFragmentManager();
placeholderFragment = (DataLoaderFragment)fm.findFragmentByTag(TAG_PLACEHOLDER);
if (placeholderFragment == null) {
placeholderFragment = PlaceholderFragment.newInstance(sectionNumber);
fm.beginTransaction().add(placeholderFragment, TAG_PLACEHOLDER).commit();
}
// you have the reference to fragment from calling newInstance(sectionNumber) or findFragmentByTag, so you can execute the method:
placeholderFragment.setItem();
I think the best practice should be to create the options menu and its functionality inside the fragment.
But if there is some reason why you set it in the activity, then you could use something like this:
((PlaceholderFragment)getSupportFragmentManager().findFragmentByTag(getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount()-1).getName())).setItem();
Depending on how you added the fragment to the backstack.
I cannot figure out how to get PreferenceFragment to work correctly. I have a ViewPager hooked up to a FragmentPagerAdapter, with two Fragments that the user can swipe between. I am trying to get the "Settings" menu working, using a PreferenceFragment, but I am unsure what I'm doing wrong. When I tap Settings the view is changed to a blank white screen.
My SettingsFragment class:
public class SettingsFragment extends PreferenceFragment{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
My PagerAdapter class:
public class PagerAdapter extends FragmentPagerAdapter {
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public PagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Object instantiateItem(ViewGroup container, int position){
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
#Override
public Fragment getItem(int i) {
switch (i) {
// default case is also case 0 to avoid redundant code
default: return new CalculatorFragment();
case 1: return new TapeFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 1: return "Review";
default: return "Calculator";
}
}
public Fragment getRegisteredFragment(int position){
return registeredFragments.get(position);
}
}
My main class which should create the PreferenceFragment when user taps "Settings"
public class MangoCalc extends FragmentActivity implements CalculatorFragment.CalcTapeInterface{
PagerAdapter pagerAdapter;
ViewPager myViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
final ActionBar actionBar = getActionBar();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mango_calc);
pagerAdapter = new PagerAdapter(getFragmentManager());
myViewPager = (ViewPager) findViewById(R.id.main);
myViewPager.setAdapter(pagerAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
myViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {}
};
for (int i=0; i< pagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setText(pagerAdapter.getPageTitle(i))
.setTabListener(tabListener));
}
myViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mango_calc, 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) {
FragmentManager fm = getFragmentManager();
SettingsFragment settingsFragment = new SettingsFragment();
fm.beginTransaction().replace(R.id.main, settingsFragment).commit();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTapePass(ArrayList<String> data) {
if (data!=null) Log.d("Tape", "Last element got: "+data.get(data.size()-1));
TapeFragment tapeFragment = (TapeFragment) pagerAdapter.getRegisteredFragment(1);
tapeFragment.updateTape(data);
}
}
My preferences.XML
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="#string/lookandfeel">
<ListPreference
android:key="theme_preference"
android:title="#string/theme"
android:summary="#string/summary_theme_preference"
android:entries="#array/entries_theme_preference"
android:entryValues="#array/entryvalues_theme_preference"
android:defaultValue="mango"/>
<SwitchPreference
android:key="keypress_vibration_preference"
android:title="#string/keypress_vibration"
android:summaryOn="#string/summaryon_keypress_vibration_preference"
android:summaryOff="#string/summaryoff_keypress_vibration_preference"
android:switchTextOn="#string/text_keypress_vibration_on"
android:switchTextOff="#string/text_keypress_vibration_off"
android:defaultValue="true" />
</PreferenceCategory>
</PreferenceScreen>
and the XML for the activity:
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/main"
/>
In your getitem case 1 needs to be listed before the default
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.
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);
}