I think the problem is that:
{
..
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
..
this.setTitle("Home");
}
and:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Home home = new Home();
return Home;
case 1:
Mail mail = new Mail();
return mail;
default:
return null;
}
}
I would now like to show in place of the page title, the new Fragment setTitle
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
Home home = new Home();
this.setTitle("change");
return Home;
case 1:
Mail mail = new Mail();
this.setTitle("change");
return mail;
default:
return null;
}
I know that is not correct, but I do not know what the correct syntax is a whole day I'm trying to solve, but nothing.
I would just change the title.
final ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Menu1");
arrayList.add("Menu2");
arrayList.add("Menu3");
arrayList.add("Menu4");
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
getSupportActionBar().setTitle(arrayList.get(position));
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int pos) {
// TODO Auto-generated method stub
}
});
Related
I have a main fragment and inside the main fragment, I have a ViewPager that consists of Nested Fragment (Detail Fragment & Summary Fragment). If I click the button in the main fragment, the data will be set in both the main fragment and Detail fragments in the ViewPager. The problem is how do I get the data from the main fragments that can be used in Detail fragments?
I tried using ViewModel in the main fragment. Suppose that the data should be passing in Detail Fragment.
//Main Fragment
private void initializeViewPager()
{
vpExpenses.setOffscreenPageLimit(2);
setupViewPager(vpExpenses);
}
private void setupViewPager(final ViewPager viewPager)
{
adapter = new ViewPagerWithTitleAdapter(getFragmentManager());
adapter.addFragment(new ExpensesDetailsListFragment(), "Detail");
adapter.addFragment(new ExpensesSummaryListFragment(), "Summary");
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }
#Override public void onPageScrollStateChanged(int state) { }
#Override public void onPageSelected(int position) {
if(position == 0)
{
tvDetailExpenses.setSelected(true);
tvSummaryExpenses.setSelected(false);
}
else if(position == 1)
{
tvDetailExpenses.setSelected(false);
tvSummaryExpenses.setSelected(true);
}
}
});
tvDetailExpenses.setSelected(true);
viewPager.setCurrentItem(0);
tvDetailExpenses.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
viewPager.setCurrentItem(0,false);
}
});
tvSummaryExpenses.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(1,false);
}
});
}
//Expenses Details List
private void setupExpensesDetailsList(String expenseCategoryId)
{
expensesViewModel = ViewModelProviders.of(this.getActivity()).get(ExpensesViewModel.class);
expensesViewModel.setToken(token);
expensesViewModel.setUserId(userId);
expensesViewModel.setDeviceId("ABCDE1234567890");
expensesViewModel.setCarId("24");
expensesViewModel.setExpensesId(expenseCategoryId);
getExpensesDetailsList();
}
public void getExpensesDetailsList()
{
expensesViewModel.getExpensesDetailsList().observe(this, expensesdetailslistObserver);
}
public Observer<ExpensesDetailsListResult> expensesdetailslistObserver = new Observer<ExpensesDetailsListResult>() {
#Override
public void onChanged(#Nullable ExpensesDetailsListResult result)
{
if(result.getStatus())
{
summary = result.getData().getSummary();
tvTotalExpenses.setText("RM"+summary.getYearly());
tvExpensesPerDay.setText("/ "+summary.getDaily_avg()+" per day");
}
else
{
if(!result.getStatus())
{
if(result.getCode() == 300)
{
new MaterialDialog.Builder(getActivity())
.title("Failed")
.content(result.getMsg())
.positiveText("OK")
.show();
}
else if(result.getCode() == 302)
{
new MaterialDialog.Builder(getActivity())
.title("Failed")
.content(result.getMsg())
.positiveText("OK")
.show();
}
}
if(result.getRedirectLogin() != null)
{
if (result.getRedirectLogin())
{
func.showErrorExpired();
}
}
}
}
};
//Details Fragment
private ExpensesDetailsListResult expensesDetails;
private List<ExpensesTypes> listExpensesType;
private Unbinder unbinder;
private ExpensesViewModel expensesViewModel;
private Function func;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_expenses_list_details, container, false);
unbinder = ButterKnife.bind(this, view);
func = new Function(getActivity());
expensesViewModel = ViewModelProviders.of(this.getActivity()).get(ExpensesViewModel.class);
expensesViewModel.getExpensesDetailsList().observe(this, item -> {
//expensesDetails = expensesViewModel.setExpensesDetailsList(item);
});
return view;
}
//View Model
public ExpensesViewModel(#NonNull Application application)
{
super(application);
}
public void setToken(String token)
{
this.token = token;
}
public void setUserId(String userId)
{
this.userId = userId;
}
public void setDeviceId(String deviceId)
{
this.deviceId = deviceId;
}
public void setCarId(String carId)
{
this.carId = carId;
}
public void setExpensesId(String expensesId)
{
this.expensesId = expensesId;
}
//THIS IS THE MAIN FUNCTION THAT UI CONTROLLER CAN OBSERVE FOR CHANGES
//Expenses Category
public MutableLiveData<ExpensesCategoryResult> getExpensesCategory()
{
expensescategoryObservable = ExpensesRepository.getInstance().getExpensesCategory(token, userId, deviceId);
return expensescategoryObservable;
}
//Expenses Details List
public MutableLiveData<ExpensesDetailsListResult> getExpensesDetailsList()
{
expensesdetailslistObservable = ExpensesRepository.getInstance().getExpensesDetailsList(token, userId, deviceId, carId, expensesId, "1");
return expensesdetailslistObservable;
}
You're passing in the wrong Lifecycle Owner when you're observing your ViewModel's data. In order for both fragments to share the data through the ViewModel, the Lifecycle Owner should be the Activity.
Both Fragments should contain something like the following:
// Get the View Model with the Activity as the owner
expensesViewModel = ViewModelProviders.of(getActivity()).get(ExpensesViewModel.class);
// Observe the LiveData by passing in the Activity as the owner, & the observer
expensesViewModel.getExpensesDetailsList().observe(getActivity(), new Observer<ExpensesDetailsListResult>(){
#Override
public void onChanged(ExpensesDetailsListResult result) {
// Do something with the data according to which Fragment this is in
}
});
I need some help with setting up the position of the Fragments in order for it to work with the the onPageListener so I can set the visibility of certain views. As I am new, I am rather unsure on how to do this. Thank you for your time and effort.
MainActivity.java
public class MainActivity extends FragmentActivity {
ViewPager viewpager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
drawerGrid = (GridView) findViewById(R.id.content);
viewpager = (ViewPager) findViewById(R.id.pager);
PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager());
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(1);
viewpager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//need some help here//
if(position == 1) {
drawerGrid.setVisibility(View.VISIBLE);
} else {
drawerGrid.setVisibility(View.GONE);
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
Fragments.java
public class Fragments extends FragmentPagerAdapter {
public Fragments(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: //need some help here//
return new Fragment1();
case 1:
return new Fragment2();
default:
break;
}
return null;
}
#Override
public int getCount() {
return 2;
}
}
try this:
ViewPager.OnPageChangeListener pageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
switch (position) {
case 0:
drawerGrid.setVisibility(View.GONE);
break;
case 1:
drawerGrid.setVisibility(View.VISIBLE);
break;
default:
break;
}
}
});
use it like:
ViewPager.addOnPageChangeListener(pageChangeListener);
// do this in a runnable to make sure the viewPager's views are already instantiated before triggering the onPageSelected call
viewpager.post(new Runnable()
{
#Override
public void run()
{
pageChangeListener .onPageSelected(viewPager.getCurrentItem());
}
});
I have a Activity with 3 tabs, inside first a fragment with listview. The listview has custom adapter. There is not problem when I start and when i go to second tab and come back. But when I go to 3th tab and come back to first one, the fragment execute onCreateView and crash with nullpointerexception, this is my code:
The fragment:
List<Post> rings;
View headerView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_within_ring, container, false);
headerView = getActivity().getLayoutInflater().inflate(R.layout.header_list_view, null);
new consultarRing().execute(); //This get the Array from web service to rings
return rootView;
}
private void fullyAdapter() {
if (rings != null) {
adapter = new PostsAdapter(getActivity(), R.layout.item_row_show_ring, rings, false, null);
lyt = (PullAndLoadListView) getActivity().findViewById(R.id.listView_withinring);
lyt.addHeaderView(headerView); //crash here
lyt.setAdapter(adapter); //crash here
//crash all down
lyt.setOnRefreshListener(new OnRefreshListener() {
//OnRefreshListener
#Override
public void onRefresh() {
// TODO Auto-generated method stub
new PullToRefreshDataTask().execute();
}
});
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
lyt.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
switch (firstVisibleItem) {
case 1:
Main.isScrolling = false;
break;
case 2:
Main.isScrolling = true;
break;
default:
break;
}
}
});
}
}
private class consultarRing extends AsyncTask<String, String, CollectionResponsePost> {
#Override
protected void onPreExecute() {
//do staff
}
#Override
protected CollectionResponsePost doInBackground(String... args) {
//do staff, get rings
}
#Override
protected void onPostExecute(CollectionResponsePost responsePost) {
//call fullyAdapter() method
fullyAdapter();
}
}
My problem is when the listview tray setAdapter for second time, I dont know how reset listview for start like new. Please help.
You execute your AsyncTask inside of onCreateView. At that moment the fragment's view hierarchy is not yet added to the activity's, therefore getActivity().findViewById() will return null if you search for fragment's views.
Try starting the AsyncTask later:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new consultarRing().execute();
}
In my program i am using Fragments with ViewPager, where each and every Fragment contains 3 checkboxes, and i want to put a condition if user has not checked any of the checkbox don't switch to other fragment when swipe.
I know what could be the condition, but i don't know where to put ?
This condition will work for me, but where to use don't know:
if(!cb1.isChecked() && !cb2.isChecked() && !cb3.isChecked())
{
Toast.makeText(getActivity(), "Choose any one !", Toast.LENGTH_SHORT).show();
return view;
}
MainActivity.java:-
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
// Locate the viewpager in activity_main.xml
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
// Set the ViewPagerAdapter into ViewPager
viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager()));
}
}
ViewPagerAdapter.java:-
public class ViewPagerAdapter extends FragmentPagerAdapter {
final int PAGE_COUNT = 2;
// Tab Titles
private String tabtitles[] = new String[] {
"Fragment 1",
"Fragment 2"
};
Context context;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return PAGE_COUNT;
}
#Override
public Fragment getItem(int position) {
switch (position) {
// Open FragmentTab1.java
case 0:
FragmentTab1 fragmenttab1 = new FragmentTab1();
return fragmenttab1;
// Open FragmentTab2.java
case 1:
FragmentTab2 fragmenttab2 = new FragmentTab2();
return fragmenttab2;
}
return null;
}
#Override
public CharSequence getPageTitle(int position) {
return tabtitles[position];
}
}
FragmentTab1.java:-
public class FragmentTab1 extends Fragment {
View view;
CheckBox cb1, cb2, cb3;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Get the view from fragmenttab1.xml
view = inflater.inflate(R.layout.fragmenttab1, container, false);
cb1 = (CheckBox) view.findViewById(R.id.cb1);
cb2 = (CheckBox) view.findViewById(R.id.cb2);
cb3 = (CheckBox) view.findViewById(R.id.cb3);
// control status of body frame checkboxes
cb1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
cb2.setChecked(false);
cb3.setChecked(false);
}
}
});
cb2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
cb1.setChecked(false);
cb3.setChecked(false);
}
}
});
cb3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
cb1.setChecked(false);
cb2.setChecked(false);
}
}
});
/**
** if(!cb1.isChecked() && !cb2.isChecked() && !cb3.isChecked())
{
Toast.makeText(getActivity(), "Choose any one !", Toast.LENGTH_SHORT).show();
return view;
}
***/
return view;
}
}
better idea is to disable viewpager from swiping and then again allow it so create custom one and use the method setPagingEnabled(boolean enabled)
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
} }
and in your xml you need:
<mypackage.CustomViewPager
android:id="#+id/myViewPager"
android:layout_height="match_parent"
android:layout_width="match_parent" />
Reference:
(i believe in copyright :-))
How do disable paging by swiping with finger in ViewPager but still be able to swipe programmatically?
When I swipe between questions, it loads current page number correctly
BUT when I use next button, first click doesnt loads pagenumber ( I mean onPageSelected() doesnt work.) second and other clicks loads content but it loads 1 page previous.
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_main);
mPager = (ViewPager)findViewById(R.id.pager);
QuestionPagerAdapter mAdapter = new QuestionPagerAdapter();
mPager.setAdapter(mAdapter);
OnPageChangeListener pageChangeListener = new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
tv.setText( mPager.getCurrentItem()+"");
}
};
mPager.setOnPageChangeListener(pageChangeListener);
Question.next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mPager.setCurrentItem(getItem(+1));
}
}
private int getItem(int i) {
int a = mPager.getCurrentItem();
i += a;
return i;
}
});
Why not just doing this in your listener:
mPager.setCurrentItem(mPager.getCurrentItem() + 1);