Putting a SwipeView inside a Fragment? - java

Problem: Having a SwipeView inside a Fragment (So when the Fragment is active you can cycle through some other fargments)
What I tried: I tried implementing it the same way you would implement it normally but in the fragment:
NORMAL WAY:
public class MainActivity extends FragmentActivity {
ViewPager viewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewPager);
SwipeAdapter swipeAdapter = new SwipeAdapter(getSupportFragmentManager());
viewPager.setAdapter(swipeAdapter);
}
}
THE WAY I TRIED IT WITH A FRAGMENT:
public class SecondFragment extends Fragment {
ViewPager viewPager;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_first, container, false);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
viewPager = view.findViewById(R.id.VIEWPAGER);
SwipeAdapter swipeAdapter = new SwipeAdapter(getChildFragmentManager());
viewPager.setAdapter(swipeAdapter);
}
}
THE ERROR: It returns a "null object reference" when I try to set the adapter (I'm guessing it has problems with the FragmentManager)
ADAPTER FOR BOTH EXAMPLES:
public class SwipeAdapter extends FragmentStatePagerAdapter {
public SwipeAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new PageFragment();
Bundle bundle = new Bundle();
bundle.putInt("count", position+1);
fragment.setArguments(bundle);
return fragment;
}
#Override
public int getCount() {
return 5;
}
}
In the Main Activity I set up so you can switch fragments with buttons, and what I'm trying to implement in the second fragment is to be able to swipe through fragments with SwipeView
MAIN ACTIVITY CODE:
public class MainActivity extends AppCompatActivity {
Button firstFragment, secondFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firstFragment = (Button) findViewById(R.id.firstFragment);
secondFragment = findViewById(R.id.secondFragment);
firstFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFragment(new FirstFragment());
}
});
secondFragment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadFragment(new SecondFragment());
}
});
}
private void loadFragment(Fragment fragment) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, fragment);
fragmentTransaction.commit();
}
}
I don't know if this is the right way to do it, but if anyone has a way to make this work any help would be appreciated, thanks!

You cannot set the adapter because your view has not been created yet.
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? = inflater.inflate(R.layout.fragment_first, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewPager = view.findViewById(R.id.viewPager) as ViewPager
swipeAdapter = SwipeAdapter(childFragmentManager)
...
}

Related

How to setOnclick Listener to image in fragment

I have image in my fragment. I want click on the picture and... for example change the fragment. I have found the same topic How to setOnclick Listener to button in fragment but ClickListner does not work.
I have tried make the same code in Activity and onClickListner is work, but in the frame it does not work.
Below my code in the Fragment.
public class Fragment2 extends Fragment {
ImageView imageView;
MyListner listner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View getview = inflater.inflate(R.layout.fragment_2, container, false);
imageView = (ImageView) getview.findViewById(R.id.imageView1);
imageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listner.callback();
}
});
return inflater.inflate(R.layout.fragment_2, container, false);
}
Below my interface
public interface MyListner {
public void callback();}
Below my MainActivity
public class MainActivity extends AppCompatActivity implements MyListner {
Fragment2 fragment2;
Fragment1 fragment1;
ImageView imageViewMain;
ImageView imageViewFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fragment2 = new Fragment2();
setContentView(R.layout.activity_main);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();//начало транзакции объекта
ft.replace(R.id.container, fragment2);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
#Override
public void callback() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();//начало транзакции объекта
ft.replace(R.id.container, fragment1);
ft.addToBackStack(null);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}}
Please, let me know where is the problem?
It seems you are inflating your fragment's view twice. Instead of this you need to return the view which you have already inflated as a result of your onCreateView inside Fragment2.
Try changing
return inflater.inflate(R.layout.fragment_2, container, false);
to
return getview;

Problem with fragment that uses a method of another class, Android Studio

I have two different classes that i will show
public class Iniziale extends AppCompatActivity {
Button credits,gioca,giocamyquiz,newquestion;
TextView testo;
public boolean whatgame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_iniziale);
gioca = findViewById(R.id.gioca);
giocamyquiz = findViewById(R.id.giocamyquiz);
newquestion= findViewById(R.id.newquestions);
whatgame=true;
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
gioca.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
whatgame=true;
Intent homeIntent = new Intent(Iniziale.this, MainActivity.class);
startActivity(homeIntent);
finish();
}
});
giocamyquiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
whatgame=false;
Intent homeIntent = new Intent(Iniziale.this, MainActivity.class);
startActivity(homeIntent);
finish();
}
});
}
public boolean FragmentMethod() {
return whatgame;
}
}
and a fragment
public class MainActivityFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_main_activity, container, false);
what=true; //sceglie a quale quiz giocare
what=((Iniziale) getActivity()).FragmentMethod();
I want use method FragmentMethod() in my Fragment class because I need the value of the whatgame variable.
How the code is write it doesn't work.
In Iniziale class I have 2 buttons and based of what button i click I will modify my whatgame variable and modify some parameters in fragment class

