I have a FragmentTabHost and have some problems with it on fragment switching. After attempting a fragment switch and then I click on another tab, the tab contents overlap. I then try to override the onTabChanged method (don't know whether it could be a solution though....), however I discover the onTabChanged does not be run!
--Update--
onTabChanged is now runnable but the overlap problem is still here.
here is my code:
MainActivity
public class MainActivity extends FragmentActivity implements OnTabChangeListener{
private static final String TAB = "MainActivity";
private FragmentTabHost tabMenu;
public static final String NEWS_TAB = "news";
public static final String SHARE_TAB = "share";
public static final String CAMERA_TAB = "camera";
public static final String STATUS_TAB = "status";
public static final String OTHER_TAB = "other";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabMenu = (FragmentTabHost)findViewById(R.id.main_tabhost);
tabMenu.setup(this, getSupportFragmentManager(), android.R.id.tabcontent);
String[] tabTitle = getResources().getStringArray(R.array.tab_title);
for (int i=0; i<tabTitle.length; i++){
String tagId = "";
int tabIconDrawable = 0;
Class tabClass = BlankTab.class;
switch(tabTitle[i]){
case "最新消息":
tabIconDrawable = R.drawable.ic_action_view_as_list;
tagId = this.NEWS_TAB;
tabClass = News.class;
break;
case "貨件分享":
tabIconDrawable = R.drawable.ic_action_important;
tagId = this.SHARE_TAB;
tabClass = GoodsShare.class;
break;
case "":
tabIconDrawable = R.drawable.ic_action_camera;
tagId = this.CAMERA_TAB;
break;
case "物流狀態":
tabIconDrawable = R.drawable.ic_action_airplane_mode_on;
tagId = this.STATUS_TAB;
tabClass = LogisticStatus.class;
break;
case "其他":
tabIconDrawable = R.drawable.ic_action_overflow;
tagId = this.OTHER_TAB;
tabClass = Others.class;
break;
}
View tabView = getLayoutInflater().inflate(R.layout.tab_layout, null, false);
ImageView tabIcon = (ImageView)tabView.findViewById(R.id.tab_icon);
TextView tabText = (TextView)tabView.findViewById(R.id.tab_title);
tabIcon.setImageDrawable(getResources().getDrawable(tabIconDrawable));
tabText.setText(tabTitle[i]);
TabSpec spec = tabMenu.newTabSpec(tagId).setIndicator(tabView);
tabMenu.addTab(spec, tabClass, null);
tabMenu.getTabWidget().getChildAt(i).setBackground(getResources().getDrawable(R.drawable.main_tab_selector));
}
tabMenu.setOnTabChangedListener(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.
return super.onOptionsItemSelected(item);
}
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
Log.d(TAB, tabId);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
Fragment fragment = null;
if (tabId.equals(this.NEWS_TAB)){
fragment = new News();
} else if (tabId.equals(this.SHARE_TAB)){
fragment = new GoodsShare();
} else if (tabId.equals(this.CAMERA_TAB)){
fragment = new Camera();
} else if (tabId.equals(this.STATUS_TAB)){
fragment = new LogisticStatus();
} else if (tabId.equals(this.OTHER_TAB)){
fragment = new Others();
}
if (fragment != null){
t.replace(android.R.id.tabcontent, fragment);
} else {
Log.e(TAB, "fragment creation error");
}
}
}
Others<---the one has fragment switching
public class Others extends Fragment{
private View view;
private Controller controller;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
controller = (Controller)this.getActivity().getApplication();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
view = inflater.inflate(R.layout.others, container, false);
setLayout();
return view;
}
private void setLayout(){
ListView othersMenu = (ListView)view.findViewById(R.id.others_menu);
String[] othersItem = getResources().getStringArray(R.array.others);
ArrayAdapter<String> adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, othersItem);
othersMenu.setAdapter(adapter);
othersMenu.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String item = (String)parent.getItemAtPosition(position);
Fragment fragment = null;
switch(item){
case "貨倉地址":
fragment = new WarehouseAddress();
break;
case "托運流程":
fragment = new TransProcess();
break;
case "常見問題":
fragment = new FAQ();
break;
case "聯絡我們":
fragment = new ContactUs();
break;
case "運費計算器":
fragment = new FeeCalculater();
break;
default:
fragment = new BlankTab();
}
controller.fragmentSwitch(getActivity(), fragment);
}
});
}
}
fragmentSwitch method
public void fragmentSwitch(Fragment fragment){
FragmentManager fragmentManager = slideMenuActivity.getSupportFragmentManager();
fragmentManager.beginTransaction()
//.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
.replace(android.R.id.tabcontent, fragment)
.commit();
fragmentManager.executePendingTransactions();
}
Finally, I found it. A commit() is missed in onTabChanged.
#Override
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
Log.d(TAB, tabId);
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
Fragment fragment = null;
if (tabId.equals(this.NEWS_TAB)){
fragment = new News();
} else if (tabId.equals(this.SHARE_TAB)){
fragment = new GoodsShare();
} else if (tabId.equals(this.CAMERA_TAB)){
fragment = new Camera();
} else if (tabId.equals(this.STATUS_TAB)){
fragment = new LogisticStatus();
} else if (tabId.equals(this.OTHER_TAB)){
fragment = new Others();
}
if (fragment != null){
t.replace(android.R.id.tabcontent, fragment).commit(); //missing commit() here
} else {
Log.e(TAB, "fragment creation error");
}
}
Related
I have a fragment MyProfile (consists info about a logged user) which I want to be used by fragments Team (consists info about all team members). When I use MyProfile for Team fragment, I need up button. I read documentation guide, tried all from up navigation inside fragment and stopped on this example. The problem is instead of going back to the previous fragment in my case it just opens the options menu.
MainActivity
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
int id = item.getItemId();
if (id == R.id.nav_team) {
fragmentTransaction.replace(R.id.container, new TeamFragment())
.addToBackStack(null)
.commit();
}
TeamFragment
public class TeamFragment extends Fragment {
private String LOG_TAG = getClass().getSimpleName();
private ListView teamList;
private android.support.v4.app.FragmentManager fragmentManager;
public TeamFragment() {
// Required empty public constructor
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
((MainActivity) getActivity()).setActionBarTitle("Team");
View rootView = inflater.inflate(R.layout.fragment_announcement, container, false);
final SwipeRefreshLayout swipeToUpdate = rootView.findViewById(R.id.swiperefresh);
teamList = rootView.findViewById(R.id.announcements_list);
getTeamFromAPI(Contract.TEAM);
teamList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageView avatar = view.findViewById(R.id.team_img);
TextView fullname = view.findViewById(R.id.team_fullname);
TextView jobtitle = view.findViewById(R.id.team_jobtitle);
TextView email = view.findViewById(R.id.team_email);
avatar.buildDrawingCache();
Bitmap bitmap = avatar.getDrawingCache();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] bAvatar = baos.toByteArray();
//when team member i replace here current fragment with profile fragment
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = ProfileFragment.newInstance(String.valueOf(fullname.getText()),
String.valueOf(jobtitle.getText()),
String.valueOf(email.getText()), bAvatar);
fragmentTransaction.replace(R.id.container, fragment, "MEMBER_PROFILE")
.addToBackStack(null)
.commit();
}
});
return rootView;
}
private void getTeamFromAPI(String url) {
//fetch team members from database
}
}
Place where I try return back to TeamFragment
ProfileFragment
public class ProfileFragment extends Fragment{
private String LOG_TAG = getClass().getSimpleName();
private String mFullname;
private String mTitle;
private String mEmail;
private byte[] mAvatar;
private android.support.v4.app.FragmentManager fragmentManager;
private ActionBar actionBar;
private View rootView;
public ProfileFragment() {
// Required empty public constructor
}
public static ProfileFragment newInstance(String name, String title, String email, byte[] avatar) {
Bundle bundle = new Bundle();
bundle.putString("fullname", name);
bundle.putString("title", title);
bundle.putString("email",email);
bundle.putByteArray("avatar", avatar);
ProfileFragment fragment = new ProfileFragment();
fragment.setArguments(bundle);
return fragment;
}
private void readBundle(Bundle bundle) {
if (bundle != null) {
this.mFullname = bundle.getString("fullname");
this.mTitle = bundle.getString("title");
this.mEmail = bundle.getString("email");
this.mAvatar = bundle.getByteArray("avatar");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragmentManager = getFragmentManager();
// Sets "up navigation" for both phone/tablet configurations
actionBar = ((MainActivity)getActivity()).getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
rootView = inflater.inflate(R.layout.fragment_announcement, container, false);
ListView listView = rootView.findViewById(R.id.announcements_list);
SwipeRefreshLayout swipe = rootView.findViewById(R.id.swiperefresh);
swipe.setEnabled(false);
readBundle(getArguments());
ArrayList<ProfileObject> list = new ArrayList<>();
list.add(new ProfileObject(mFullname, mTitle,mEmail,mAvatar));
ProfileAdapter adapter = new ProfileAdapter(getContext(), list);
listView.setAdapter(adapter);
return rootView;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.e(LOG_TAG+"/onOptionsItemSelected","Pressed: "+item.getItemId());
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProfileFragment member_profile = (ProfileFragment)fragmentManager.findFragmentByTag("MEMBER_PROFILE");
fragmentTransaction.remove(member_profile).commit();
fragmentManager.popBackStack();
actionBar.setDisplayHomeAsUpEnabled(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
But as I already said it only the opens options menu. Did I make a somewhere conceptual mistake?
UPDATE: Problem inside onOptionsItemSelected. If add
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
Log.e(LOG_TAG+"/onOptionsItemSelected","Pressed: "+item.getItemId());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
and click on back arrow nothing will be in Logcat.
As per your code you have handled onOptionsItemSelected() for R.id.home but I see you are using ActionBar back button which is provided by Android UI itself
actionBar = ((MainActivity)getActivity()).getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
In this case Home Button is referenced as android.R.id.home and NOT R.id.home
This is the reason you are not getting any update in Logcat too (as you mentioned in comments).
Update your switch case as below and replace R.id.home with android.R.id.home
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: // <- Update this
android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
ProfileFragment member_profile = (ProfileFragment)fragmentManager.findFragmentByTag("MEMBER_PROFILE");
fragmentTransaction.remove(member_profile).commit();
fragmentManager.popBackStack();
actionBar.setDisplayHomeAsUpEnabled(false);
return true;
default:
return super.onOptionsItemSelected(item);
}
So, as the title states, I wish to produce some amount of layouts within a Fragment which is in turn within a fragment. The number of layouts depends on the number of columns returned from a database, and the number of columns returned depends on which Fragment the user is currently on.
The first fragments are a BottomNavigation View, then the second set of Fragments are a range of swipe panels within each part of the BottomNavigation. It is in these fragments that I want to produce the variable number of layouts.
Here is a screenshot of what I'm looking to achieve
I was trying to create the Layouts within the OnCreateView() method for the inner Fragment but that is causing errors. I know that OnCreateView() returns a view so that must be wrong to try to create these layouts here.
I essentially have my main class which is divided into the 4 bottomNav fragments, each of which are divided into between 2-6 Fragments themselves.
Where should I be creating these layouts? Is there some other way to achieve the objective? Why is it not possible to create a layout within OnCreateView()? I'm very confused by the whole process, though the issue is probably a simple enough fix. Any help would be much appreciated.
If necessary I can provide code, though hopefully this is a simple enough issue that it is not needed.
EDIT: Below I have added the code I have so far:
MainActivity (which produces the BottomNavigation):
public class MainActivity extends AppCompatActivity {
private static final String SELECTED_ITEM = "arg_selected_item";
private BottomNavigationView mBottomNav;
private int mSelectedItem;
public static int numTabs;
public static String fragType;
public static String[] headings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBottomNav = (BottomNavigationView) findViewById(R.id.navigation);
mBottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
selectFragment(item);
return true;
}
});
MenuItem selectedItem;
if (savedInstanceState != null) {
mSelectedItem = savedInstanceState.getInt(SELECTED_ITEM, 0);
selectedItem = mBottomNav.getMenu().findItem(mSelectedItem);
} else {
selectedItem = mBottomNav.getMenu().getItem(0);
}
selectFragment(selectedItem);
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putInt(SELECTED_ITEM, mSelectedItem);
super.onSaveInstanceState(outState);
}
#Override
public void onBackPressed() {
MenuItem homeItem = mBottomNav.getMenu().getItem(0);
if (mSelectedItem != homeItem.getItemId()) {
// select home item
selectFragment(homeItem);
} else {
super.onBackPressed();
}
}
private void selectFragment(MenuItem item) {
Fragment frag = null;
// init corresponding fragment
switch (item.getItemId()) {
//USER PROFILE
case R.id.menu_home:
numTabs = 3;
fragType = getString(R.string.text_home);
headings = new String[numTabs];
headings[0] = "PROFILE HEADING 1";
headings[1] = "PROFILE HEADING 2";
headings[2] = "PROFILE HEADING 3";
frag = MenuFragment.newInstance(fragType);
break;
//DISCOVER
case R.id.menu_search:
fragType = getString(R.string.text_search);
numTabs = 6;
headings = new String[numTabs];
headings[0] = "DISCOVER HEADING 1";
headings[1] = "DISCOVER HEADING 2";
headings[2] = "DISCOVER HEADING 3";
headings[3] = "DISCOVER HEADING 4";
headings[4] = "DISCOVER HEADING 5";
headings[5] = "DISCOVER HEADING 6";
frag = MenuFragment.newInstance(fragType);
break;
//SCHEDULE
case R.id.menu_notifications:
fragType = getString(R.string.text_notifications);
numTabs = 2;
headings = new String[numTabs];
headings[0] = "SCHEDULE HEADING 1";
headings[1] = "SCHEDULE HEADING 2";
frag = MenuFragment.newInstance(fragType);
break;
//FOLLOWED
case R.id.menu_followed:
fragType = getString(R.string.text_follow);
numTabs = 3;
headings = new String[numTabs];
headings[0] = "FOLLOWED HEADING 1";
headings[1] = "FOLLOWED HEADING 2";
headings[2] = "FOLLOWED HEADING 3";
frag = MenuFragment.newInstance(fragType);
}
// update selected item
mSelectedItem = item.getItemId();
// uncheck the other items.
for (int i = 0; i< mBottomNav.getMenu().size(); i++) {
MenuItem menuItem = mBottomNav.getMenu().getItem(i);
menuItem.setChecked(menuItem.getItemId() == item.getItemId());
}
if (frag != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.container, frag, frag.getTag());
ft.commit();
}
}
}
Here's the MenuFragment class:
public class MenuFragment extends Fragment {
private static final String ARG_TEXT = "arg_text";
private String mText;
private TextView mTextView;
private Button contactButton;
private Button logoutButton;
public static Fragment newInstance(String text) {
Fragment frag = new MenuFragment();
Bundle args = new Bundle();
args.putString(ARG_TEXT, text);
frag.setArguments(args);
return frag;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View result = inflater.inflate(R.layout.fragment_menu, container, false);
ViewPager view = (ViewPager)result.findViewById(R.id.pager);
view.setAdapter(buildAdapter());
return(result);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (savedInstanceState == null) {
Bundle args = getArguments();
mText = args.getString(ARG_TEXT);
} else {
mText = savedInstanceState.getString(ARG_TEXT);
}
// initialize views
mTextView = (TextView) view.findViewById(R.id.text);
contactButton = (Button) view.findViewById(R.id.contactButton);
logoutButton = (Button) view.findViewById(R.id.logoutbutton);
// set text
mTextView.setText(mText);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(ARG_TEXT, mText);
super.onSaveInstanceState(outState);
}
private PagerAdapter buildAdapter() {
return(new MidSectionAdapter(getActivity(), getChildFragmentManager()));
}
}
And here is the MidSectionAdapter:
public class MidSectionAdapter extends FragmentPagerAdapter {
Context ctxt=null;
String title;
public MidSectionAdapter(Context ctxt, FragmentManager mgr) {
super(mgr);
this.ctxt=ctxt;
}
#Override
public int getCount() {
return(MainActivity.numTabs);
}
#Override
public Fragment getItem(int position) {
if(MainActivity.fragType.equals("MY PROFILE")) {
return(ProfileFragment.newInstance(position));
} else if(MainActivity.fragType.equals("DISCOVER")) {
return(DiscoverFragment.newInstance(position));
} else if(MainActivity.fragType.equals("SCHEDULE")) {
return(ScheduleFragment.newInstance(position));
} else {
return(UpComingFragment.newInstance(position));
}
}
#Override
public String getPageTitle(int position) {
if(MainActivity.fragType.equals("MY PROFILE")) {
title = ProfileFragment.getTitle(ctxt, position);
} else if(MainActivity.fragType.equals("DISCOVER")) {
title = DiscoverFragment.getTitle(ctxt, position);
} else if(MainActivity.fragType.equals("SCHEDULE")) {
title = ScheduleFragment.getTitle(ctxt, position);
} else {
title = UpComingFragment.getTitle(ctxt, position);
}
return(title);
}
}
And here is an example of the inner Fragment (I have reverted it back to the code I had before I was having the issue, so it doesn't do much other than display "in panel x"):
public class ScheduleFragment extends Fragment {
private static final String KEY_POSITION="position";
private TextView panelView;
private static String head;
private static int panelPosition;
String panelCheck;
static ScheduleFragment newInstance(int position) {
ScheduleFragment frag=new ScheduleFragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
static String getTitle(Context ctxt, int position) {
head = MainActivity.headings[position];
panelPosition = position;
return(head);
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.schedule_content, container, false);
panelView = (TextView) result.findViewById(R.id.testFrag);
int position=getArguments().getInt(KEY_POSITION, -1);
if(getTitle(getActivity(), position).equals(MainActivity.headings[0])) {
//MAY NOT NEED THIS NITIAL IF STATEMENT
panelCheck = "in first panel";
} else {
//tableType = "Venue";
panelCheck = "in second panel";
}
panelView.setText(panelCheck);
return(result);
}
}
By the way, you can create/add/replace n of fragments in Android Activity.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity)
//or
LinearLayout layout = getLayoutInflator.inflate(R.layout.your_activity);
setContentView(layout)
}
Similarly you can create n of Views within Activity as well as Fragment.
private LayoutInflater fragmentInflater,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.fragmentInflater = inflater;
View view = inflater.inflate(R.layout.alto_dialog, container, false);
return view;
}
Basically you can create Views/ViewGroups add/remove views at any time you want. What you want is the fragmentInflater object.
According to your screenshot req, you may need a ListView or RecyclerView with different view types. If your list is small you can simply go head with ScrollView + LinearLayout
Hope this helps.
I am working on a card swipe and card flip functionality and I am using ViewPager and fragments.
My problem is I am not able to update TextView inside fragments as I swipe the card from left to right or right to left but when I flip the card it update the UI.
I tried everything which is available over Internet but none of the soltuion is working for me.
I am following this link https://github.com/jamesmccann/android-view-pager-cards
Here is my code
public class CardContainerFragment extends Fragment {
private boolean cardFlipped = false;
static TextView textview;
public CardContainerFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_container, container, false);
LinearLayout ll = (LinearLayout)rootView.findViewById(R.id.layout);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipCard();
}
});
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
}
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
int page = CardActivity.mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = page_index + " of " + card_activity.deck_map.size();
CardActivity.tv.setText(current_page);
super.handleMessage(msg);
}
};
public void flipCard() {
Fragment newFragment = null;
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
if (cardFlipped) {
newFragment = new CardFrontFragment();
} else {
newFragment = new CardBackFragment();
}
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
cardFlipped = !cardFlipped;
}
public static class CardFrontFragment extends Fragment {
public CardFrontFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card, container, false);
textview = (TextView)rootView.findViewById(R.id.card_front);
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
String complete_text = card_front_string +" \n \n + \n Tap now to flip this card.";
textview.setText(complete_text);
return rootView;
}
}
public static class CardBackFragment extends Fragment {
public CardBackFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_back, container, false);
TextView textview = (TextView)rootView.findViewById(R.id.card_back);
textview.setMovementMethod(new ScrollingMovementMethod());
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
String deck_data = card_activity.deck_map.get(card_front_string);
textview.setText(deck_data);
return rootView;
}
}
Here is my adapter code
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.card_example);
tv = (TextView)findViewById(R.id.tv_card_number);
tv1 = (TextView)findViewById(R.id.tv_card_index);
FragmentManager m = getFragmentManager();
CardPagerAdapter adapter = new CardPagerAdapter(m);
index = getIntent().getStringExtra("index");
card_activity.cardCounter = Integer.parseInt(index);
int count = card_activity.cardCounter;
int final_count = count+1;
String current_page = final_count+" of "+card_activity.deck_map.size();
//CardActivity.tv.setText(current_page);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
// mViewPager.setAllowedSwipeDirection(CustomViewPager.SwipeDirection.all);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(card_activity.cardCounter);
//mViewPager.setOffscreenPageLimit(1);
//mViewPager.setOnPageChangeListener(new pagechangelistener())
//Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
}catch(Exception e){
e.printStackTrace();
}
}
public class CardPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
public CardPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
mViewPager.setOffscreenPageLimit(0);
int page = mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = " of " + card_activity.deck_map.size();
tv.setText(current_page);
tv1.setText(String.valueOf(page_index));
CardContainerFragment cardContainerFragment = new CardContainerFragment();
cardContainerFragment.current_index_front = page;
cardContainerFragment.current_index_back = page;
String card_front_string = card_activity.arraylst.get(page);
CardContainerFragment.complete_text_front = card_front_string +" \n \n + \n Tap now to flip this card.";
Bundle b = new Bundle();
b.putInt("index",page);
CardContainerFragment.complete_text_back = card_activity.deck_map.get(card_front_string);
cardContainerFragment.setArguments(b);
return cardContainerFragment;
}
#Override
public int getCount() {
int len = card_activity.deck_map.size();
return len;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Please let me know what I am doing wrong here.
Thanks in advance
Finally I am able to do this with some efforts.
After searching, I get to know that getItems (The method in CardPagerAdapter) is called two times because Android creates one extra fragments for smooth transition and I was sending or getting wrong position of fragments from getItems.
By letting the android to create one extra fragment and by sending correct position I am able to solve this issue.
Here is my updated code
public class CardActivity extends android.support.v4.app.FragmentActivity {
public TextView tv;
public static String index=null;
public static ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.card_example);
tv = (TextView)findViewById(R.id.tv_card_number);
FragmentManager m = getFragmentManager();
CardPagerAdapter adapter = new CardPagerAdapter(m);
index = getIntent().getStringExtra("index");
card_activity.cardCounter = Integer.parseInt(index);
int count = card_activity.cardCounter;
int final_count = count+1;
String current_page = final_count+" of "+card_activity.deck_map.size();
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setOffscreenPageLimit(0);
mViewPager.setAdapter(adapter);
mViewPager.setCurrentItem(card_activity.cardCounter);
String current_page_temp =final_count+" of " + card_activity.deck_map.size();
tv.setText(current_page_temp);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Log.e("aaa",position+"");
String current_page = position+1 + " of " + card_activity.deck_map.size();
tv.setText(current_page);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}catch(Exception e){
e.printStackTrace();
}
}
public class CardPagerAdapter extends android.support.v13.app.FragmentStatePagerAdapter {
public CardPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
CardContainerFragment cardContainerFragment = new CardContainerFragment();
Bundle b = new Bundle();
b.putInt("index",i);
cardContainerFragment.setArguments(b);
return cardContainerFragment;
}
#Override
public int getCount() {
int len = card_activity.deck_map.size();
return len;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
}
==================================================================
public class CardContainerFragment extends Fragment {
private boolean cardFlipped = false;
int current_index=0;
static int pos = 0;
public CardContainerFragment() {
/*setHasOptionsMenu(true);*/
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_card_container, container, false);
LinearLayout ll = (LinearLayout)rootView.findViewById(R.id.layout);
rootView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flipCard();
}
});
pos = getArguments().getInt("index");
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment().newInstance(pos))
.commit();
card_activity.tempCounter = card_activity.tempCounter+1;
return rootView;
}
public void flipCard() {
Fragment newFragment = null;
CardFrontFragment cardFrontFragment = null;
CardBackFragment cardBackFragment = null;
if (cardFlipped) {
newFragment = CardFrontFragment.newInstance(CardActivity.mViewPager.getCurrentItem());
} else {
newFragment = cardBackFragment.newInstance(CardActivity.mViewPager.getCurrentItem());
}
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
cardFlipped = !cardFlipped;
}
public static class CardBackFragment extends Fragment {
public CardBackFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView_back = inflater.inflate(R.layout.fragment_card_back, container, false);
TextView textview_back = (TextView)rootView_back.findViewById(R.id.card_back);
textview_back.setMovementMethod(new ScrollingMovementMethod());
String text = getArguments().getString("back_text");
textview_back.setText(text);
return rootView_back;
}
static CardBackFragment newInstance(int position) {
CardBackFragment cardBackFragment = new CardBackFragment();
Bundle args = new Bundle();
String card_front_string = card_activity.arraylst.get(position);
String text = card_activity.deck_map.get(card_front_string);
args.putString("back_text", text);
cardBackFragment.setArguments(args);
return cardBackFragment;
}
}
public static class CardFrontFragment extends Fragment {
public CardFrontFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView_front = null;
rootView_front = inflater.inflate(R.layout.fragment_card, container, false);
TextView textview_front = (TextView)rootView_front.findViewById(R.id.card_front);
String text = getArguments().getString("front_text");
textview_front.setText(text);
return rootView_front;
}
static CardFrontFragment newInstance(int position) {
CardFrontFragment cardFrontFragment = new CardFrontFragment();
Bundle args = new Bundle();
String card_front_string = card_activity.arraylst.get(position);
String text = card_front_string +" \n \n + \n Tap now to flip this card.";
args.putString("front_text", text);
cardFrontFragment.setArguments(args);
return cardFrontFragment;
}
}
}
As #david-rawson says
Don't use static fields CardActivity.mViewPager. See https://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
Reason for this is that the ViewPager might/will create the views of your fragments before they are displayed to ensure you get that smooth animation that people love ViewPagers for. So the mViewPager calls a number of fragments createView() function at the same time, and at that time the mViewPager has an index for .getCurrentItem() which goes to the CardContainer on the page being viewed.
A better option would be for you to pass CardContainerFragment a String argument with the value for "completeText" which you want it to display whenever it creates either CardBackFragment or CardFrontFragment.
Go through this for more details.
You just have to set data to text view which is used in CardFrontFragment.
Here when ever a swipe happens onCreateView() of CardContainerFragment is called.
You are adding CardFrontFragment every time when onCreateView() is called. you need to use text view of CardFrontFragment instead of using textview of activity.
Just replace CardActivity.tv.setText(current_page);
with textView.setText(current_page);
Make sure the textview you have used in CardFrontFragment is available at class level.
you are using static fragments so textview must be static.
private static TextView textView=null;
Hope this will work for you :)
Have you tried this:
tv.post(new Runnable() {
#Override
public void run() {
CardActivity.tv.setText(current_page);
}
});
I did something similar wihtin my App, and I manage the display of my TextView into the OnCreateView, with a switch case.
I tried to implent your code but did not have all your materials (like custom animator).
You should then try something like that:
public class CardContainerFragment extends AppCompatActivity {
private boolean cardFlipped = false;
static TextView textview;
/*public CardContainerFragment() {
setHasOptionsMenu(true);
}*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activity_name);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
/*
The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
flipCard();
#Override
public void onPageSelected(int position) {
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
}
#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_welcome, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Initializing data
Context context = getContext();
View rootView = inflater.inflate(R.layout.fragment_card, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.txtView);
int fragment = getArguments().getInt(ARG_SECTION_NUMBER);
switch (fragment)
{
case 1: //front card
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
Log.e("current Item",CardActivity.mViewPager.getCurrentItem()+"");
String complete_text = card_front_string +" \n \n + \n Tap now to flip this card.";
textview.setText(complete_text);
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
case 2: //back card
TextView textview = (TextView)rootView.findViewById(R.id.card_back);
textview.setMovementMethod(new ScrollingMovementMethod());
String card_front_string = card_activity.arraylst.get(CardActivity.mViewPager.getCurrentItem());
String deck_data = card_activity.deck_map.get(card_front_string);
textview.setText(deck_data);
getChildFragmentManager()
.beginTransaction()
.add(R.id.container, new CardFrontFragment())
.commit();
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
return rootView;
default:
return rootView;
}
}
}
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
int page = CardActivity.mViewPager.getCurrentItem();
int page_index = page+1;
String current_page = page_index + " of " + card_activity.deck_map.size();
CardActivity.tv.setText(current_page);
super.handleMessage(msg);
}
};
public void flipCard() {
Message msg = handler.obtainMessage();
msg.arg1 = 1;
handler.sendMessage(msg);
getChildFragmentManager()
.beginTransaction()
.setCustomAnimations(
R.animator.card_flip_right_in, R.animator.card_flip_right_out,
R.animator.card_flip_left_in, R.animator.card_flip_left_out)
.replace(R.id.container, newFragment)
.commit();
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
}
return null;
}
}
The textView is displayed on your page, and when selecting the change, the content of your textview will be changed.
In android, how to have menu onClick start new fragment? i'm creating Fragment inside tabLayout? How to set menu click start new fragment? See my code, how can I display a new fragment when clicked from menu items?
public class NetworkFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private TabLayout tabLayout;
private ViewPager viewPager;
public NetworkFragment() {
// Required empty public constructor
}
public static NetworkFragment newInstance(String param1, String param2) {
NetworkFragment fragment = new NetworkFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.fragment_network, container, false);
ViewPager viewPager = (ViewPager)view. findViewById(R.id.viewpager);
final PagerAdapter pagerAdapter =
new PagerAdapter(getChildFragmentManager(), getContext());
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
final TabLayout tabLayout = (TabLayout)view. findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
final ImageView menuView = (ImageView) view.findViewById(R.id.menuView);
menuView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
PopupMenu popup = new PopupMenu(getContext(), v);
popup.getMenuInflater().inflate(R.menu.network_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
//Toast.makeText(getContext(), "You Clicked : " + item.getTitle(), Toast.LENGTH_SHORT).show();
if(item.getItemId() ==R.id.allLinks){
//new Fragment
}
else if(item.getItemId() ==R.id.networkFavourites){
Toast.makeText(getContext(), "networkFavourites" , Toast.LENGTH_SHORT).show();
}
else if(item.getItemId() ==R.id.CompanyLinks){
Toast.makeText(getContext(), "CompanyLinks" , Toast.LENGTH_SHORT).show();
}
else if(item.getItemId() ==R.id.Company){
Toast.makeText(getContext(), "CompanyLinks" , Toast.LENGTH_SHORT).show();
}
else if(item.getItemId() ==R.id.Industry){
Toast.makeText(getContext(), "CompanyLinks" , Toast.LENGTH_SHORT).show();
}
return true;
}
});
popup.show();
}
});
return view;
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = getResources().getStringArray(R.array.network_tab);
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new MylinksFragment();
case 1:
return new MyGroupsFragment();
case 2:
return new MyInvitationsFragment();
case 3:
return new MyMessagesFragment();
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(getContext()).inflate(R.layout.tab_text_layout, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
Actually your question is not clear. But as per my understanding you want to display a new fragment on menu click. To do so you have to write a code like
for API level 2.2 and above and when you are using a v4 support jar
Fragment fragment = new YourFragmentName();// the fragment which you ant to display
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container,fragment).commit();
for API level 3.0 and above and when you are not using a v4 support jar
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
By this way you can replace a fragment or display a new fragment.
Hi I have problem with backstack. Here is the list of my fragments:
A - Dashboard Fragment
B - NewOrders Fragment
C - Product Fragment
Backstack is working when I navigate A -> B (back pressed) -> A - this is OK
But in this situation A -> B -> C (back pressed) -> B (blank fragment) (back pressed) -> A (blank fragment)
Dashboard Fragment:
public class DashboardFragment extends Fragment implements View.OnClickListener{
public static final String TAG = DashboardFragment.class.getSimpleName();
ImageButton scan;
ImageButton paragon;
ImageButton cart;
ImageButton orders;
public DashboardFragment() { }
public static DashboardFragment newInstance(){
return new DashboardFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "Fragment active: ************************************************************");
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_dashboard, container, false);
scan = (ImageButton) rootView.findViewById(R.id.scanButton);
paragon = (ImageButton) rootView.findViewById(R.id.paragonButton);
cart = (ImageButton) rootView.findViewById(R.id.cartButton);
orders = (ImageButton) rootView.findViewById(R.id.newOrdersButton);
scan.setOnClickListener(this);
paragon.setOnClickListener(this);
cart.setOnClickListener(this);
orders.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View v) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
switch(v.getId()){
case R.id.paragonButton:
ft.replace(R.id.container, ReceiptFragment.newInstance());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
break;
case R.id.scanButton:
ft.replace(R.id.container, ProductsFragment.newInstance());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
break;
case R.id.cartButton:
ft.replace(R.id.container, CartFragment.newInstance());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
break;
case R.id.newOrdersButton:
ft.replace(R.id.container, NewOrdersFragment.newInstance());
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
break;
default:
return;
}
ft.addToBackStack(null);
ft.commit();
}
}
NewOrdersFragment:
public class NewOrdersFragment extends Fragment implements ExpandableListView.OnChildClickListener{
private static final String TAG = NewOrdersFragment.class.getSimpleName();
List<JsonNewOrder> newOrderList;
ExpandableListView listView;
public NewOrdersFragment() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "Fragment active: ************************************************************");
View rootView = inflater.inflate(R.layout.fragment_new_orders, container, false);
newOrderList = new ArrayList<>();
listView = (ExpandableListView) rootView.findViewById(R.id.expandableListView);
listView.setOnChildClickListener(this);
listView.setAdapter(new ExpandableListAdapter(getActivity(), newOrderList));
return rootView;
}
public static Fragment newInstance() {
return new NewOrdersFragment();
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Long productId = ((JsonOrder)parent.getExpandableListAdapter().getChild(groupPosition, childPosition)).getBarcode();
ProductFragment fragment = ProductFragment.newInstance(String.valueOf(productId));
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
ft.replace(R.id.container, fragment);
ft.addToBackStack(null);
ft.commit();
return true;
}
#Override
public void onResume() {
super.onResume();
if(NetworkHelper.isConnected(getActivity())) new JSONTask().execute();
}
private class JSONTask extends AsyncTask<Void, Void, String>{
....
}
}
ProductFragment:
public class ProductFragment extends Fragment {
private static final String ARG_EAN = "ean";
private static final String TAG = ProductFragment.class.getSimpleName();
ImageView thumbnail;
private String ean;
public static ProductFragment newInstance(String ean) {
ProductFragment fragment = new ProductFragment();
Bundle args = new Bundle();
args.putString(ARG_EAN, ean);
fragment.setArguments(args);
return fragment;
}
public ProductFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
ean = getArguments().getString(ARG_EAN);
}
}
private void setImage(Bitmap image){
thumbnail.setImageBitmap(image);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(TAG, "Fragment active: ************************************************************");
View rootView = inflater.inflate(R.layout.fragment_product, container, false);
thumbnail = (ImageView) rootView.findViewById(R.id.thumbnail);
TextView gender = (TextView) rootView.findViewById(R.id.gender_text);
TextView category = (TextView) rootView.findViewById(R.id.category_text);
TextView name = (TextView) rootView.findViewById(R.id.name_text);
TextView size = (TextView) rootView.findViewById(R.id.size_text);
TextView color = (TextView) rootView.findViewById(R.id.color_text);
ImageView color_thumb = (ImageView) rootView.findViewById(R.id.color_thumbnail);
TextView price = (TextView) rootView.findViewById(R.id.price_text);
String [] projection = Product.getProjection();
String selection = Product.C_ID + "=?";
String [] selectionArgs = {ean};
Cursor cursor = getActivity().getContentResolver().query(Uri.parse(Product.CONTENT_URI + "/" + ean), projection, selection, selectionArgs, null);
if(cursor.moveToFirst()) {
if (!cursor.isNull(cursor.getColumnIndex(Product.C_GENDER_NAME)))
gender.setText(cursor.getString(cursor.getColumnIndex(Product.C_GENDER_NAME)));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_CATEGORY_NAME)))
category.setText(cursor.getString(cursor.getColumnIndex(Product.C_CATEGORY_NAME)));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_PRODUCT_NAME)))
name.setText(cursor.getString(cursor.getColumnIndex(Product.C_PRODUCT_NAME)));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_PRICE)))
price.setText(cursor.getString(cursor.getColumnIndex(Product.C_PRICE)) + " PLN");
if (!cursor.isNull(cursor.getColumnIndex(Product.C_COLOR_NAME)))
color.setText(cursor.getString(cursor.getColumnIndex(Product.C_COLOR_NAME)));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_COLOR_HEX)))
color_thumb.setBackgroundColor(Color.parseColor(cursor.getString(cursor.getColumnIndex(Product.C_COLOR_HEX))));
if (!cursor.isNull(cursor.getColumnIndex(Product.C_SIZE_NAME)))
size.setText(cursor.getString(cursor.getColumnIndex(Product.C_SIZE_NAME)));
String [] stockProjection = {Stock.T_NAME + "." + Stock.C_ID, Stock.T_NAME + "." + Stock.C_NAME, ProductsStocks.T_NAME + "." + ProductsStocks.C_AMOUNT};
Cursor stockCursor= getActivity().getContentResolver().query(Uri.parse(ProductsStocks.CONTENT_URI + "/" + cursor.getString(0)), stockProjection, null, null, null);
if(cursor.moveToFirst()){
ListView listView = (ListView) rootView.findViewById(R.id.stock_list);
String [] from = {Stock.C_NAME, ProductsStocks.C_AMOUNT};
int[] to = {R.id.row_stock_name, R.id.row_stock_qty};
listView.setAdapter(new SimpleCursorAdapter(getActivity(), R.layout.row_stock_item, stockCursor, from, to));
}
//stockCursor.close();
if(NetworkHelper.isConnected(getActivity())) new DownloadImage().execute(cursor.getString(cursor.getColumnIndex(Product.C_THUMB_URI)));
}else{
getFragmentManager().beginTransaction().replace(R.id.productContainer, new NoProductFragment()).commit();
}
cursor.close();
return rootView;
}
I'm assuming that you are already handling the onBackPressed() properly and using the popBackStack() method to jump back to the previous fragment.
A fragment should never replace itself. You will always run into problems. Instead, tell the activity that you want to be replaced by another fragment. Something like this:
interface AppEventListener{
void onNewOrdersSelected();
void onDashboardSelected();
}
class MainActivity extends Activity implements AppEventListener{
...
void onNewOrdersSelected(){
//replace fragment with NewOrders fragment
}
void onDashBoardSelected(){
//replace fragment with Dashboard fragment
}
...
#Override
public void onBackPressed() {
FragmentManager manager = getFragmentManager();
int count = manager.getBackStackEntryCount();
if(count==0) {
super.onBackPressed();
}else{
manager.popBackStack();
}
}
}
class DashBoardFragment extends Fragment{
...
public void OnClick(View view){
AppEventListener listener = (AppEventListener) getActivity();
...
case(R.id.NewOrdersButton):
listener.onNewOrdersSelected();
...
}
}