I have a main activity that handles the static elements, attached to the main activity there is a fragment, this fragment has a tablelayout with a viewpager2, each page shows a recycler view.
The shared element transition works well from FRAGMENT A(Tab_1) to FRAGMENT B(ElementDetails), but when I press the back button, the return shared element transition doesn't work.
TAb_1(Fragment A):
public class tab1_anime extends Fragment {
private RecyclerView recycler_view;
public static AFSGAdapter adapter;
private ArrayList<AddElement> a_list = new ArrayList<>();
private Context context;
public tab1_anime(){ };
#Override
public void onCreate(Bundle savedInstancesState) {
super.onCreate(savedInstancesState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstancesState) {
View view = inflater.inflate(R.layout.fragment_tab1_anime, container, false);
recycler_view = view.findViewById(R.id.recycler_view);
recycler_view.setHasFixedSize(true);
context = getActivity();
LinearLayoutManager layoutManager_anime_crucial = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
recycler_view.setLayoutManager(layoutManager_anime_crucial);
recycler_view.setItemAnimator(new DefaultItemAnimator());
int spanCount = 3; // 3 columns
int spacing = 10; // 10 for my phone, 35 for the emulator
boolean includeEdge = true;
recycler_view.addItemDecoration(new GridSpacingItemDecoration(spanCount, spacing, includeEdge));
adapter = new AFSGAdapter(a_list, getContext(), this);
adapter.setDataSet(a_list);
recycler_view.setAdapter(adapter);
recycler_view.scheduleLayoutAnimation();
adapter.notifyDataSetChanged();
return view;
}
public void openShowElementFragment(int position, View view) {
AddElement element = a_list.get(position);
ShowElementFragment showElementFragment = new ShowElementFragment();
Bundle bundle = new Bundle();
bundle.putString("transitionName", "transition" + position);
bundle.putSerializable("element", element);
showElementFragment.setArguments(bundle);
((MainActivity) context).showFragmentWithTransition(this, showElementFragment, "showElementFragment", view, "transition" + position);
}
}
ShoeElementDetails(Fragment B):
public class ShowElementFragment extends Fragment {
private AddElement elemento;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_show_element, parent, false);
//showelement_background_image.setTransitionName("example_transition");
Bundle b = getArguments();
if (b != null) {
String transitionName = b.getString("transitionName");
elemento = (AddElement) b.getSerializable("element");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
showelement_image.setTransitionName(transitionName);
}
}
//postponeEnterTransition();
Glide.with(this)
.load(elemento.image_url)
.diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
.skipMemoryCache(false)
.apply(RequestOptions.bitmapTransform(new BlurTransformation(10, 3)))
.into(showelement_background_image);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getActivity().getWindow().getSharedElementEnterTransition().setDuration(800);//.setInterpolator(new AccelerateInterpolator());
getActivity().getWindow().getSharedElementReturnTransition().setDuration(850);//.setInterpolator(new DecelerateInterpolator());
}
showelement_backarrow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
getActivity().getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragmentHolder, new MainFragment())
.commit();
//startActivity(new Intent(ShowElementActivity.this, AnimeActivity.class));
}
});
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
postponeEnterTransition();
OneShotPreDrawListener.add(view, this::startPostponedEnterTransition);
super.onViewCreated(view, savedInstanceState);
}
}
Inside the adapter I handle the click of the element to start the transition:
inside adapter:
holder.itemView.setOnClickListener(new View.OnClickListener() {
#SuppressLint("ClickableViewAccessibility")
#Override
public void onClick(View v) {
fragment.openShowElementFragment(holder.getAdapterPosition(), v.findViewById(R.id.main_image));
}
});
the openShowElementFragment called is inside main activity:
public void showFragmentWithTransition(Fragment current, Fragment newFragment, String tag, View sharedView, String sharedElementName) {
FragmentManager fragmentManager = getSupportFragmentManager();
// check if the fragment is in back stack
boolean fragmentPopped = fragmentManager.popBackStackImmediate(tag, 0);
if (fragmentPopped) {
// fragment is pop from backStack
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
current.setSharedElementReturnTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
current.setExitTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setSharedElementEnterTransition(TransitionInflater.from(this).inflateTransition(R.transition.default_transition));
newFragment.setEnterTransition(TransitionInflater.from(this).inflateTransition(android.R.transition.no_transition));
}
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.fragmentHolder, newFragment, tag);
fragmentTransaction.addToBackStack(tag);
fragmentTransaction.addSharedElement(sharedView, sharedElementName);
fragmentTransaction.commit();
}
}
It's my first time approaching with fragments.
Related
I want two textviews from recyclerview to have a correctly transition when return. Now it works very strange I mean return transition for both textwievs starts from 11 element and then it is what I want, but before that just one textview (title) has a return transition. Why then return transition starts from 11 item and how to have this transition of course from first element on recyclerview list?
Here is my code and explanation.
I have a recyclerview which sets transitionname for two textviews dynamically:
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Note noteItem = noteItemList.get(position);
holder.noteTitleText.setText(noteItem.getNoteTitle());
ViewCompat.setTransitionName(holder.noteTitleText, "title" + position);
holder.noteDetailsText.setText(noteItem.getNoteDetails());
ViewCompat.setTransitionName(holder.noteDetailsText, "details" + position);
(...)
}
in this adapter I have ViewHolder in which on parent view I set onclick like this:
rlNumberToGradient.setOnClickListener(view -> noteTitleDetailsOnClickAction());
where
private void noteTitleDetailsOnClickAction() {
boolean edit = true;
if (fragment instanceof FragmentMain) {
list = db.getAllNotes();
isOnMove = ((FragmentMain) fragment).isOnMove;
} else if (fragment instanceof FragmentFav) {
list = db.getFavNotes();
} else if (fragment instanceof FragmentSearch) {
list = db.getSearchNotes(((FragmentSearch) fragment).onChange());
}
if (!isOnMove) {
Bundle bundle = new Bundle();
bundle.putBoolean("edit", edit);
bundle.putInt("position", list.get(getAdapterPosition()).getId());
((ActivityMain) fragment.requireActivity()).onPassValuesToFragmentShowNote(bundle, noteTitleText, noteDetailsText);
}
isOnMove = false;
}
don't care about isOnMove variable, for this purpose lets assume its always true.
Once I click on this rlNumberToGradient view onPassValuesToFragmentShowNote method from main activity is called. It looks like this:
#Override
public void onPassValuesToFragmentShowNote(Bundle bundle, TextView tvTitle, TextView tvDetails) {
bundle.putString("transition_name_title", ViewCompat.getTransitionName(tvTitle));
bundle.putString("title", tvTitle.getText().toString());
bundle.putString("transition_name_details", ViewCompat.getTransitionName(tvDetails));
bundle.putString("details", tvDetails.getText().toString());
fragmentShowNote.setArguments(bundle);
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.setReorderingAllowed(true);
ft.addSharedElement(tvTitle, ViewCompat.getTransitionName(tvTitle));
ft.addSharedElement(tvDetails, ViewCompat.getTransitionName(tvDetails));
ft.setCustomAnimations(R.anim.fade_in, R.anim.fade_out);
ft.addToBackStack(fragmentShowNote.getClass().getSimpleName());
ft.replace(R.id.content_frame, fragmentShowNote);
ft.commit();
}
As we can see the fragment is showing up. Here is the key code here:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
sp = PreferenceManager.getDefaultSharedPreferences(requireContext());
setSharedElementEnterTransition(TransitionInflater.from(requireContext()).inflateTransition(R.transition.change_image_transform));
setSharedElementReturnTransition(TransitionInflater.from(requireContext()).inflateTransition(R.transition.change_image_transform));
setExitTransition(TransitionInflater.from(requireContext()).inflateTransition(R.transition.change_image_transform));
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_show_note, container, false);
if (getArguments() != null) {
Bundle b = getArguments();
position = b.getInt("position");
transitionNameTitle = b.getString("transition_name_title");
title = b.getString("title");
transitionNameDetails = b.getString("transition_name_details");
details = b.getString("details");
}
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
if (((ActivityMain) requireActivity()).getSupportActionBar() != null) {
((ActivityMain) requireActivity()).getSupportActionBar().hide();
}
Toolbar toolbar = view.findViewById(R.id.toolbar);
ViewCompat.setTransitionName(toolbar, transitionNameTitle);
((ActivityMain) requireActivity()).setSupportActionBar(toolbar);
((AppBarLayout) view.findViewById(R.id.app_bar_layout)).setExpanded(true);
toolbar.setTitle(title);
TextView tvNoteDescValue = view.findViewById(R.id.note_desc_value);
ViewCompat.setTransitionName(tvNoteDescValue, transitionNameDetails);
tvNoteDescValue.setText(details);
}
Solved. It turned out it was a uncompatibility. I tried to set transition on Toolbar and TextView. Once I get TextView from Toolbar with this method everything works fine:
public static TextView getTextViewTitle(Toolbar toolbar){
TextView textViewTitle = null;
for(int i = 0; i<toolbar.getChildCount(); i++) {
View view = toolbar.getChildAt(i);
if(view instanceof TextView) {
textViewTitle = (TextView) view;
break;
}
}
return textViewTitle;
}
I open a dialog fragment from A fragment, and when the dialog fragment is closed,
I want to switch from A fragment to B fragment at the same time.
But I keep getting Fragment already added error.
I am using show() instead of replace() to change the screen.
Fragment already added error was easily solved on the web, but
I don't work out weird.
Probably there is a problem with my code, please let me know where the problem is.
MainActivity.java
public class MainActivity extends AppCompatActivity {
BottomNavigationView bottomNav;
FragmentManager fm;
FragmentTransaction transaction;
Fragment curFrag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomNav = findViewById(R.id.bottom_nav);
bottomNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
fm = getSupportFragmentManager();
transaction = fm.beginTransaction();
curFrag = fm.getPrimaryNavigationFragment();
String tag = String.valueOf(item.getItemId());
int id = item.getItemId();
if(curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if(fragment == null) {
if(id == R.id.list)
fragment = new WorkoutListFragment();
transaction.add(R.id.content_layout, fragment, tag);
}
else {
transaction.show(fragment);
}
transaction.setPrimaryNavigationFragment(fragment);
transaction.setReorderingAllowed(true);
transaction.commitNow();
return true;
}
});
}
// Method for screen switching
public void onFragmentChanged() {
// transaction = fm.beginTransaction();
String tag = "WriteRoutine";
curFrag = fm.getPrimaryNavigationFragment();
if (curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if (fragment == null) {
fragment = new WriteRoutineFragment();
fragment.setArguments(curFrag.getArguments());
transaction.add(R.id.content_layout, fragment, tag);
} else {
transaction.show(fragment);
}
transaction.setReorderingAllowed(true);
transaction.commit();
}
}
WorkoutListFragment.java (A Fragment)
public class WorkoutListFragment extends Fragment {
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getParentFragmentManager().setFragmentResultListener("result", this, new FragmentResultListener(){
#Override
public void onFragmentResult(#NonNull String requestKey, #NonNull Bundle result) {
if(result != null)
WorkoutListFragment.this.setArguments(result);
titleData = result.getStringArrayList("title");
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.activity_workout_list, container, false);
initViews(rootView);
((AppCompatActivity) getActivity()).setSupportActionBar((toolbar));
return rootView;
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
menu.clear();
inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.record_item_add, menu);
}
#Override // open dialog
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
BodyPartDialogFragment dialog = new BodyPartDialogFragment();
dialog.show(getActivity().getSupportFragmentManager(), "BodyPartDialog");
return true;
}
}
DialogFragment.java
public class BodyPartDialogFragment extends DialogFragment {
Button startBtn;
ArrayList<String> bodypart_strData;
int selectedNum;
final static String TAG = "DialogFragment";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_body_part_dialog, null);
startBtn = view.findViewById(R.id.check);
// A D D
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedNum == 0){
Toast.makeText(getContext(), "Plaese select", Toast.LENGTH_SHORT).show();
}
else {
MainActivity activity = (MainActivity) getActivity();
Bundle result = new Bundle();
result.putStringArrayList("title", bodypart_strData);
getParentFragmentManager().setFragmentResult("result", result);
activity.onFragmentChanged();
dismiss();
}
}
});
return view;
}
Upon testing your code, you'll just need to reinstantiate the transaction object before adding/replacing your fragment.
So, you need to add below in onFragmentChanged():
transaction = getSupportFragmentManager().beginTransaction();
And here it is:
// Method for screen switching
public void onFragmentChanged() {
String tag = "WriteRoutine";
transaction = getSupportFragmentManager().beginTransaction(); // <<< THE CHANGE IS HERE
curFrag = fm.getPrimaryNavigationFragment();
if (curFrag != null) {
transaction.hide(curFrag);
}
Fragment fragment = fm.findFragmentByTag(tag);
if (fragment == null) {
fragment = new WriteRoutineFragment();
fragment.setArguments(curFrag.getArguments());
transaction.add(R.id.content_layout, fragment, tag);
} else {
transaction.show(fragment);
}
transaction.setReorderingAllowed(true);
transaction.commit();
}
I am trying to add a button clicker listener in my fragment but it doesn't seem to work.
My main fragment is created to show tabs of two other fragments. Now, this tabs fragment has a button in the toolbar to filter content. This filter button's listener and method are in my two other fragments. The issue is, when clicking on the button, it does nothing.
Tabs Fragment:
public class LibraryFragment extends Fragment implements ViewPager.OnPageChangeListener {
private View view;
private SectionsPagerAdapterLib PageAdapter;
public ViewPager viewPager;
private ImageView filterBtn;
private LibraryFragment.OnItemClickListener mOnItemClickListener;
public interface OnItemClickListener {
void onItemClick(View view);
}
public void setOnItemClickListener(LibraryFragment.OnItemClickListener mItemClickListener) {
this.mOnItemClickListener = mItemClickListener;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.view = inflater.inflate(R.layout.fragment_library_tabs, container, false);
TabLayout tabLayout = view.findViewById(R.id.fav_list_tabs);
filterBtn = view.findViewById(R.id.filterBtn);
viewPager = view.findViewById(R.id.fav_list_tabs_container);
filterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v);
}
}
});
PageAdapter = new SectionsPagerAdapterLib(getFragmentManager(), getActivity());
viewPager.setAdapter(PageAdapter);
viewPager.setOffscreenPageLimit(2);
viewPager.addOnPageChangeListener(this);
tabLayout.setupWithViewPager(viewPager);
getActivity().getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
getActivity().getWindow().setStatusBarColor(getActivity().getResources().getColor(R.color.mWindowColorHeaders));
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Fragment fragment = PageAdapter.getFragment(position);
if (fragment != null) {
fragment.onResume();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
}
Fragment which is supposed to work when the button is clicked:
public class ContentFragment extends Fragment implements LibraryFragment.OnItemClickListener {
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_data, null);
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// find my views, etc
}
#Override
public void onItemClick(View view) {
//populate filter list
if (Constants.genreList != null){
list.add(0, "All Filters");
for (int i = 0; i < Constants.list.size(); i++) {
list.add((i + 1), Constants.list.get(i).getName());
}
}
final String[] listArray = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
listArray[i] = list.get(i);
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Select Filter");
builder.setItems(genreArray, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
// ((TextView) v).setText(genreArray[i]);
selected_list.setText(listArray[i]);
if (i == 0) {
getData(1);
}
dialogInterface.dismiss();
}
});
builder.show();
}
}
Any help will be appreciated.
try this in a fragment
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{ //change fragment_video to where your button is located//
final View v2 = inflater.inflate(R.layout.fragment_video,container,false);
//start stream Button
Button startButton = (Button)v2.findViewById(R.id.buttonStart);
startButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//what your button is going to do
}
});
return v2;
}
As fragments are handled by Activity ,Fragments are still not depend on each other and can be used in one or two pane mode. Activity should handle listeners of both fragments.
I use a Bundle to pass data between Fragments. However, I ran into some problems. My Bundle is not working, I do not know why. Because I do everything as I did before.
Here is my Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_jegyek);
BottomNavigationView bottomNav = findViewById(R.id.lista_navigation);
bottomNav.setOnNavigationItemSelectedListener(navListener);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container_lista,
new Tantargylista()).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_lista,
selectedFragment).commit();
return true;
}
};
}
My first Fragment:
View v;
DB mydb;
ListView listView;
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.Jegyekview);
mydb = new DB(getActivity());
final ArrayList<String> thelist = new ArrayList<>();
Cursor data = mydb.getTantargynev();
if (data.getCount() == 0) {
Toast.makeText(getActivity(), "Empty", 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();
bundle.putString("test", teszt);
Fragment targyAdatok = new targyAdatok();
Fragment jegyekAllando = new jegyekAllando();
jegyekAllando.setArguments(bundle);
FragmentTransaction FragTan = getActivity().getSupportFragmentManager().beginTransaction();
FragTan.replace(R.id.jegyekMenu, targyAdatok);
FragTan.commit();
}
}
});
}
return v;
}
There is a second Fragment which has a Button. If the Button is pressed, then the third Fragment is open.
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});
My third Fragment:
#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("test");
//Here crash the program. :/
return rootView;
}
You have not passed anything from your second Fragment while opening your third Fragment. Hence you need to do something like the following.
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
// Get a bundle
Bundle bundle = new Bundle();
bundle.putString("test", teszt);
// Set as argument
jegyekAllando.setArguments(bundle);
// Begin the transaction
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});
I think the problem is your second fragment is not passing the bundle from the first fragment to the third fragment in this code
Button button = (Button)v.findViewById(R.id.elemzes);
elemzes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment jegyekAllando = new jegyekAllando();
FragmentTransaction FragTan2 = getFragmentManager().beginTransaction();
FragTan2.replace(R.id.fragment_container_lista,jegyekAllando);
FragTan2.commit();
}
});
I would change fragment in the viewpager using a button in every fragment. So in the fragment in position 0 i have a button and onClick i'll change in second fragment (position 1) and so on. Actually i'm using this code in the fragment at position 0:
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.open_welcome_fragment_layout, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnOpen = (Button)view.findViewById(R.id.button_next_open);
nextBtnOpen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
}
});
return view;
}
position 1:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.firstwelcomefrg, container, false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtn = (Button)view.findViewById(R.id.button_next_one);
nextBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(2, true);
}
});
return view;
}
position 2:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.secondwelcomefrg, container,
false);
final WelcomeViewPager pagerV = new WelcomeViewPager();
Button nextBtnTwo = (Button)view.findViewById(R.id.button_next_two);
nextBtnTwo.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((WelcomeViewPager)getActivity()).setCurrentItem(3, true);
}
});
return view;
}
and in my ViewPager Activity i created this method:
public void setCurrentItem (int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
unfortunatelly not works. I can change from first to second fragment but every fragment returns to second.. Seems that the only one position accepted is the first one. In this case:
((WelcomeViewPager)getActivity()).setCurrentItem(1, true);
why this behaviour?
I think what you are trying to do is to have tabs and each tab to help switch between views. You should use actionBar tabs for this, not buttons.
This should help. It is a pretty detailed tutorial.
Do you want Button ? I use for similary problem solving with listener. Example of code below. Maybe help.
PagerActivity.java
import com.example.zzztest2.MyPagerAdapter.OnPagerItemSelected;
public class PagerActivity extends Activity implements OnPagerItemSelected {
ViewPager viewPager;
ArrayList<Bitmap> bitmapArray=null;
ArrayList<String> textArray=null;
ArrayList<String> urlArray=null;
int pagexi;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reklamapager);
viewPager = (ViewPager) findViewById(R.id.view_pager);
//setting adapter
new readAsync().execute();
}//end oncreate
//switch page
public void pagerItemSelected(int newposition) {
viewPager.setCurrentItem(newposition);
}
Setting my adapter in onpostexecute Async
protected void onPostExecute(String file_url) {
MyPagerAdapter adapter = new MyPagerAdapter(PagerActivity.this, textArray, urlArray, bitmapArray, PagerActivity.this );
viewPager.setAdapter(adapter);
//start position
int pagexi = 2;
viewPager.setCurrentItem(pagexi);
}
MyPagerAdapte.java
public class MyPagerAdapter extends PagerAdapter {
Context context;
OnPagerItemSelected mListener;
ArrayList<String> textArray;
ArrayList<String> urlArray;
ArrayList<Bitmap> bitmapArray;
ImageView imageView;
TextView textreklama1;
Button btnSwitchPage;
public Activity activity;
String firmax;
String adresarx;
MyPagerAdapter(Context context, ArrayList<String> textArray, ArrayList<String> urlArray, ArrayList<Bitmap> bitmapArray, OnPagerItemSelected listener){
this.context=context;
this.textArray=textArray;
this.urlArray=urlArray;
this.bitmapArray=bitmapArray;
this.mListener = listener;
}
#Override
public int getCount() {
return textArray.size();
}
public Object instantiateItem(ViewGroup collection, int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.reklamator_new, null);
String indexx = textArray.get(position).toString();
String delims2 = "[;]+";
String[] riadokxxx = indexx.split(delims2);
String ucex = riadokxxx[0].trim();
String dokx = riadokxxx[1].trim();
EditText inputUce = (EditText) view.findViewById(R.id.inputUce);
inputUce.setText(ucex);
EditText inputDok = (EditText) view.findViewById(R.id.inputDok);
inputDok.setText(dokx);
btnSwitchPage = (Button) view.findViewById(R.id.btnSwitchPage);
btnSwitchPage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//here set new position
int xxx=1;
mListener.pagerItemSelected(xxx);
}
});
((ViewGroup) collection).addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup arg0, int arg1, Object arg2) {
((ViewGroup) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
//new position
public interface OnPagerItemSelected {
void pagerItemSelected(int xxx);
}
}