I am trying to convert all my code from activities to fragments in order to use a navigation drawer and eventualy some sliding tabs.
Currently I have a semi working navigation drawer that opens and displays a list. BUt I am new to fragments and am confused because it seems to reload my first fragment everytime I close the navigation drawer and do not select anything.
MainDrawer.java :
package com.beerportfolio.beerportfoliopro;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by Mike on 1/3/14.
*/
public class MainDraw extends FragmentActivity {
final String[] data ={"Statistics","two","three"};
final String[] fragments ={
"com.beerportfolio.beerportfoliopro.StatisticsPage",
"com.beerportfolio.beerportfoliopro.FragmentTwo",
"com.beerportfolio.beerportfoliopro.FragmentThree"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
//todo: load statistics fragment
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActionBar().getThemedContext(), android.R.layout.simple_list_item_1, data);
final DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
final ListView navList = (ListView) findViewById(R.id.drawer);
navList.setAdapter(adapter);
navList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener( new DrawerLayout.SimpleDrawerListener(){
#Override
public void onDrawerClosed(View drawerView){
super.onDrawerClosed(drawerView);
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main, Fragment.instantiate(MainDraw.this, fragments[pos]));
tx.commit();
}
});
drawer.closeDrawer(navList);
}
});
FragmentTransaction tx = getSupportFragmentManager().beginTransaction();
tx.replace(R.id.main,Fragment.instantiate(MainDraw.this, fragments[0]));
tx.commit();
}
}
StatisticsPage.java :
package com.beerportfolio.beerportfoliopro;
import android.app.ActionBar;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Created by Mike on 1/3/14.
*/
public class StatisticsPage extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
String url = "http://www.beerportfolio.com/app_getStatistics.php?";
String userURLComp = "u=" + userID;
url = url + userURLComp ;
Log.d("basicStats", url);
new getBasicStats(getActivity()).execute(url);
// Inflate the layout for this fragment
return inflater.inflate(R.layout.statistics_pagelayout, container, false);
}
}
The issue is that your DrawerListener is set in your OnClickListener when it shouldn't be:
#Override public void onItemClick(AdapterView<?> parent, View view, final int pos,long id){
drawer.setDrawerListener(
new DrawerLayout.SimpleDrawerListener(){
#Override public void onDrawerClosed(View drawerView){...}
}
);
}
The scope of your pos integer is such that, every time the drawer closes, onDrawerClose thinks that the value of pos hasn't changed. Since there isn't a condition checking that an item was clicked, then the same Fragment is recreated each time the drawer closes (unless you click on a different item).
Set a member boolean to true when an item is clicked and set a member int to its position. Use the boolean to differentiate between an item click and a drawer close:
private boolean mNavItemClicked = false;
private int mNavPosition = 0;
...
#Override protected void onCreate(Bundle savedInstanceState) {
...
navList.setOnItemClickListener(new ListView.OnItemClickListener {
#Override public void onItemClick(AdapterView parent, View view, int position, long id) {
mNavItemClicked = true;
mNavPosition = position;
drawerLayout.closeDrawer(navList);
}
});
ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(...) {
public void onDrawerClosed(View view) {
if (mNavItemClicked) {
getSupportFragmentManager().beginTransaction()
.replace(R.id.main, Fragment.instantiate(MainDraw.this
, fragments[mNavPosition])
.commit();
}
mNavItemClicked = false;
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
If you decide to use the ActionBarDrawerToggle then follow its design guidelines and call through to the Activity callback methods onConfigurationChanged and onOptionsItemSelected.
Related
For my academic project, I want create an application with 4 tabs. The first one will show recent games added to a list, the second one will be a search form, the third will show the search result, and the last one will show the details. I currently have created the code for TabView and the 4 tabs. The problem is that I want to perform a search to get the items I have in a list which meet the search criteria on fragment 2, but I don't know how to pass the data from fragment 2 (textView data and spinner) to fragment 3. My code is the following:
MainActivity.java:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_search_white_24dp);
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();
}
});
//TabLayout function call
configureTabLayout();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
return true;
case R.id.menu_settings:
Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Tab Layout function declaration
private void configureTabLayout() {
//Getting the tab layout
TabLayout tabLayout = findViewById(R.id.tab_layout);
//Adding Tabs
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));
//The TabPagerAdapter instance is then
//assigned as the adapter for the ViewPager and the TabLayout component added
//to the page change listener
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Finally, the onTabSelectedListener is configured on the TabLayout instance and
//the onTabSelected() method implemented to set the current page on the
//ViewPager based on the currently selected tab number.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
TabPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeScreenFragment();
case 1:
return new SearchFormFragment();
case 2:
return new SearchResultsFragment();
case 3:
return new DetailsScreenFragment();
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
SearchFormFragment.java
package gr.pliroforiki_edu.videogamedb;
import android.content.Intent;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchFormFragment extends Fragment {
private Button searchButton;
private EditText gameTitleEditText;
Spinner spinnerGenre;
public SearchFormFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);
searchButton = searchFormView.findViewById(R.id.searchButton);
gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);
spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
getActivity(),
R.array.game_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterGameTitle = gameTitleEditText.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);
Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();
}
});
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_search_form, container, false);
return searchFormView;
}
}
SearchResultsFragment.java
import android.content.Intent;
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.ListView;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);
return searchResultsView;
}
private void findViews()
{
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
I want to archive the following via the fragments:
ListActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class ListActivity extends AppCompatActivity {
private TextView textViewInfo;
private ListView listViewBooks;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
// Animation when this Activity appears
overridePendingTransition(R.anim.pull_in_from_right, R.anim.hold);
// Get user filters from Intent
Intent intent = getIntent();
String filterAuthor = intent.getStringExtra("AUTHOR");
String filterTitle = intent.getStringExtra("TITLE");
int filterGenreId = intent.getIntExtra("GENREID", 0);
findViews();
// Show user filters for information
String message = String.format("Author: %s\nTitle: %s\nGenreId: %d",
filterAuthor, filterTitle, filterGenreId);
textViewInfo.setText(message);
DataStore.LoadBooks(filterAuthor, filterTitle, filterGenreId);
//Complex Object Binding
ListAdapter booksAdapter = new SimpleAdapter(
this,
DataStore.Books,
R.layout.list_item,
new String[]{DataStore.KEY_TITLE, DataStore.KEY_AUTHOR, DataStore.KEY_GENRENAME},
new int[]{R.id.book_item_title, R.id.book_item_author, R.id.book_item_genre}
);
listViewBooks.setAdapter(booksAdapter);
listViewBooks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent detailsIntent = new Intent(ListActivity.this, DetailsActivity.class);
detailsIntent.putExtra(DataStore.KEY_POSITION, position);
startActivity(detailsIntent);
}
});
}
#Override
protected void onPause(){
overridePendingTransition(R.anim.hold, R.anim.push_out_to_right);
super.onPause();
}
private void findViews(){
textViewInfo = findViewById(R.id.textViewInfo);
listViewBooks = findViewById(R.id.listViewBooks);
}
}
Mainactivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private EditText textAuthor;
private EditText textTitle;
private EditText textGenre;
private Button buttonSearch;
private Spinner spinnerGenre;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DataStore.Init(getApplicationContext());
textAuthor = findViewById(R.id.editTextAuthor);
textTitle= findViewById(R.id.editTextAuthor);
buttonSearch = findViewById(R.id.buttonSearch);
spinnerGenre = (Spinner) findViewById(R.id.spinnerGenre);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
this,
R.array.book_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
buttonSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterAuthor = textAuthor.getText().toString();
String filterTitle = textTitle.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
Intent intent = new Intent(MainActivity.this, ListActivity.class);
intent.putExtra("AUTHOR", filterAuthor);
intent.putExtra("TITLE", filterTitle);
intent.putExtra("GENREID", filterGenreId);
startActivity(intent);
}
});
}
}
Try this
pass value between two fragment using bundle
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class TabPagerAdapter extends FragmentPagerAdapter{
int tabCount;
public TabPagerAdapter(FragmentManager fm, int numberOfTabs) {
super(fm);
this.tabCount = numberOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new HomeScreenFragment();
case 1:
return new SearchFormFragment();
case 2:
Fragment fragment = new SearchResultsFragment()
Bundle args = new Bundle();
args.putString("Key", "Value");
fragment.setArguments(args);
return fragment;
case 3:
return new DetailsScreenFragment();
default:
return null;
}
}
#Override
public int getCount() {
return tabCount;
}
}
in your onCreateView(....) of SearchResultsFragment
String value = getArguments().getString("Key");
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView =
inflater.inflate(R.layout.fragment_search_results, container, false);
String value = getArguments().getString("Key");
return searchResultsView;
}
private void findViews(){
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
hop its help you
There are many ways you can pass objects/values between fragments. In your case, the simplest solution would be to delegate those values to the holding Activity i.e MainActivity.
MainActivity:
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.view.MenuInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
//these will hold your values
String filterGameTitle;
int filterGenreId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setImageResource(R.drawable.ic_search_white_24dp);
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();
}
});
//TabLayout function call
configureTabLayout();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menu_exit:
finish();
return true;
case R.id.menu_settings:
Toast.makeText(this, "Under Construction", Toast.LENGTH_LONG).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//Tab Layout function declaration
private void configureTabLayout() {
//Getting the tab layout
TabLayout tabLayout = findViewById(R.id.tab_layout);
//Adding Tabs
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_home_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_search_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_results_white_24dp));
tabLayout.addTab(tabLayout.newTab().setIcon(R.drawable.ic_details_white_24dp));
//The TabPagerAdapter instance is then
//assigned as the adapter for the ViewPager and the TabLayout component added
//to the page change listener
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new TabPagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
//Finally, the onTabSelectedListener is configured on the TabLayout instance and
//the onTabSelected() method implemented to set the current page on the
//ViewPager based on the currently selected tab number.
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
}
SearchFormFragment:
import android.content.Intent;
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.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchFormFragment extends Fragment {
private Button searchButton;
private EditText gameTitleEditText;
Spinner spinnerGenre;
public SearchFormFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(final LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchFormView = inflater.inflate(R.layout.fragment_search_form, container, false);
searchButton = searchFormView.findViewById(R.id.searchButton);
gameTitleEditText = searchFormView.findViewById(R.id.game_title_editText);
spinnerGenre = searchFormView.findViewById(R.id.genre_spinner);
ArrayAdapter<CharSequence> genreAdapter = ArrayAdapter.createFromResource(
getActivity(),
R.array.game_genres,
android.R.layout.simple_spinner_item
);
genreAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerGenre.setAdapter(genreAdapter);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String filterGameTitle = gameTitleEditText.getText().toString();
int filterGenreId = spinnerGenre.getSelectedItemPosition();
((MainActivity)getActivity()).filterGameTitle = filterGameTitle;
((MainActivity)getActivity()).filterGenreId = filterGenreId;
String message = String.format("Game Title: %s\n Genre: %s", filterGameTitle, filterGenreId);
Toast.makeText(getActivity(),message, Toast.LENGTH_LONG).show();
}
});
// Inflate the layout for this fragment
//return inflater.inflate(R.layout.fragment_search_form, container, false);
return searchFormView;
}
}
SearchResultFragment:
import android.content.Intent;
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.ListView;
import android.widget.TextView;
/**
* A simple {#link Fragment} subclass.
*/
public class SearchResultsFragment extends Fragment {
TextView infoTextView;
ListView listViewGames;
String filterGameTitle;
int filterGenreId;
public SearchResultsFragment() {
// Required empty public constructor
}
#Override
public void onAttach(Context context)
{
filterGameTitle = ((MainActivity)getActivity()).filterGameTitle;
filterGenreId = ((MainActivity)getActivity()).filterGenreId;
super.onAttach(context);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View searchResultsView = inflater.inflate(R.layout.fragment_search_results, container, false);
return searchResultsView;
}
private void findViews()
{
infoTextView = getActivity().findViewById(R.id.info_textView);
listViewGames = getActivity().findViewById(R.id.games_listView);
}
}
You can use interface to send your search string to your activity from fragment 2, and from their you can call all methods in your fragment 3 as fragment3 object will be available to you in your activity, you can make performSearch() in your fragment3 and call it from your activity.
Alternatively you can use something like event bus to avoid the boiler plate code needed to setup interface.
Have a look at this event bus repo https://github.com/greenrobot/EventBus
Register event bus where you want the search string, in your case register the event bus in Fragment3 like this
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
In your Fragment 3 create a function like this
#Subscribe
public void onSearchEvent(String searchString){
//you will get your search string here
}
Now comeback to fragment2 from where you want to send the searchString, you have to put below code from where you want to send searchString, and this posted searchString will be received by fragment 3 in its onSearchEvent method
EventBus.getDefault().post(searchString);
import android.app.DialogFragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
/**
* Created by jamie on 9/12/2015.
*/
public class PlayersFragment extends DialogFragment {
ListView lv;
String[] players = {"arteta", "costa", "reid", "degea", "rooney", "terry"};
int[] images = {R.drawable.arteta, R.drawable.costa, R.drawable.reid, R.drawable.degea,
R.drawable.rooney, R.drawable.terry};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.dialog, container, false);
//initialize listview
lv = (ListView) rootView.findViewById(R.id.listView1);
//set dialog title
getDialog().setTitle("Soccer SuperStars");
//create adapter obj and set list view to it
Adapter adapter = new Adapter(getActivity(), players, images);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int pos, long id) {
Toast.makeText(getActivity(), players[pos], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
Trying to create a ListView fragment in android studio and getting
error
cannot resolve method show(android.support.v4.app
FragmentManager,java.lang.string)
the error is on the p.show(fm,"Players Fragment) underlined in red, tried to resolve this but getting nowhere, i would really appreciate a solution to this! thank you
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class MainActivity extends FragmentActivity {
Button showBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final FragmentManager fm =getSupportFragmentManager();
final PlayersFragment p=new PlayersFragment();
showBtn=(Button)findViewById(R.id.button1);
showBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
p.show(fm,"Players Fragment"); //error is here
}
});
}
}
I suppose you are using android.app.DialogFragment and not android.support.v4.app.DialogFragment. Just extend PlayersFragment from support library's android.support.v4.app.DialogFragment. Or, if you are not targeting old devices, you can change getSupportFragmentManager() to getFragmentManager()
You have to import android.support.v4.app.DialogFragment on the class PlayersFragment and then change getSupportFragmentManager() to getFragmentManager().
Can someone help me how to handle button clicks on fragments? I'm having an error when I go to my fragment in profile. When I click the button on fragment_profile, I always get an error.
Here's my code:
For my Main Activity Class:
package com.the.healthescort;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
Context CTX = this;
public int see;
public String cc="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Mod();
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
//
}
public void Mod(){
DatabaseOperation DOp = new DatabaseOperation(CTX);
Cursor cr = DOp.getInformation(DOp);
if (cr != null && cr.getCount()>0){
cr.moveToFirst();
startManagingCursor(cr);
for(int i=0;i<cr.getCount();i++){
String x = cr.getString(3);
String y = cr.getString(4);
String c = x.replace("\"", "");
String r = c.replace("' ", ".");
double get = Double.parseDouble(r);
int z = (int) get;
double w = get % z;
double roundOff = Math.round(w*10);
int ans = (z*12)+ (int)roundOff;
String g = y.replace(" lbs","");
double h = Double.parseDouble(g);
double total = (h/(ans*ans))*703;
}
}else{
Intent k = new Intent(MainActivity.this, Add_Profile.class);
startActivity(k);
finish();
}
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
FragmentTransaction tx = getSupportFragmentManager().beginTransaction(); // For AppCompat use getSupportFragmentManager
switch(position) {
case 0:
mTitle = getString(R.string.title_section1);
tx.replace(R.id.container,PlaceholderFragment.newInstance(position + 1));
tx.commit();
break;
case 1:
mTitle = getString(R.string.title_section2);
tx.replace(R.id.container,new profile_fragment());
tx.commit();
break;
case 2:
fragment = PlaceholderFragment.newInstance(position + 1);
break;
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
break;
case 2:
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public int check;
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
My Fragment code:
package com.the.healthescort;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
public class profile_fragment extends Fragment {
public static Fragment newInstance(Context context) {
profile_fragment f = new profile_fragment();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View root = (View) inflater.inflate(R.layout.fragment_profile_fragment, container, false);
Button a = (Button) root.findViewById(R.id.sana);
a.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
TextView b = (TextView) view.findViewById(R.id.gumana);
b.setText("Click!");
}
});
return root;
}
}
public void onClick(View view){
TextView b = (TextView) view.findViewById(R.id.gumana);
b.setText("Click!");
}
in this case, view is the object on which you called setOnClickListener, the button you called a. If you call view.findViewById(R.id.yourid), on a View's subclass, what the system does is to check if the id you passed as parameter is equal to the one of the view on which you are calling findViewById. It the view is subclass of ViewGroup's, then the system looks for the provided id among the ViewGroup's children. In your case the view's id is R.id.sana, and you are passing R.id.gumana as parameter. Since the ids don't match the system returns null. You probably have declared the TextView, inside fragment_profile_fragment.xml.
Change
TextView b = (TextView) view.findViewById(R.id.gumana);
with
TextView b = (TextView) getView().findViewById(R.id.gumana);
I am just starting to learn how to program, so sorry if this is a weird or dumb question.
I am making SlideingScreen using a ViewPager. I copied the code from here (http://developer.android.com/training/animation/screen-slide.html), but I keep getting the errors located here.
Here is the code with the two thingies:
package com.example.ryanfolz.gridgame;
import android.support.v4.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
public class ScreenSlideActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
//invalidateOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
menu.findItem(R.id.action_previous).setEnabled(mPager.getCurrentItem() > 0);
// Add either a "next" or "finish" button to the action bar, depending on which page
// is currently selected.
MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,
(mPager.getCurrentItem() == mPagerAdapter.getCount() - 1)
? R.string.action_finish
: R.string.action_next);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
return true;
case R.id.action_previous:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
The fragment is here
package com.example.ryanfolz.gridgame;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ScreenSlidePageFragment extends Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
ViewGroup rootView;
private int mPageNumber;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
if(mPageNumber == 1){
rootView = (ViewGroup) inflater
.inflate(R.layout.test, container, false);
((TextView) rootView.findViewById(R.id.test)).setText("Hello");
}else {
rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_screen_slide_page, container, false);
// Set the title view to show the page number.
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.title_template_step, mPageNumber + 1));
}
return rootView;
}
public int getPageNumber() {
return mPageNumber;
}
}
Delete these line from your import
import android.app.FragmentManager;
import android.app.Fragment;
When your IDE ask for which class to import, you should choose these classes from support package instead, like this:
android.support.v4.app.FragmentStatePagerAdapter;
Instead of using getFragmentManager(), you should call getSupportFragmentManager()
I am making SlideingScreen using a ViewPager. I copied the code from here (http://developer.android.com/training/animation/screen-slide.html), but I keep getting the errors
If you check the example properly they have imported
import android.support.v4.app.FragmentManager;
and not
import android.app.FragmentManager;
And also they have used
getSupportFragmentManager()
and not
getFragmentManager()
This changes is required because you are using the android support library for your fragment.
In your ScreenSlideActivity file, change
import android.app.FragmentManager;
to
import android.support.v4.app.FragmentManager;
And for ScreenSlidePageFragment, change this line
import android.app.Fragment;
into this
import android.support.v4.app.Fragment;
At last. Change all
getFragmentManager()
to
getSupportFragmentManager()
As a lot of people have been doing so far, I'm implementing the FragmentTabsPager into my app, which is using ActionBarSherlock 4.0. However, I'm lost.
Fragments, and all of Google's little ideas, plans and methods surrounding it, are confusing me. If anyone could take a look at my code and walk me through this, providing help in making it work, I would thank them a thousand times :D.
I have another project with a sort-of beginning for a ViewPager, but the Tabs just mix better, especially with them being in the ActionBar on landscape and tablets.
My code is all zipped up and ready to go over here:
http://dl.dropbox.com/u/21807195/Antonius%20College%202.zip
Thanks in advance!
I will show you my code that has a ViewPager, TabListener, and system of Fragments linked to each tab. It implements ABS, but as of yet, still crashes on Gingerbread and lower (works beautifully on ICS, though):
import java.util.ArrayList;
import library.DatabaseHandler;
import org.json.JSONObject;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View.OnClickListener;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
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.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
public class Polling extends SherlockFragmentActivity {
private ViewPager mViewPager;
private TabsAdapter mTabsAdapter;
private final static String TAG = "21st Polling:";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mViewPager = new ViewPager(this);
mViewPager.setId(R.id.pager);
setContentView(mViewPager);
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
mTabsAdapter = new TabsAdapter(this, mViewPager);
mTabsAdapter.addTab(bar.newTab().setText(R.string.login),
LoginFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.economics),
EconFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.elections),
ElectionsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.politics),
PoliticsFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.science),
ScienceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.finance),
FinanceFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.religion),
ReligionFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.military),
MilitaryFragment.class, null);
mTabsAdapter.addTab(bar.newTab().setText(R.string.international),
InternationalFragment.class, null);
Log.v(TAG, (String)bar.getTabAt(0).getText());
}
public static class TabsAdapter extends FragmentPagerAdapter
implements ActionBar.TabListener, ViewPager.OnPageChangeListener {
private final Context mContext;
private final ActionBar mActionBar;
private final ViewPager mViewPager;
private final ArrayList<TabInfo> mTabs = new ArrayList<TabInfo>();
static final class TabInfo {
private final Class<?> clss;
private final Bundle args;
TabInfo(Class<?> _class, Bundle _args) {
clss = _class;
args = _args;
}
}
public TabsAdapter(SherlockFragmentActivity activity, ViewPager pager) {
super(activity.getSupportFragmentManager());
mContext = activity;
mActionBar = activity.getSupportActionBar();
mViewPager = pager;
mViewPager.setAdapter(this);
mViewPager.setOnPageChangeListener(this);
}
public void addTab(ActionBar.Tab tab, Class<?> clss, Bundle args) {
TabInfo info = new TabInfo(clss, args);
tab.setTag(info);
tab.setTabListener(this);
mTabs.add(info);
mActionBar.addTab(tab);
notifyDataSetChanged();
}
public int getCount() {
return mTabs.size();
}
public SherlockFragment getItem(int position) {
TabInfo info = mTabs.get(position);
return (SherlockFragment)Fragment.instantiate(mContext, info.clss.getName(), info.args);
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
public void onPageScrollStateChanged(int state) {
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mViewPager.setCurrentItem(tab.getPosition());
//Log.v(TAG, "clicked");
Object tag = tab.getTag();
for (int i=0; i<mTabs.size(); i++) {
if (mTabs.get(i) == tag) {
mViewPager.setCurrentItem(i);
}
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, FragmentTransaction ft) {}
public void onTabReselected(Tab tab, android.app.FragmentTransaction ft) {}
public void onTabUnselected(Tab tab, android.app.FragmentTransaction ft) {}
}
And here is what one fragment looks like:
package com.davekelley.polling;
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MilitaryFragment extends SherlockFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.militaryfragment, container, false);
}
}
My last note would that my code still has one other issue: individual fragments do not always reload their interface after the user press back (which results in removing the entire app from the screen, regardless which tab/fragment they are on, because I have no backStack). So that's what I'm working through now. I think once I have that sorted, I'll try to figure out why I still don't have Gingerbread execution functioning properly. Either way, I hope looking through this code helps you out.
Here is a fragment with some onClickListeners:
import com.actionbarsherlock.R;
import com.actionbarsherlock.app.SherlockFragment;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
public class LoginFragment extends SherlockFragment {
Button loginButton;
Button registerButton;
Polling activity;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.loginfragment, container, false);
return v;
}
public void onResume() {
super.onResume();
Log.d("Econ", "onresume");
loginButton = (Button) getActivity().findViewById(R.id.loginButton);
loginButton.setOnClickListener(loginListener);
registerButton = (Button) getActivity().findViewById(R.id.registerButton);
registerButton.setOnClickListener(registerListener);
}
public OnClickListener loginListener = new OnClickListener() {
#Override
public void onClick(View v) {
if(loginButton.getText().toString() == "Log Out") {
activity.loginReport(2);
loginButton.setText(R.string.login);
//Remove user from dB sqllite when I know how
}
else {
Log.v("LoginF", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Logging in...");
LoginTask loginTask = new LoginTask((Polling) getActivity(), progressDialog);
loginTask.execute();
}
}
};
public OnClickListener registerListener = new OnClickListener() {
#Override
public void onClick(View v) {
Log.v("Register", "onclick");
ProgressDialog progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Registering new user...");
RegisterTask registerTask = new RegisterTask((Polling) getActivity(), progressDialog);
registerTask.execute();
}
};
public void onAttach(Activity activity) {
super.onAttach(activity);
this.activity = (Polling) activity;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public void onStart() {
super.onStart();
Log.d("Econ", "onstart");
}
public void onPause() {
super.onPause();Log.d("Econ", "onpause");
}
public void onStop() {
super.onStop();
Log.d("Econ", "onstop");
}
public void onDestroyView() {
super.onDestroyView();
Log.d("Econ", "ondestroyview");
}
public void onDestroy() {
super.onDestroy();
Log.d("Econ", "ondestroy");
}
public void onDetach() {
super.onDetach();
Log.d("Econ", "ondetach");
}
}
The loginTask objects that you see are actually classes that extend ASyncTask - they handle connecting to my server and registering/logging in.
I thought it would be helpful to add in one bit more of code. This is another one of my fragments, like LoginFragment, but it inflates a UI a little differently. Eventually, what you see in the while loop below, will head into an ASyncTask to acquire each question from the server, rather than the dummy string array you see:
public class EconFragment extends SherlockFragment {
private TableLayout questionContainer;
int pos = 0;
private String[] titles = {"The first title ", "hallo1","hallo2", "hallo3",
"hallo4", "hallo5","hallo6", "hallo7","hallo8", "hallo9"};
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.v("Econ", "onCreateView");
View v = inflater.inflate(R.layout.econfragment, container, false);
questionContainer = (TableLayout) v.findViewById(R.id.questionContainer);
//bs
int leftMargin=5;
int topMargin=5;
int rightMargin=5;
int bottomMargin=5;
while (pos < 10) {
View question = inflater.inflate(R.layout.question, null);
question.setId(pos);
TextView title = (TextView) question.findViewById(R.id.questionTextView);
title.setText(titles[pos]);
Button charts = (Button) question.findViewById(R.id.chartsButton);
charts.setId(pos);
charts.setOnClickListener(chartsListener);
TableRow tr = (TableRow) question;
TableLayout.LayoutParams trParams = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT);
trParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(trParams);
Log.v("econ", "while loop");
questionContainer.addView(tr);
pos++;
}
pos = 0;
return v;
}
I have ported the FragmentTabsPager Activity and associated Fragments from "Support4Demos" (Android Support library sample) to use ActionBarSherlock and true ActionBar Tabs. The sample includes an Activity that uses both a ViewPager and Tabs to switch between Fragments. The Fragments contain three kinds of ListViews. I've tested it from ICS down to Eclair (2.1). You can browse or download the code at http://code.google.com/p/sherlock-demo/.