۱۳۹۴/۱۲/۱۳, ۰۲:۵۵ ب.ظ
سلام
دوستان کسی تا حالا با ViewPager بدون TabHost در Nested Fragment کار کرده
MainActivity:
MainFragment:
NewFragment:
CustomPagerAdapter:
OnFragmentInteraction Interface :
mainavtivity.xml
mainfragment.xml
newfragment.xml
دوستان کسی تا حالا با ViewPager بدون TabHost در Nested Fragment کار کرده
کد پیاچپی:
Logcat :
03-03 05:17:37.300 1415-1415/com.olomrayan.obituary D/AndroidRuntime: Shutting down VM
03-03 05:17:37.305 1415-1415/com.olomrayan.obituary E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.olomrayan.obituary, PID: 1415
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference
at android.support.v4.app.FragmentManagerImpl.getFragment(FragmentManager.java:667)
at android.support.v4.app.FragmentStatePagerAdapter.restoreState(FragmentStatePagerAdapter.java:211)
at android.support.v4.view.ViewPager.onRestoreInstanceState(ViewPager.java:1319)
at android.view.View.dispatchRestoreInstanceState(View.java:14746)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3121)
at android.view.ViewGroup.dispatchRestoreInstanceState(ViewGroup.java:3127)
at android.view.View.restoreHierarchyState(View.java:14724)
at android.support.v4.app.Fragment.restoreViewState(Fragment.java:468)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1094)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1248)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1613)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:517)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
MainActivity:
کد پیاچپی:
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity implements OnFragmentInteractionListener {
NewFragment newFragment = null;
MainFragment mainFragment = null;
String CurrentFragment = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
initFirstLoad();
Bitmap bitmap = null;
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
try {
InputStream is = getAssets().open("images/new.png");
bitmap = BitmapFactory.decodeStream(is);
} catch (IOException e) {
e.printStackTrace();
}
fab.setImageBitmap(bitmap);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (newFragment == null) {
newFragment = NewFragment.newInstance();
}
if (newFragment.isVisible()) {
return;
}
CurrentFragment = "NewFragment";
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.mainfragment, newFragment, "NewFragment").addToBackStack("NewFragment");
fragmentTransaction.commit();
}
});
}
@Override
public void onBackPressed() {
if (CurrentFragment.equals("NewFragment") && newFragment.isVisible()) {
getSupportFragmentManager().popBackStack();
CurrentFragment = getSupportFragmentManager().getFragments().get(0).getTag();
if (CurrentFragment == null)
CurrentFragment = "MainActivity";
//noinspection ConstantConditions
getSupportActionBar().setTitle(R.string.app_name);
}
//super.onBackPressed();
}
// @Override
// public void onBackPressed() {
// Log.d("MYLOG",String.valueOf(getFragmentManager().getBackStackEntryCount()));
// if (getFragmentManager().getBackStackEntryCount() > 0) {
// getFragmentManager().popBackStack();
// } else {
// super.onBackPressed();
// }
// }
private void initFirstLoad() {
if (mainFragment == null) {
mainFragment = MainFragment.newInstance();
}
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.mainfragment, mainFragment, "MainFragment").addToBackStack("MainFragment");
fragmentTransaction.commit();
}
@Override
public void onFragmentInteraction(String fragmentName, String[] Values) {
switch (fragmentName) {
case "AboutFragment":
Toast.makeText(MainActivity.this, "MainActivity onFragmentInteraction From About Fragment : Uri " + Values[0], Toast.LENGTH_SHORT).show();
break;
}
}
}
کد پیاچپی:
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Toast;
import com.olomrayan.obituary.Adapters.CustomAdapterRecyclerView;
import com.olomrayan.obituary.Database.DBAccess;
import com.olomrayan.obituary.Database.DBHelper;
import com.olomrayan.obituary.Models.ObituaryItem;
import java.util.ArrayList;
import java.util.List;
import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;
import jp.wasabeef.recyclerview.animators.SlideInLeftAnimator;
public class MainFragment extends Fragment implements OnFragmentInteractionListener {
private OnFragmentInteractionListener mListener;
ProgressDialog mProgressDialog;
View mRootView;
List<ObituaryItem> mObituaryItemList;
DBAccess mDBAccess;
public MainFragment() {
}
public static MainFragment newInstance() {
return new MainFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mRootView = inflater.inflate(R.layout.fragment_main, container, false);
return mRootView;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mObituaryItemList = new ArrayList<>();
LoadingData loadingData = new LoadingData();
loadingData.execute();
RecyclerView recyclerView = (RecyclerView) mRootView.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
CustomAdapterRecyclerView customAdapterRecyclerView = new CustomAdapterRecyclerView(mObituaryItemList);
AlphaInAnimationAdapter alphaInAnimationAdapter = new AlphaInAnimationAdapter(customAdapterRecyclerView);
recyclerView.setItemAnimator(new SlideInLeftAnimator());
recyclerView.getItemAnimator().setChangeDuration(1000);
alphaInAnimationAdapter.setDuration(1000);
alphaInAnimationAdapter.setFirstOnly(false);
alphaInAnimationAdapter.setHasStableIds(true);
recyclerView.setAdapter(new ScaleInAnimationAdapter(alphaInAnimationAdapter));
}
public void onButtonPressed(String fragmentName, String[] Values ) {
if (mListener != null) {
mListener.onFragmentInteraction(fragmentName, Values);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onFragmentInteraction(String fragmentName, String[] Values) {
switch (fragmentName) {
case "AboutFragment":
Toast.makeText(getActivity(), "MainFragment onFragmentInteraction From About Fragment : Uri " + Values[0], Toast.LENGTH_SHORT).show();
break;
default:
}
}
class LoadingData extends AsyncTask<String,String,List<ObituaryItem>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mDBAccess = DBAccess.getInstance(getActivity());
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(android.R.attr.progressBarStyleSmall);
mProgressDialog.show();
WindowManager.LayoutParams params = mProgressDialog.getWindow().getAttributes();
params.x = -20;
params.height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150f, getResources().getDisplayMetrics());
params.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 180f, getResources().getDisplayMetrics());
params.y = -10;
mProgressDialog.getWindow().setAttributes(params);
mProgressDialog.setContentView(R.layout.loadgin_data_progressbar);
}
@Override
protected List<ObituaryItem> doInBackground(String... params) {
return mDBAccess.getSelectData(DBHelper.DB_TABLE_NAME, DBHelper.TABLE_COLUMNS_NAMES,null,null,null,null,DBHelper.TABLE_COLUMNS_CREATEDATE + " DESC");
};
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(List<ObituaryItem> obituaryItemList) {
mProgressDialog.dismiss();
}
}
}
NewFragment:
کد پیاچپی:
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.olomrayan.obituary.Adapters.CustomPagerAdapter;
public class NewFragment extends Fragment implements View.OnKeyListener {
int CurrnetPagerItem = 1;
private OnFragmentInteractionListener mListener;
public NewFragment() {
// Required empty public constructor
}
public static NewFragment newInstance() {
new NewFragment();
return new NewFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_new, container, false);
//noinspection ConstantConditions
final ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewPager);
FragmentManager fragmentManager = getChildFragmentManager();
CustomPagerAdapter customPagerAdapter = new CustomPagerAdapter(fragmentManager);
//customPagerAdapter.setPrimaryItem(viewPager,0,StepOneFragment.newInstance());
Log.d("MYLOG", String.valueOf(customPagerAdapter.getCount()));
viewPager.setAdapter(customPagerAdapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.d("MYLOG", String.valueOf(position));
CurrnetPagerItem = position;
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
Button btnNext = (Button) rootView.findViewById(R.id.btnNext);
btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (CurrnetPagerItem > 1)
CurrnetPagerItem = 0;
viewPager.setCurrentItem(CurrnetPagerItem);
CurrnetPagerItem++;
}
});
ActionBar toolbar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if (toolbar != null) {
toolbar.setHomeButtonEnabled(true);
toolbar.setDisplayShowTitleEnabled(true);
toolbar.setDisplayShowHomeEnabled(true);
toolbar.setTitle("New Obituary");
}
return rootView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
public void onButtonPressed(String[] Values) {
if (mListener != null) {
mListener.onFragmentInteraction("NewFragment", Values);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// if (event.getAction() == KeyEvent.ACTION_DOWN) {
// if (keyCode == KeyEvent.KEYCODE_BACK) {
// return true;
// }
// }
return false;
}
}
کد پیاچپی:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.util.Log;
import com.olomrayan.obituary.StepOneFragment;
import com.olomrayan.obituary.StepTwoFragment;
public class CustomPagerAdapter extends FragmentPagerAdapter {
int count = 2;
public CustomPagerAdapter(FragmentManager fm) {
super(fm);
Log.d("MYLOG", "Custom Created");
}
@Override
public int getCount() {
return (count);
}
@Override
public Fragment getItem(int position) {
Fragment fragment;
Log.d("MYLOG", String.valueOf(position));
switch (position) {
case 0:
fragment = StepOneFragment.newInstance();
break;
case 1:
fragment = StepTwoFragment.newInstance();
break;
default:
fragment = null;
}
return fragment;
}
}
OnFragmentInteraction Interface :
کد پیاچپی:
public interface OnFragmentInteractionListener {
void onFragmentInteraction(String fragmentName,String[] Values);
}
mainavtivity.xml
کد پیاچپی:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.olomrayan.obituary.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<fragment
android:layout_marginTop="64dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/mainfragment"
class ="com.olomrayan.obituary.MainFragment"
tools:layout="@layout/fragment_main" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
app:rippleColor="@color/colorAccent"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
app:backgroundTint="@color/textColorPrimary"
android:scrollbars="vertical"
android:layout_margin="@dimen/fab_margin"
android:src="@drawable/newo"
app:theme="@style/MyFloatingButton"/>
</android.support.design.widget.CoordinatorLayout>
کد پیاچپی:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.olomrayan.obituary.MainFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:fitsSystemWindows="true"
android:layout_below="@android:id/empty"
android:layout_alignWithParentIfMissing="true"
android:layout_height="match_parent"
android:id="@+id/recyclerview">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
کد پیاچپی:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="100"
android:background="@color/navigationBarColor"
tools:context="com.olomrayan.obituary.NewFragment"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="100">
</android.support.v4.view.ViewPager>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/btnNext"
android:text="Next Page" />
</LinearLayout>