Android restore from backstack give me blank fragment - android

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();
...
}
}

Related

Open a fragment from a fragment's fragment?

I have a Fragment with a ListView. When I click one of the item, a new Fragment is opened, and from this Fragment I want to open a new Fragment witha a Button.
I try to write the code, but it's a mess. When a click the Button, the program is crashed.
Should I use another way? I call the third Fragment like the second
Activity:
public class Grade extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceSt
ate);
setContentView(R.layout.activity_grade);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
new Objectlist()).commit();
}
}
private BottomNavigationView.OnNavigationItemSelectedListener navListener =
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
Fragment selectedFragment = null;
switch (item.getItemId()) {
case R.id.nav_tantargylista:
selectedFragment = new Objectlist();
break;
case R.id.nav_dolgozatlista:
selectedFragment = new Examlist();
break;
}
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_list,
selectedFragment).commit();
return true;
}
};
}
1st Fragment:
public class Objectlist extends Fragment {
View v;
DB mydb;
ListView listView;
private String teszt;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_objectlist, container, false);
listView = (ListView)v.findViewById(R.id.Gradeview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Nincs jegyek hozzáadva", Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()) {
thelist.add(data.getString(0));
ListAdapter listadapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, thelist);
listView.setAdapter(listadapter);
}
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
teszt = thelist.get(i);
Bundle bundle = new Bundle();
String jegyAtlag="0";
Cursor data = mydb.JegyekAtlaga(teszt);
while (data.moveToNext()) jegyAtlag=data.getString(0);
String jegyDarab="0";
data = mydb.JegyekDarabszama(teszt);
while (data.moveToNext()) jegyDarab=data.getString(0);
if (jegyAtlag.equals("") || jegyDarab.equals(""))
else {
bundle.putString("Tantárgy átlaga", jegyAtlag);
bundle.putString("Tantárgy darabszáma", jegyDarab);
TextView jegyekHeader = (TextView) v.findViewById(R.id.header);
jegyekHeader.setText(teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
ListView listaNezet = (ListView) v.findViewById(R.id.Gradeview);
listaNezet.setVisibility(View.GONE);
FragTan.commit();
}
}
}
);
}
return v;
}
}
2nd Fragment:
public class targyAdatok extends Fragment {
public targyAdatok() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_targy_adatok, container, false);
Button elemzes = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.targyAdatok,jegyekAllando);
FragTan.commit();
}
});
return v;
}
}
3rd Fragment:
public class jegyekAllando extends Fragment {
DB mydb;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jegyek_allando, container, false);
Bundle bundle = getArguments();
String jegyAtlagSt = bundle.getString("Tantárgy átlaga");
String jegyDarabSt = bundle.getString("Tantárgy darabszáma");
return rootView;
}
}
I solved my problem. The problem was that a replaced the wrong fragment. Every time I have to replace the Activity's Fragment.

How to get value from childfragment to parentfragment?

I am frustrated.
i want to get value from child fragment to parent fragment
i had tries many method.
interface, viewModel, sharedpreferences but no one work.
I had follow this method
but it doesn't work for me.
here my code parent fragment:
public class Chart_Fragment extends Fragment
implements Product_Fragment.pf_interface {
String dt;
TextView tv;
public Chart_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.chart_fragment, container, false);
// create product_fragment as childfragment
FragmentManager fm = getChildFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
Product_Fragment product_fragment = new Product_Fragment();
ft.replace(R.id.fl_two, new Product_Fragment());
ft.commit();
return v;
}
public void onViewCreated(View v, Bundle savedInstanceState){
super.onViewCreated(v,savedInstanceState);
tv = (TextView)v.findViewById(R.id.rcv);
}
#Override
public void data(String d) {
FragmentManager fragmentManager = getChildFragmentManager();
Product_Fragment product_fragment =
(Product_Fragment)fragmentManager.findFragmentByTag("data");
if(product_fragment != null){
String dt = d;
tv.setText(dt);
}
}
}
and my childfragment is :
public class Product_Fragment extends Fragment {
private pf_interface pf;
public Product_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.product_fragment, container, false);
Button b = (Button)v.findViewById(R.id.btn_sender);
b.setOnClickListener(new btnClick());
return v;
}
public void onAttachToParentFragment(Fragment fragment){
try {
pf = (pf_interface)fragment;
}catch (ClassCastException e){
throw new ClassCastException(
fragment.toString()+ "must implement pf_interface"
);
}
}
public void onCreate(Bundle savedInstanceState){
Log.i(TAG, "onCreate");
super.onCreate(savedInstanceState);
onAttachToParentFragment(getParentFragment());
}
private class btnClick implements View.OnClickListener{
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.btn_sender:
if(pf != null){
pf.data("button click interface");
}break;
}
}
}
public interface pf_interface{
void data(String d);
}
}
textview on parent fragment didn't show the string d ("button click interface")from child fragment
Why you're checking for child fragment in callback on your parent fragment ?
#Override
public void data(String d) {
FragmentManager fragmentManager = getChildFragmentManager();
Product_Fragment product_fragment =
(Product_Fragment)fragmentManager.findFragmentByTag("data");
if(product_fragment != null){ // Why to check for child fragment nullability?
String dt = d;
tv.setText(dt);
}
}
You can directly use like this:
#Override
public void data(String d) {
tv.setText(d);
}
Note: on any certain scenario if any of object is null, your callback won't be executed. You've already check for null reference.

