I have 4 activity that have 4 class & xml layout ; i want to swipe between in 4 activity !!
i use this code from another post (This Post: Fling gesture detection on grid layout)
i want when touching leftToright Or rightToleft swipe with opening new activity.
where is my code is wrong :
my code :
package com.package110.Y;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
public class ActivitySwipeDetectorActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// how to set this 3 line to in my code Or change or update it
//ActivitySwipeDetector activitySwipeDetector = new ActivitySwipeDetector(this);
//lowestLayout = (RelativeLayout)this.findViewById(R.id.lowestLayout);
//lowestLayout.setOnTouchListener(activitySwipeDetector);
}
public class ActivitySwipeDetector implements View.OnTouchListener {
Intent left = new Intent(getApplicationContext(), left.class);
Intent right = new Intent(getApplicationContext(), right.class);
Intent top = new Intent(getApplicationContext(), top.class);
Intent bottom = new Intent(getApplicationContext(), bottom.class);
static final String logTag = "ActivitySwipeDetector";
private Activity activity;
static final int MIN_DISTANCE = 100;
private float downX, downY, upX, upY;
public ActivitySwipeDetector(Activity activity){
this.activity = activity;
}
public void onRightToLeftSwipe(){
Log.i(logTag, "RightToLeftSwipe!");
activity.startActivity(right);
}
public void onLeftToRightSwipe(){
Log.i(logTag, "LeftToRightSwipe!");
activity.startActivity(left);
}
public void onTopToBottomSwipe(){
Log.i(logTag, "onTopToBottomSwipe!");
activity.startActivity(top);
}
public void onBottomToTopSwipe(){
Log.i(logTag, "onBottomToTopSwipe!");
activity.startActivity(bottom);
}
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN: {
downX = event.getX();
downY = event.getY();
return true;
}
case MotionEvent.ACTION_UP: {
upX = event.getX();
upY = event.getY();
float deltaX = downX - upX;
float deltaY = downY - upY;
// swipe horizontal?
if(Math.abs(deltaX) > MIN_DISTANCE){
// left or right
if(deltaX < 0) { this.onLeftToRightSwipe(); return true; }
if(deltaX > 0) { this.onRightToLeftSwipe(); return true; }
}
else {
Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
return false; // We don't consume the event
}
// swipe vertical?
if(Math.abs(deltaY) > MIN_DISTANCE){
// top or down
if(deltaY < 0) { this.onTopToBottomSwipe(); return true; }
if(deltaY > 0) { this.onBottomToTopSwipe(); return true; }
}
else {
Log.i(logTag, "Swipe was only " + Math.abs(deltaX) + " long, need at least " + MIN_DISTANCE);
return false; // We don't consume the event
}
return true;
}
}
return false;
}
}
}
explain:
my app is force close !!!
my google API is for android 3.0 ; does it have make problem for my app ?
and also i try this code and it force close !!!!
another code :
package ir.package110.Y;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
public class ActivitySwipeDetectorActivity extends Activity {
private GestureDetector gestureDetector;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// ...
gestureDetector = new GestureDetector(new SwipeGestureDetector());
}
/* ... */
Intent right = new Intent(ActivitySwipeDetectorActivity.this.getBaseContext(), right.class);
Intent left = new Intent(ActivitySwipeDetectorActivity.this.getBaseContext(), left.class);
private void onLeftSwipe() {
// Do something
startActivity(left);
}
private void onRightSwipe() {
startActivity(right);
// Do something
}
// Private class for gestures
private class SwipeGestureDetector extends SimpleOnGestureListener {
// Swipe properties, you can change it to make the swipe
// longer or shorter and speed
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 200;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
#Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
try {
float diffAbs = Math.abs(e1.getY() - e2.getY());
float diff = e1.getX() - e2.getX();
if (diffAbs > SWIPE_MAX_OFF_PATH)
return false;
// Left swipe
if (diff > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
ActivitySwipeDetectorActivity.this.onLeftSwipe();
// Right swipe
} else if (-diff > SWIPE_MIN_DISTANCE
&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
ActivitySwipeDetectorActivity.this.onRightSwipe();
}
} catch (Exception e) {
Log.e("YourActivity", "Error on gestures");
}
return false;
}
}
}
I think the best way to do that is one single Activity and 4 fragments, with a ViewPager.
You can check this link about fragments:
http://androidcookbook.com/Recipe.seam;jsessionid=A2DD7A11C804B7C7646DCA883AA452FC?recipeId=1160
And this one about ViewPager:
http://developer.android.com/reference/android/support/v4/view/ViewPager.html
You should use Fragments. It makes navigation much cleaner.
Fragments run inside of an Activity, and can look and function just like an Activity!
Here is some code.
Activity to hold Fragments
(Tabs and ActionBar can be hidden)
public class Activity extends FragmentActivity implements ActionBar.TabListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(R.style.ScoreBoardStyles);
super.onCreate(savedInstanceState);
setContentView(R.layout.view_pager);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(actionBar.newTab()
.setCustomView(t)
.setTabListener(this));
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new FirstFragment();
}
if (position == 1) {
fragment = new SecondFragment();
}
if (position == 2) {
fragment = new ThirdFragment();
}
if (position == 3) {
fragment = new FourthFragment();
}
return fragment;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
}
return null;
}
}
/**
* 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";
/**
* 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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_layout, container, false);
return rootView;
}
}
}
Example of a Fragment
public class FirstFragment extends Fragment {
public ScoreFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.first_layout, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// YOUR CODE HERE
}
}
If you are using AndroidStudio!
Right click your com.blah.bleh
Go to New
Select create new TabbedActivity (Choose your navigation style towards bottom)
Then create your Fragments
Right click your com.blah.bleh
Go to New
Select Fragment and choose your Fragment type
Set the layout in your Activity class here
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position == 0) {
fragment = new FirstFragment();
}
if (position == 1) {
fragment = new SecondFragment();
}
if (position == 2) {
fragment = new ThirdFragment();
}
if (position == 3) {
fragment = new FourthFragment();
}
return fragment;
}
Hope that helps!
Related
I created a view pager that controls four fragments. But I want to disabled swiping by finger. I want to lock swipe and use button click to navigate to the next fragment or previous fragment. But all my trial codes gotten from research proved wrong. Please how do I disable swiping completely and introduce a button to enable me to navigate to the
This is SimpleFragmentPageAdapter
public class SimpleFragmentPageAdapter extends FragmentPagerAdapter {
private String[] tabtitle=new String[]{"Page1","Page2","Page3","Page4",};
Context context;
private int pagecount=4;
public SimpleFragmentPageAdapter(FragmentManager fm, Context context) {
super(fm);
this.context=context;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: //Fragment # 0 - This will show DevelopersFragment
return Page1Fragment.newInstance(0, "page # 0");
case 1: //Fragment # 0 - This will show Page1Fragment
return Page2Fragment.newInstance(1, "Page # 1");
case 2: //Fragment # 0 - This will show Page2Fragment
return Page3Fragment.newInstance(2, "Page # 2");
case 3: //Fragment # 0 - This will show Page3Fragment
return Page4Fragment.newInstance(3, "Page # 3");
default:
return null;
}
}
#Override
public int getCount() {
return pagecount;
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return "woliwo" + position;
}
}
This is Main1Activity.java
public class Main1Activity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
Button Tips3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the start page passed to us or default to first page
Intent mIntent = getIntent();
int startPage = mIntent.getIntExtra("startPage", 0);
setContentView(R.layout.activity_main1);
toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new SimpleFragmentPageAdapter(getSupportFragmentManager(), this));
// set the current page to the start page
viewPager.setCurrentItem(startPage);
//Attach the page change listener inside the activity
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
// This method will be invoked when a new page becomes selected
#Override
public void onPageSelected(int position) {
Toast.makeText(Main1Activity.this, "bool:" + position, Toast.LENGTH_SHORT).show();
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetpixels) {
}
// Called when the scroll state changes:
//SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
}
});
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
}
This is what I tried that gave 1% motion event disability
final View touchView = findViewById(R.id.view_pager);
touchView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
return true;
}
});
This is the ViewPager class Main1Activity.java This below is how I did it and it show nothing please correct me
public class Main1Activity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
Button Tips3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main1);
toolbar = findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
CustomViewPager viewPager = findViewById(R.id.view_pager);
viewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.tool_item_menu1, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.item0:
Toast.makeText(this, "Home Selected", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Main1Activity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
You can use ViewPager2 as mentioned in the comment above by https://stackoverflow.com/users/7725103/rajasekhar, but if you really need to use a viewpager: then you will have to create a custom viewpager like this:
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import androidx.viewpager.widget.ViewPager;
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;
}
}
Usage
<com.yourpackagename.CustomViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="#id/tab_layout"/>
Finally :
In the class you are using the viewpager:
CustomViewPager viewPager=findViewById(R.id.view_pager);
viewPager.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
This Solution is for those using ViewPager2
Set you Layout thus:
<androidx.viewpager2.widget.ViewPager2
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/tab_layout"/>
And then set the class thus: No matter the way you code just placing this viewPager2.setUserInputEnabled(false); disables swiping effects
ViewPager2 viewPager2 = findViewById(R.id.viewPager);
viewPager2.setAdapter(new SimpleFragmentPagerAdapter(this));
viewPager2.setUserInputEnabled(false);
Goodluck!
I am trying to create a form using fragments in a viewpager which is a step by step process.
there are 6 fragments in the viewpager. a "Back" button and a "Next" button(in the activity).
I want to save the form when the user clicks the "Next" button.
To the Reference here is the code
The Adapter to load the Fragments
public class RegistrationPagerAdapter extends FragmentPagerAdapter {
Fragment fragment;
public RegistrationPagerAdapter(#NonNull FragmentManager fm, int behavior) {
super(fm, behavior);
}
#NonNull
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
fragment = new PersonalDetailsFragment();
break;
case 1:
fragment = new AboutMeFragment();
break;
case 2:
fragment = new HoroscopeFragment();
break;
case 3:
fragment = new EducationFragment();
break;
case 4:
fragment = new FamilyFragment();
break;
case 5:
fragment = new ExpectationFragment();
break;
}
return fragment;
}
#Override
public int getCount() {
return 6;
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
}
There are two buttons in the activity(not in fragments)
public class FormActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "FormActivity";
AppCompatButton backButton, nextButton;
CustomViewPager viewpager;
Toolbar toolbar;
ApiInterface apiInterface;
RegistrationPagerAdapter adapter;
int status;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_form);
initilizeToolbar();
}
#Override
protected void onRestart() {
super.onRestart();
}
private void initilizeToolbar() {
apiInterface = ApiClient.getClient(getApplicationContext()).create(ApiInterface.class);
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
castComponents();
}
private void castComponents() {
viewpager = findViewById(R.id.viewPager);
backButton = findViewById(R.id.backButton);
nextButton = findViewById(R.id.nextButton);
nextButton.setOnClickListener(this);
backButton.setOnClickListener(this);
GetAllDetailsOfUser();
}
#Override
public void onResume() {
initilizeToolbar();
super.onResume();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
public void setViewPagerData(int status) {
FragmentManager fm = getSupportFragmentManager();
adapter = new RegistrationPagerAdapter(fm, 0);
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(status);
viewpager.setPagingEnabled(false);
}
public void GetAllDetailsOfUser() {
Call<AllProfileDetails> allDetails = apiInterface.allDetails(PrefUtils.getToken(this), PrefUtils.getID(this));
allDetails.enqueue(new Callback<AllProfileDetails>() {
#Override
public void onResponse(Call<AllProfileDetails> call, Response<AllProfileDetails> response) {
AllProfileDetails all = response.body();
if (all != null) {
if (all.getStatus()) {
Data data = all.getData();
setViewPagerData(data.getProfileCurrentStatus());
status = data.getProfileCurrentStatus();
}
}
}
public void onFailure(Call<AllProfileDetails> call, Throwable t) {
Crashlytics.log(t.getLocalizedMessage());
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backButton:
if (viewpager.getCurrentItem() == 0){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
}
break;
case R.id.nextButton:
if (viewpager.getCurrentItem() == 6){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
}
break;
}
}
}
this is Code is Fine but here is the problem...
When i save the data in Fragment1 i.e "PersonalDetailsFragment", it moves to fragment2 i.e "AboutMeFragment"
again when i click on save button for "AboutMeFragment" it runs the method of "PersonalDetailsFragment" only
please note that i call the activity buttons in fragments as
getActivity().findViewById(R.id.backButton);
getActivity().findViewById(R.id.nextButton);
You should have a interface like OnSaveTapped.
public interface OnSaveTapped{
void onSaveTapped();
}
Then make the fragments implement the interface above, ex:
public class PersonalDetailsFragment extends Fragment implements OnSaveTapped{
public void onSaveTapped(){
//do your business code here to save data
}
}
Finally ,In the activity class:
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.backButton:
if (viewpager.getCurrentItem() == 0){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() - 1);
}
break;
case R.id.nextButton:
if (viewpager.getCurrentItem() == 6){
}else{
viewpager.setCurrentItem(viewpager.getCurrentItem() + 1);
}
break;
case R.id.button_save:
((OnSaveTapped)viewpager.getCurrentFragment()).onSaveTapped();
}
Don't forget to create new method named getCurrentFragment() to return current item (fragment) in RegistrationPagerAdapter.
public class RegistrationPagerAdapter extends FragmentPagerAdapter {
private Fragment fragment;
/**other lines of code*/
public Fragment getCurrentFragment(){
return fragment;
}
}
In Android if I start new Activity B from within activity A, Android will automatically save all the state of Activity A. So when I click back button on the device in Activity B, A will be restored to the state when I had started Activity B (for example: Spinners, ListView and Toggle Buttons all are in their previous positions).
BUT when I click the back button in action bar activity A starts fresh with no stored state.
Is there any way to make this back button similar to the device's back or I have to use SharedPreferences and store every thing myself?
(api 8 and above for my app)
In one of the fragments in my app I have a ListView which is one of the fragments that needs to be in the same state when coming back from the next page. I have added the code below.
If any other part is needed please tell me and I will add the code.
The main activity code:
private ProgressDialog progress;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(Farsi.Convert(getString(R.string.app_name_farsi)));
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab. We can also use ActionBar.Tab#select() to do this if we have a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter. Also specify this Activity object, which implements the TabListener interface, as the callback (listener) for when this tab is selected.
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will automatically handle clicks on the Home/Up button, so long as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent=new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
Here is the code to my List Fragment:
public class SearchResultListFragment extends Fragment{
Pagination pagination;
boolean loadingMore = false;
ListView list;
TextView text1;
TextView text2;
TextView text3;
TextView text4;
TextView text5;
Button Btngetdata;
private static String url = "https://www.....com/api/property/search";
private static int currentFirstVisibleItem;
public SearchResultArrayListAdaptor adapter ;
LinearLayout linlaHeaderProgress;
JSONArray jsonArray = null;
JSONParse fetchclass = null;
public SearchResultListFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linlaHeaderProgress = (LinearLayout) getActivity().findViewById(R.id.linlaHeaderProgress);
ArrayAdapter<PropertyObject> aa =(ArrayAdapter<PropertyObject>) list.getAdapter();
if (aa!= null){
aa.clear();
aa.notifyDataSetChanged();
}
list.setOnItemClickListener((OnItemClickListener) getActivity());
adapter = new SearchResultArrayListAdaptor(getActivity(), R.layout.list_view_items, new ArrayList<PropertyObject>());
list.setAdapter(adapter);
pagination = new Pagination(0,15);
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search_result_list, container, false);
list=(ListView)rootView.findViewById(R.id.listViewSearchResult);
list.setOnScrollListener(
new OnScrollListener(){
private int currentVisibleItemCount;
private int currentTotalItemCount;
private int currentScrollState;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
if(fetchclass!=null) {
pagination = new Pagination(this.currentTotalItemCount,15);
if(!(fetchclass.getStatus()== AsyncTask.Status.RUNNING)) {
fetchclass= new JSONParse(getActivity());
fetchclass.execute(url);
}
}
else {
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
});
return rootView;
}
//*********************************** inner class
public class JSONParse extends AsyncTask<String, String, JSONObject> {
Context mContext;
int checkBoxRooms;
public JSONParse(Context context){
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject json = null;
PropertyFilter searchFilter = SearchFilterManager.initializePropertyFilter(new PropertyFilter(), getArguments());
getActivity().setProgressBarIndeterminateVisibility(true);
JSONParserForSearch jParser = new JSONParserForSearch();
json = jParser.getJSONFromUrl(url, searchFilter, pagination);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// SHOW THE SPINNER WHILE LOADING FEEDS
getActivity().setProgressBarIndeterminateVisibility(false);
PropertyObject propertyObject;
try {
jsonArray = json.getJSONArray("PropertyListings");
if (jsonArray == null || jsonArray.length()<1){
// list.setEmptyView(getActivity().findViewById(R.id.txtNoResult));
}
else {
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
adapter.add(propertyObject);
adapter.notifyDataSetChanged();
}
}
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
<ListView
android:id="#+id/listViewSearchResult"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
>
</ListView>
<LinearLayout
android:id="#+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone"
>
My Adapter is ArrayAdapter.
I have implemented isEmpty and getCount too.
My Activity For List:
public class SearchResultListActivity extends ActionBarActivity implements OnItemClickListener{
static PropertyObject selectedPropertyObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle=new Bundle();
bundle.putInt("intentionOfOwner", intent.getIntExtra("intentionOfOwner",0));
SearchResultListFragment fragobj=new SearchResultListFragment();
fragobj.setArguments(bundle);
///back button
setContentView(R.layout.activity_search_result_list);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, fragobj).commit();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View textView, int rowNumber, long arg3) {
Intent intent = new Intent(this, PropertyDetailActivity.class);
PropertyObject po = (PropertyObject) arg0.getAdapter().getItem((int)arg3);
intent.putExtra("listingID",po.getID());
startActivity(intent);
}
EDIT:
All right. I changed my API level from 8 to 11 to.
Also I added getActionBar().setDisplayHomeAsUpEnabled(true); to onCreate() of activity.
And changes the onOptionsItemSelected as follows.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent=new Intent(PropertyDetailActivity.this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.up:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.homeAsUp:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
BUT none of the switch cases gets the chance to run when I click the back button in the action bar!
I am working on a ViewPager whose elements can be flipped, as in the CardFlipActivity of android animations demo.
I am having a problem with the beginTransaction() method.
The only quick fix options I get ask me to change the type of frag from android.support.v4.app.Fragment to android.app.Fragment
When I do so, another error comes up and I have to change the type back to support.v4.app.Fragment.
How do I proceed ?
I am using all support.v4 library imports in my code for fragments and viewPagers.
Code:
package com.example.flag_o;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class QuizGame extends FragmentActivity
implements FragmentManager.OnBackStackChangedListener {
static DataClass dc;
static int numQues;
static int quizLev;
static int FLIP_FOR_MAP = 1;
static int FLIP_FOR_INFO = 2;
static int frag_status=0;
static int questions[] = null;
MenuItem map;
MenuItem ques;
private Handler mHandler = new Handler();
private boolean mShowingBack = false;
QuizPagerAdapter quizAdapter;
ViewPager quizPager;
static String RETRIEVE_POS = "position";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quiz_pager);
dc = new DataClass();
numQues = getIntent().getExtras().getInt("numQ");
quizLev = getIntent().getExtras().getInt("level");
java.util.List<Integer> randNums = new java.util.ArrayList<Integer>(dc.flags.length);
for (int i = 0; i <= dc.flags.length; i++)
{
randNums.add(new Integer(i));
}
java.util.Collections.shuffle(randNums);
for(int i=0;i<numQues;i++)
questions[i] = randNums.get(i);
quizAdapter = new QuizPagerAdapter(getSupportFragmentManager(),questions);
quizPager = (ViewPager) findViewById(R.id.quizPager);
quizPager.setAdapter(quizAdapter);
if (savedInstanceState == null) {
// If there is no saved instance state, add a fragment representing the
// front of the card to this activity. If there is saved instance state,
// this fragment will have already been added to the activity.
getFragmentManager()
.beginTransaction()
.add(R.id.container, new FlagFragment())
.commit();
} else {
mShowingBack = (getFragmentManager().getBackStackEntryCount() > 0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
// Add either a "photo" or "finish" button to the action bar, depending on which page
// is currently selected.
map = menu.add(Menu.NONE, R.id.action_map, Menu.NONE,
mShowingBack
? R.string.action_photo
: R.string.action_map);
map.setIcon(mShowingBack
? R.drawable.ic_action_photo
: android.R.drawable.ic_menu_mapmode);
map.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
ques = menu.add(Menu.NONE, R.id.action_ques, Menu.NONE,
mShowingBack
? R.string.action_photo
: R.string.action_ques);
ques.setIcon(mShowingBack
? R.drawable.ic_action_photo
: android.R.drawable.ic_menu_help);
ques.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
//NavUtils.navigateUpTo(this, new Intent(this, MainActivity.class));
frag_status=0;
return true;
case R.id.action_map:
if(mShowingBack)
frag_status=0;
else
frag_status=1;
flipCard(FLIP_FOR_MAP);
return true;
case R.id.action_info:
if(mShowingBack)
frag_status=0;
else
frag_status=2;
flipCard(FLIP_FOR_INFO);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
switch(frag_status)
{
case 1:
map.setVisible(true);
ques.setVisible(false);
break;
case 2:
map.setVisible(false);
ques.setVisible(true);
break;
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
map.setVisible(true);
ques.setVisible(true);
}
private void flipCard(int flipType) {
if (mShowingBack) {
getFragmentManager().popBackStack();
return;
}
mShowingBack = true;
Fragment mapFrag;
InfoFragment infoFrag;
Bundle args = new Bundle();
args.putInt(RETRIEVE_POS, questions[quizPager.getCurrentItem()]);
switch(flipType) {
case 1 :
mapFrag = new Fragment();
mapFrag.setArguments(args);
getFragmentManager()
.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, mapFrag)
.addToBackStack(null)
.commit();
break;
case 2 :
frag = new InfoFragment();
frag.setArguments(args);
getFragmentManager()
.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, frag)
.addToBackStack(null)
.commit();
break;
}
mHandler.post(new Runnable() {
#Override
public void run() {
invalidateOptionsMenu();
}
});
}
#Override
public void onBackStackChanged() {
mShowingBack = (getFragmentManager().getBackStackEntryCount() > 0);
// When the back stack changes, invalidate the options menu (action bar).
invalidateOptionsMenu();
}
public static class FlagFragment extends Fragment {
int position;
Bundle args;
public FlagFragment() {
position = args.getInt(RETRIEVE_POS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.pic_fragment, container, false);
ImageView flipImg = (ImageView)rootView.findViewById(R.id.flipFlagImage);
try {
flipImg.setImageResource(dc.flags[position]);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootView;
}
}
public static class MapFragment extends Fragment {
int position;
Bundle args;
public MapFragment() {
position = args.getInt(RETRIEVE_POS);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.map_fragment, container, false);
ImageView flipImg = (ImageView)rootView.findViewById(R.id.flipMapImage);
try {
flipImg.setImageResource(dc.ortho[position]);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rootView;
}
}
public static class InfoFragment extends Fragment {
public InfoFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.info_fragment, container, false);
}
}
public class QuizPagerAdapter extends FragmentStatePagerAdapter {
int fragDet[];
Fragment frag;
Bundle args;
public QuizPagerAdapter(FragmentManager fragmentManager, int [] q) {
super(fragmentManager);
fragDet = q;
}
#Override
public Fragment getItem(int i) {
frag = new FlagFragment();
args.putInt(RETRIEVE_POS, fragDet[i]);
frag.setArguments(args);
return frag;
}
#Override
public int getCount() {
return numQues;
}
#Override
public CharSequence getPageTitle(int position) {
String title = null;
switch(position)
{
case 0 : title = "Paired Devices";
break;
case 1 : title = "Chats";
break;
case 2 : title = "New Devices";
break;
}
return (CharSequence)title;
}
}
}
The support library's Fragment class doesn't support animations in transactions.
Its a trade off between animating or building the app for devices with API higher than 11.
http://developer.android.com/reference/android/app/FragmentTransaction.html
Another way about this is to use the NineOldAndroids library from Jake Wharton and code the transaction yourself.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
moveTaskToBack(true);
return true;
}
return super.onKeyDown(keyCode, event);
}
hi have this code to go back to previous class but when i hit back button i get in my home launcher screen.
I want to get to my previous screen of my app and keep what changes i have made in settings menu.
Try adding this instead of moveTaskToBack():
super.onBackPressed();
So your code should look like:
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
super.onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
Obviously, if you're on the first activity in your application, you will then be taken to your homescreen
this is my main Activity
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_settings4:
mainactivity();
return true;
case R.id.menu_settings1:
ipallilos();
return true;
case R.id.menu_settings2:
rithmisi();
return true;
case R.id.menu_settings3:
sxetika();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void mainactivity() {
Toast.makeText(MainActivity.this, "Επιστροφή στην Αρχική Σελίδα",
Toast.LENGTH_SHORT).show();
}
private void rithmisi() {
setContentView(R.layout.rithmisis);
Toast.makeText(MainActivity.this, "Loading Settings",
Toast.LENGTH_SHORT).show();
}
private void ipallilos() {
setContentView(R.layout.ipallilos);
Toast.makeText(MainActivity.this, "Loading Staff",
Toast.LENGTH_SHORT).show();
}
private void sxetika() {
//anoigma menou efarmogis
setContentView(R.layout.sxetikame);
Toast.makeText(MainActivity.this, "Loading about Software",
Toast.LENGTH_SHORT).show();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//moveTaskToBack(true);
super.onBackPressed();
return true;
}
return super.onKeyDown(keyCode, event);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
/**
* εγω γράφεις τον τίτλο που θα φενεται
* στο γραμμη το paper title
*/
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
// case 1:
// return getString(R.string.title_section2).toUpperCase();
case 1:
return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
/**
* ΕΔΩ ΓΡΑΦΕΙΣ ΓΙΑ ΤΟ ΤΙ ΘΑ ΦΕΝΕΤΑΙ ΜΕΣΑ
*
*/
public static class DummySectionFragment extends Fragment {
public DummySectionFragment() {
}
public static final String ARG_SECTION_NUMBER = "section_number";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Bundle args = getArguments();
switch (args.getInt(ARG_SECTION_NUMBER)){
case 1:
return inflater.inflate(R.layout.paraggeleialayout, container, false);
case 2:
return inflater.inflate(R.layout.trapezia, container, false);
}
return getView();
}
}
}