Listen DialogFragment dismiss event from ViewPager Fragment

There are lot of (duplicate) questions and answers are available, I went through almost all of them and failed. On reference of this question, I made some changes recently.
Brief : In my app, MainActivity holds Fragment View Pager and FrangmentA,B and C. FrangmentA Shows a DialogFragment CDialog onClik. After dismissing CDialog I need to Call FragmentA's doReload() which is not happening here.
MainActivity
protected void onCreate(Bundle savedInstanceState){
...
mSectionsPageAdapter = new FragmentAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
setupViewPager(mViewPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
int defaultValue = 0;
int page = getIntent().getIntExtra("One", defaultValue);
mViewPager.setCurrentItem(page);
}
private void setupViewPager(ViewPager viewPager)
{
FragmentAdapter adapter = new
FragmentAdapter(getSupportFragmentManager());
adapter.addFragment(new FragmentA(), "FragA");
adapter.addFragment(new FragmentB(), "FragB");
adapter.addFragment(new FragmentC(), "FragC");
viewPager.setAdapter(adapter);
}
FragmentA
public class FragmentA extends Fragment implements CDialog.Dismissed{
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
...
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
FragmentManager fm = getActivity().getFragmentManager();
DialogFragment f = new CDialog();
f.show(fm, "CDialog");
}
});
#Override
public void dialogDismissed() {
Log.e(DFD_1, "dialogDismiss Called" );// <-- This is not working*
doReload();
}
}
And CDialogue
public class CDialog extends DialogFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
....
return v;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
...
dfd_1.setOnClickListener(
new View.OnClickListener() {
public void onClick(View v) {
getDialog().dismiss(); //<--when this happens*
}
});
}
#Override
public void onDismiss(DialogInterface dialog) {
if (getActivity() != null && getActivity() instanceof Dismissed) {
((Dismissed) getActivity()).dialogDismissed();
}
super.onDismiss(dialog);
}
public interface Dismissed {
public void dialogDismissed(); //<-- FragmentA implements this
}
}
You can always have direct callback to your Fragment itself.
First step, is to set targetFragment using setTargetFragment():
DialogFragment#setTargetFragment(Fragment fragment, int requestCode);
I do it this way:
public void showDialogFragment(Fragment targetFragment, AppCompatDialogFragment appCompatDialogFragment, int requestCode) {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
appCompatDialogFragment.setTargetFragment(targetFragment, requestCode);
fragmentTransaction.add(appCompatDialogFragment, appCompatDialogFragment.getClass().getSimpleName());
fragmentTransaction.commitAllowingStateLoss();
}
and then call to this method to open dialog fragment as:
public static final int RC_CDIALOG = 111;
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showDialogFragment(FragmentA.this, new CDialog(), RC_CDIALOG);
}
});
Then, in your DialogFragment's onDismissListener(), have some code like below:
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if (getTargetFragment() instanceof FragmentA)
((FragmentA) getTargetFragment()).doReload();
}
What you did this way is:
Show Dialog Fragment "CDialog" along with telling it that your target fragment is "FragmentA" whose reference you can use incase you have something to do with it. In your case you had to call doReload();

Android fragments looks overhead