Produce a variable amount of layouts programmatically within nested fragment?

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.

Not able to Update fragments text while swaping cards

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.

android value passing adapter to fragment

I am developing an app for displaying images and text. When clicking on the item it goes to another fragment. The listing showing is correct but when I click on the item it does not go to fragment. I am using recycler adapter to listing the items. The code is shown below.
public class MyRecyclerAdapter extends RecyclerView.Adapter < MyRecyclerAdapter.MyViewHolder > {
String categoryId;
private List < NewsFeeds > feedsList;
private Context context;
private LayoutInflater inflater;
public MyRecyclerAdapter(Context context, List < NewsFeeds > feedsList) {
this.context = context;
this.feedsList = feedsList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.singleitem_recyclerview_categories, parent, false);
return new MyViewHolder(rootView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NewsFeeds feeds = feedsList.get(position);
//Pass the values of feeds object to Views
holder.title.setText(feeds.getName());
//holder.categoryId.setText(feeds.getCategory_id());
categoryId = feeds.getCategory_id();
Log.d("LOGTAG", "id : " + categoryId);
holder.imageview.setImageUrl(feeds.getImgURL(), NetworkController.getInstance(context).getImageLoader());
Log.d("LOGTAG", "feeds.getFeedName():" + feeds.getName());
}
#Override
public int getItemCount() {
return feedsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private NetworkImageView imageview;
private CardView cardView;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title_view);
//categoryId = (TextView) itemView.findViewById(R.id.content_view);
// Volley's NetworkImageView which will load Image from URL
imageview = (NetworkImageView) itemView.findViewById(R.id.thumbnail);
cardView = (CardView) itemView.findViewById(R.id.card_view);
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
Log.d("LOGTAG", categoryId);
Log.d("LOGTAG", "clicked");
//newInstance(categoryId);
}
});
}
}
}
I want to send value to SubCategoryFragment and start SubCategoryFragment.
my SubCategoryFragment code
public class SubCategoryFragment extends Fragment {
public SubCategoryFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_sub_category, container, false);
//Bundle bundle = this.getArguments();
Bundle args = getArguments();
//String categoryId = args.getString("index");
String categoryId = getArguments().getString("category_id");
//String categoryId = getArguments().getString("category_id");
TextView textView = (TextView) rootView.findViewById(R.id.label);
textView.setText(categoryId);
// Inflate the layout for this fragment
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
}
Please help me
From Adapter you send data with intent as:
Fragment fragment = new tasks();
FragmentManager fragmentManager = context.getSupportFragmentManager(); // this is basically context of the class
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Bundle bundle=new Bundle();
bundle.putString("name", "From Adapter"); //key and value
//set Fragmentclass Arguments
fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
and in Fragment onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
String strtext=getArguments().getString("name"); //fetching value by key
return inflater.inflate(R.layout.fragment, container, false);
}
In your onClickListener();
Fragment fragment = new tasks();
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, fragment);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
Change R.id.content_frame with your fragment
You have made one mistake in your onClick method.
When you want to go one fragment to other fragment, you have to transaction the fragment using FragmentTransaction.class
Check out below code.
Edit :
SecondFragment fragment = new SecondFragment();
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragment);
fragmentTransaction.hide(currentfragment) fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
Edit :
Just put below code in your RecyclerViewAdapter method onBindViewHolder.
holder.cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragobj);
fragmentTransaction.hide(currentfragment);
fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
//newInstance(categoryId);
}
});
EDIT :
public class MyRecyclerAdapter extends RecyclerView.Adapter<MyRecyclerAdapter.MyViewHolder> {
String categoryId;
private List<NewsFeeds> feedsList;
private Context context;
private LayoutInflater inflater;
private Fragment currentFragment;
public MyRecyclerAdapter(Context context, List<NewsFeeds> feedsList, final Fragment currentFragment) {
this.context = context;
this.feedsList = feedsList;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.currentFragment = currentFragment;
}
#Override
public MyRecyclerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View rootView = inflater.inflate(R.layout.singleitem_recyclerview_categories, parent, false);
return new MyViewHolder(rootView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
NewsFeeds feeds = feedsList.get(position);
//Pass the values of feeds object to Views
holder.title.setText(feeds.getName());
//holder.categoryId.setText(feeds.getCategory_id());
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
FragmentManager fragmentManager = currentfragment.getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.content_frame, fragobj);
fragmentTransaction.hide(currentfragment);
fragmentTransaction.addToBackStack(currentfragment.getclass().getsimplename());
fragmentTransaction.commit();
//newInstance(categoryId);
}
});
}
#Override
public int getItemCount() {
return feedsList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder {
private TextView title;
public MyViewHolder(View itemView) {
super(itemView);
title = (TextView) itemView.findViewById(R.id.title_view);
}
}
}
Replace your onclick listener with this.
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(context, "Clicked", Toast.LENGTH_SHORT).show();
// I want to send values to SubCategoryFragment and start SubCategoryFragment
Bundle args = new Bundle();
args.putString("category_id", categoryId);
//set Fragmentclass Arguments
SubCategoryFragment fragobj = new SubCategoryFragment();
fragobj.setArguments(args);
Log.d("LOGTAG", categoryId);
Log.d("LOGTAG", "clicked");
//put this in your code
FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.SubCategoryFragment, fragobj);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.commit();
//newInstance(categoryId);
}
});

Categories

Resources