MainActivity has 2 buttons and when I click the buttons I want 2 fragments to appear in the same page.But when I click on itsMeContact button, it comes up, but when I click on the PhoneContact button, I overwrite the other one.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button itsMeContact,phoneContact;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itsMeContact= (Button) findViewById(R.id.its_me_contact);
phoneContact= (Button) findViewById(R.id.phone_contact);
itsMeContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
UserFragment userFragment = new UserFragment();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.frame_layout, userFragment, "userFragment");
transaction.commit();
}
});
phoneContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
FragmentB fragmentB = new FragmentB();
FragmentTransaction transaction = manager.beginTransaction();
transaction.add(R.id.frame_layout, fragmentB, "fragg");
transaction.commit();
}
});
}
}
UserFragment.java
public class UserFragment extends Fragment {
RecyclerView recyclerView ;
UserAdapter userAdapter ;
ArrayList<Person> arrayList ;
private LinearLayoutManager layoutManager;
Button itsMeContact,phoneContact;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_user,container,false);
recyclerView = view.findViewById(R.id.recycler_view);
itsMeContact= view.findViewById(R.id.its_me_contact);
layoutManager = new LinearLayoutManager(getActivity());
layoutManager.scrollToPosition(0);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(layoutManager);
arrayList=new ArrayList<Person>();
initial();
return view;
}
private void initial() {
Factory.getInstance().user().enqueue(new Callback<List<User>>() {
#Override
public void onResponse(Call<List<User>> call, Response<List<User>> response) {
// textView.setText(response.body().get(0).name);
userAdapter= new UserAdapter(response.body(), getActivity());
recyclerView.setAdapter(userAdapter);
}
#Override
public void onFailure(Call<List<User>> call, Throwable t) {
}
});
}
}
FragmentB.java
public class FragmentB extends Fragment {
TextView textView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.fragment_fragment_b,container,false);
textView=view.findViewById(R.id.textView);
textView.setText("naber");
return view;
}
}
Your advice important for me !
Thank you very much
My app:
enter image description here
Each Fragment transaction you did use the same framelayout : "R.id.frame_layout".
So this is normal if "it looks overhead". If you want 2 fragments displayed in a same layout, you should use 2 differents framelayout.

ANDROID fragment inside a custom dialog in activity

I would like to put a fragment inside a custom dialog in activity.
I receive this error:
java.lang.IllegalArgumentException: No view found for id 0x7f0c007e (copyworld.rebootcw:id/container_schedule1) for fragment FragmentGiorno{418215c0 #0 id=0x7f0c007e}
This is my code:
layout.xml
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="#+id/spinner_dialog_schedulazione"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:id="#+id/container_schedule1">
</FrameLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Popup_schedule();
}
//******POPUP PER LA SCHEDULAZIONE******************
public void Popup_schedule() {
dialog_schedule=new Dialog(MainActivity.this);
dialog_schedule.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dialog_schedule.setContentView(R.layout.dialog_schedule);
dialog_schedule.setCancelable(false);
lp = new WindowManager.LayoutParams();
window = dialog_schedule.getWindow();
lp.copyFrom(window.getAttributes());
lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
dialog_schedule.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
window = dialog_schedule.getWindow();
window.setAttributes(lp);
FragmentGiorno fragment = new FragmentGiorno();
android.support.v4.app.FragmentTransaction fragmentTransaction =
getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container_schedule1, fragment);
fragmentTransaction.commit();
dialog_schedule.show();
}
}
How I add a fragment inside a custom dialog in MainActivity.java that extend Activity?
Try this
dialog_schedule.findViewById(R.id.container_schedule1)
Instead Of
R.id.container_schedule1
In your Code
If you want to load fragment inside dialog then you can use DialogFragment instead.
Below is the working example of using DialogFragment.
public class Demo extends DialogFragment{
View mainView;
LinearLayout layoutArrow;
Bundle bundle;
ArrayList<BookingDetail> bookingDetails;
View.OnClickListener onClickListener;
public static Demo newInstance(#NonNull ArrayList<BookingDetail> bookingDetails) {
Demo alertPopUpMapReservedBedInfo = new Demo();
Bundle args = new Bundle();
args.putSerializable("bookingDetails", bookingDetails);
alertPopUpMapReservedBedInfo.setArguments(args);
return alertPopUpMapReservedBedInfo;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, R.style.InvitationDialogWithSimpleAnim);
bundle = getArguments();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.alert_info, container, false);
getDialog().setCanceledOnTouchOutside(true);
return mainView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
layoutArrow = (LinearLayout) mainView.findViewById(R.id.layoutArrow);
FragmentGiorno fragment = new FragmentGiorno();
android.support.v4.app.FragmentTransaction fragmentTransaction =
this.getChildFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container_schedule1, fragment);
fragmentTransaction.commit();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
if(onClickListener!=null){
onClickListener.onClick(null);
}
}
}
And call it by,
Demo newFragment = Demo.newInstance(bookingDetails);
newFragment.show(ft,"dialog");

Categories

Resources