my problem is same as link given below
I have a ViewPager by same fragments RecyclerView just load items in one fragment of ViewPager
but at this post no one solve issue...
I have a recycler view items...I want when I click on recycler view item it takes me to viewpager fragment and shows that data of clicked item dynamically and on swiping viewpager it should move previous and next fragment accordingly...under fragment I want to show data of recyclerrview item using single fragment...
I have done this by using multiple fragment and using multiple instances by different name and different layout name and different id for its recyclerView and it works but i have a large number of fragments and it is not the solution for me ):
here is my viewpager code
public class AndroidViewPagerExample extends FragmentActivity {
ViewPager pager;
int positionring;
String rgtv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.mainuuuu);
Intent it = getIntent();
positionring = it.getIntExtra("POS", 0);
final int position = it.getIntExtra("POS", 0);
rgtv= it.getStringExtra("name");
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
pager.setPageTransformer(true, new RotateUpTransformer());
pager.setCurrentItem(position);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
Boolean first = true;
Boolean userScrollChange=false;
public void onPageScrollStateChanged(int state) {
System.out.println("onPageScrollStateChanged");
System.out.println("Current position=="+position);
int curreentpos=position;
int newpos=curreentpos+1;
int previousState=curreentpos-1;
if (previousState == pager.SCROLL_STATE_DRAGGING
&& state == pager.SCROLL_STATE_SETTLING)
userScrollChange = true;
else if (previousState == pager.SCROLL_STATE_SETTLING
&& state == pager.SCROLL_STATE_IDLE)
userScrollChange = false;
previousState = state;
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
System.out.println("onPageScrolled");
}
public void onPageSelected(int position) {
// Check if this is the page you want.
System.out.println("onPageSelected");
Apples.newInstance(rgtv);
}
});
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public android.support.v4.app.Fragment getItem(int position) {
return Apples.newInstance(rgtv);
}
#Override
public int getCount() {
return ringtonelist.size();
}
}
#Override
public void onBackPressed() {
// if (pager.getCurrentItem() != 36) {
// pager.setCurrentItem(36);
// } else {
Vp_Ringtoneplaybtn.Playstop();
super.onBackPressed();
// }
}
}
code given below is adapter code
public class RingToneAdapter extends RecyclerView.Adapter<RingToneAdapter.RingToneViewHolder> {
public int mSelectedItem = -1;
static MediaPlayer mp;
View view;
static Context rcntx;
int oldpossssssss;
List<RingTone_Items> ringtonelist;
private TextView hello, close;
ImageView prev, next;
private ImageView iconplay;
private InterstitialAd mInterstitialAd;
Dialog MyDialog;
static final int[] resID = {R.raw.a48, R.raw.funny_hen, R.raw.funny_roster_1, R.raw.funny_roster_2, R.raw.rooster_1, R.raw.rooster_2,R.raw.rooster_3,R.raw.funny_cock,R.raw.a12,R.raw.a45,R.raw.a44,R.raw.a43,R.raw.a31, R.raw.a10,R.raw.chicken_1,R.raw.chick_2,R.raw.chick_3,R.raw.chick_4,R.raw.chick_5,R.raw.chick_6};
public RingToneAdapter(Context rcntx, List<RingTone_Items> ringtonelist) {
this.rcntx = rcntx;
this.ringtonelist = ringtonelist;
}
#NonNull
#Override
public RingToneViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
view = LayoutInflater.from(rcntx).inflate(R.layout.ringtone_values, viewGroup, false);
RingToneViewHolder ringToneViewHolder = new RingToneViewHolder(view);
return ringToneViewHolder;
}
#Override
public void onBindViewHolder(#NonNull final RingToneViewHolder ringToneViewHolder, final int i) {
final RingTone_Items ringTone_items = ringtonelist.get(i);
ringToneViewHolder.rtv.setText(ringTone_items.getRintonetv());
if (mSelectedItem == i) { // mSelectedItem = -1 and at 1st time
// there is no position selected...so the condition goes false...go
// to else condtion
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_pause_black_24dp);
} else {
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp); // all icons will show play icon
}
ringToneViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// MyCustomAlertDialog(i);
if (mp != null && mp.isPlaying()) {
mp.stop();
mp.reset();
mp = null;
ringToneViewHolder.iconplay.setImageResource(R.drawable.ic_play_arrow_black_24dp);
}
//Intent it = new Intent(rcntx, ViewPager_Data.class);
Intent it = new Intent(rcntx, AndroidViewPagerExample.class);
it.putExtra("POS",i);
it.putExtra("name",ringTone_items.getRintonetv());
// mInterstitialAd = new InterstitialAd(rcntx);
// mInterstitialAd.setAdUnitId(rcntx.getResources().getString(R.string.ad_interstitial));
// AdRequest adRequest = new AdRequest.Builder().build();
// mInterstitialAd.loadAd(adRequest);
// mInterstitialAd.setAdListener(new AdListener() {
// public void onAdLoaded() {
// if (mInterstitialAd.isLoaded()) {
// mInterstitialAd.show();
// }
// }
// });
rcntx.startActivity(it);
}
});
ringToneViewHolder.iconplay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mSelectedItem == i) {
mSelectedItem = -1;
oldpossssssss = i;
} else {
mSelectedItem = i;
}
notifyDataSetChanged(); //update the position of row...notifyDataSetChanged is bindview method
if (mp != null && mp.isPlaying()) {
mp.stop();
//mp.deselectTrack(resID[i]);
mp.reset();
mp.release();
mp = null;
if (oldpossssssss == i) {
} else {
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
} else {
// MyCustomAlertDialog(i);
mp = new MediaPlayer();
mp = MediaPlayer.create(rcntx, resID[i]);
mp.start();
}
}
});
}
#Override
public int getItemCount() {
return ringtonelist.size();
}
class RingToneViewHolder extends RecyclerView.ViewHolder {
private TextView rtv, hello, close;
private ImageView iconplay;
public RingToneViewHolder(#NonNull View itemView) {
super(itemView);
rtv = itemView.findViewById(R.id.ringtitle);
iconplay = itemView.findViewById(R.id.playicon);
}
}
public void InterstitialAdmob() {
mInterstitialAd = new InterstitialAd(rcntx);
mInterstitialAd.setAdUnitId(rcntx.getResources().getString(R.string.ad_interstitial));
mInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
}
protected void requestNewInterstitial() {
AdRequest adRequest = new AdRequest.Builder().build();
mInterstitialAd.loadAd(adRequest);
}
}
here is main activity code
public class MainActivity extends AppCompatActivity {
RecyclerView recyclerView;
RingToneAdapter adapter;
public static ArrayList<RingTone_Items> ringtonelist;
//final int[] resID = {R.raw.alert};
public static int posss;
private String[] fruitlist = new String[]{"Funny hen 1", "Funny hen 2", "Funny roaster 1", "Funny roaster 2","Funny roaster 3", "Funny roaster 4", "funny roaster 5","Funny cock", "Funny hen alarm","Abstracts", "Wake up", "Funny tone","Get up","Alarm","Hen sound 1","Hen sound 2","Hen sound 3","Hen sound 4","Hen sound 5","Hen sound 6"};
private boolean isFABOpen;
FloatingActionButton fab,fab1, fab3;
FrameLayout fab2;
AdView mAdView;
RelativeLayout layout_no, layoutrateus, layout_yes, adlayout, adlayout1;
private static final int PERMISSION_REQUEST_CODE = 1;
private String fNmae = String.valueOf(R.raw.alarm);
private String fPAth = "android.resource://packagename/raw/alarm";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler);
// Here, thisActivity is the current activity
if (Build.VERSION.SDK_INT >= 23) {
if (checkPermission()) {
if (Settings.System.canWrite(MainActivity.this)) {
//setRingtone();
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS)
.setData(Uri.parse("package:" + getPackageName()))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
Log.e("value", "Permission already Granted, Now you can save image.");
} else {
requestPermission();
}
} else {
// setRingtone();
Log.e("value", "Not required for requesting runtime permission");
}
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
//recyclerView.setBackgroundColor(getResources().getColor(R.color.colorAccent));
recyclerView.setBackground(getResources().getDrawable(R.drawable.bg));
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
// RecyclerView.LayoutManager mLayoutManager =
// new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false);
ringtonelist = getRingTone_Items();
adapter = new RingToneAdapter(this, ringtonelist);
recyclerView.setAdapter(adapter);
recyclerView.addOnItemTouchListener(new RecyclerTouchListener(getApplicationContext(), recyclerView, new RecyclerTouchListener.ClickListener() {
#Override
public void onClick(View view, int position) {
RingTone_Items itemrg = ringtonelist.get(position);
posss=position;
}
#Override
public void onLongClick(View view, int position) {
}
}));
}
protected boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (result == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
protected void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
Toast.makeText(MainActivity.this, "Write External Storage permission allows us to do store images. Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.e("value", "Permission Granted, Now you can save image .");
if (Build.VERSION.SDK_INT >= 23) {
if (Settings.System.canWrite(MainActivity.this)) {
// setRingtone();
} else {
Intent intent = new Intent(android.provider.Settings.ACTION_MANAGE_WRITE_SETTINGS)
.setData(Uri.parse("package:" + getPackageName()))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
} else {
Log.e("value", "Permission Denied, You cannot save image.");
}
break;
}
}
private ArrayList<RingTone_Items> getRingTone_Items(){
ArrayList<RingTone_Items> list = new ArrayList<>();
for(int i = 0; i < 20; i++){
RingTone_Items model = new RingTone_Items();
model.setRintonetv(fruitlist[i]);
list.add(model);
}
return list;
}
public void onBackPressed(){
if (mp != null && mp.isPlaying()) {
mp.pause();
mp.stop();
mp.release();
mp = null;
}
onexit();
}
public void onexit() {
android.view.LayoutInflater layout1 = android.view.LayoutInflater.from(this);
View view1 = layout1.inflate(R.layout.backpress, null);
final RelativeLayout relativeLayout=(RelativeLayout) view1.findViewById(R.id.layout_top);
final AlertDialog.Builder gotoBuilder1 = new AlertDialog.Builder(this);
gotoBuilder1.setView(view1);
final AlertDialog gotoDialog1 = gotoBuilder1.create();
layout_no = view1.findViewById(R.id.layoutno);
layoutrateus = view1.findViewById(R.id.layoutrateus);
layout_yes = view1.findViewById(R.id.layout_yes);
layout_no.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
gotoDialog1.dismiss();
}
});
layoutrateus.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
Intent mintent = new Intent(Intent.ACTION_VIEW);
mintent.setData(android.net.Uri.parse("market://details?id="
+ getPackageName()));
startActivity(mintent);
} catch (Exception e1) {
try {
android.net.Uri uriUrl = android.net.Uri
.parse("https://market.android.com/details?id="
+ getPackageName());
Intent launchBrowser = new Intent(Intent.ACTION_VIEW,
uriUrl);
startActivity(launchBrowser);
} catch (Exception e2) {
android.widget.Toast.makeText(getApplicationContext(),
"No Application Found to open link",
android.widget.Toast.LENGTH_SHORT).show();
}
}
gotoDialog1.dismiss();
}
});
layout_yes.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
} catch (Exception e) {
}
gotoDialog1.dismiss();
finish();
}
});
gotoDialog1.getWindow().setLayout(android.view.ViewGroup.LayoutParams.MATCH_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
gotoDialog1.show();
}
public void onDestroy() {
super.onDestroy();
}
}
this is my fragment
public class Apples extends BaseFragment{
ImageView vpbtn;
MediaPlayer mp;
ImageView tvshare;
static String s;
static TextView rgtname;
int position = 0;
private ShareActionProvider mShareActionProvider;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.apple, container, false);
vpbtn = (ImageView) v.findViewById(R.id.iconplaypause);
mAdView = (AdView) v.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
rgtname=v.findViewById(R.id.rgtname);
rgtname.setText(s);
tvshare=v.findViewById(R.id.tvshare);
fab = v.findViewById(R.id.fab);
fab1 = v.findViewById(R.id.frm1);
fab2 = v.findViewById(R.id.frm2);
fab3 = v.findViewById(R.id.frm3);
// Vp_Ringtoneplaybtn.Setrintones(fab,fab1,fab2,fab3);
// tvshare.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Vp_Ringtoneplaybtn.shareapp();
// }
// });
Vp_Ringtoneplaybtn.shareapp(tvshare);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(!isFABOpen){
showFABMenu();
}else{
closeFABMenu();
}
}
});
Vp_Ringtoneplaybtn.Setrintones(fab1,fab2,fab3,position);
vpbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vp_Ringtoneplaybtn.PlaySound( vpbtn, position);
}
});
return v;
}
public static Apples newInstance(String rgtvv) {
s=rgtvv;
Apples f16 = new Apples();
return f16;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (this.isVisible()) {
// If we are becoming invisible, then...
if (!isVisibleToUser) {
Vp_Ringtoneplaybtn.Playstop();
vpbtn.setImageResource(R.drawable.ic_play_arrow_black_24dp);
} else {
// do what you like
}
}
}
#Override
public void onPause() {
super.onPause();
}
}
in my app I have a ViewPager with 3 fragments. I want to save the state of progress bar in my 1st fragment, since it is destroyed when I scroll all the way to the 3th one and go back to the 1st one. Now, I know that I can use setOffscreeLimit method of the viewpager to say 2 and that will fix my issue, but I want my app to be memory efficient. I did try to use the fragment's onSaveInstanceState method but for some reason it is not called when the fragment's view is destroyed. How can I save my progress bar state, please share.
This is my fragment's code:
public class SnapshotFragment extends Fragment {
public static final String ARG_PAGE = "ARG_PAGE";
private static String TAG;
private int mPage;
private ImageView mCantDecideGg;
private CircleProgressBar mCantDecideProgressBar;
private ObjectAnimator cantDecideProgressAnimator;
private Animator.AnimatorListener progressBarAnimationListener = new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animator) {
mCantDecideProgressBar.setProgress(0);
}
#Override
public void onAnimationEnd(Animator animator) {
// Log.d(TAG, "onAnimationEnd");
if(mCantDecideProgressBar.getProgress() < 100){
mCantDecideProgressBar.setProgress(0);
}else {
mCantDecideProgressBar.setProgress(100);
}
}
#Override
public void onAnimationCancel(Animator animator) {}
#Override
public void onAnimationRepeat(Animator animator) {}
};
private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
cantDecideProgressAnimator.cancel();
Log.d(TAG, "ACTION_UP canceled");
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
cantDecideProgressAnimator.start();
Log.d(TAG, "ACTION_DOWN executed");
}
return true;
}
};
public static SnapshotFragment newInstance(int page) {
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
SnapshotFragment fragment = new SnapshotFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPage = getArguments().getInt(ARG_PAGE);
TAG = getActivity().getClass().getSimpleName();
Log.d("MainActivity", "onCreate" + mPage);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_snapshot_layout,container,false);
mCantDecideGg = (ImageView)view.findViewById(R.id.cant_devide_black_circle_bg);
if(savedInstanceState != null){
mCantDecideProgressBar.setProgress(savedInstanceState.getInt(Constants.CANT_DECIDE_PROGRESS_BAR));
}
mCantDecideGg.setOnTouchListener(onTouchListener);
mCantDecideProgressBar = (CircleProgressBar)view.findViewById(R.id.cantDecideProgressBar);
//set up the project animator to animate the progress bar from 0 to 100
cantDecideProgressAnimator = ObjectAnimator.ofFloat(mCantDecideProgressBar, "progress", 0.0f, 100.0f);
//add the animation listener to the progress animator to check when the progress has started,finished...
cantDecideProgressAnimator.addListener(progressBarAnimationListener);
//set the duration of the animation to 1.2 seconds
cantDecideProgressAnimator.setDuration(1200);
Log.d("MainActivity", "onCreateView" + mPage);
return view;
}
#Override
public void onDestroyView() {
super.onDestroyView();
Log.d(TAG, "onDestroyView");
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(Constants.CANT_DECIDE_PROGRESS_BAR, (int) mCantDecideProgressBar.getProgress());
Log.d(TAG, "onSaveInstanceState");
}
}
I am implementing Cwac-camera for video recording within my application. I am trying to figure out how can I setup my Video Preview Fragment which will playback the Video Recorded within the fragment with replay in infinite until the user has accepted or rejected the video preview.
This is my Activity where it calls for the video fragment.
#Override
public void onVideoRecorded(File video) {
videoPreviewFragment = VideoPreviewFragment.newInstance(video);
getSupportFragmentManager().beginTransaction().replace(R.id.sc_camera_container, picturePreviewFragment).commit();
}
And the VideoPreviewFragment I am using File to instead of URi
public class VideoPreviewFragment extends Fragment implements MediaPlayer.OnCompletionListener {
private static final String EXTRA_VIDEO_LOCATION = "extra_video_location";
public static VideoPreviewFragment newInstance(File video) {
VideoPreviewFragment fragment = new VideoPreviewFragment();
Bundle args = new Bundle(1);
args.putString(EXTRA_VIDEO_LOCATION, video.toString());
fragment.setArguments(args);
return fragment;
}
private VideoView videoView;
private File video;
private ImageButton btnAccept;
private ImageButton btnReject;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.sc_video_preview, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
videoView = (VideoView) view.findViewById(R.id.sc_video);
btnAccept = (ImageButton) view.findViewById(R.id.sc_btn_accept);
btnAccept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCameraActivity().onAccept(video);
}
});
btnReject = (ImageButton) view.findViewById(R.id.sc_btn_reject);
btnReject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getCameraActivity().onReject(video);
}
});
video = new File(getArguments().getString(EXTRA_VIDEO_LOCATION));
}
public SimpleCameraActivity getCameraActivity() {
return (SimpleCameraActivity) getActivity();
}
#Override
public void onSuccess() {
btnAccept.setEnabled(true);
btnReject.setEnabled(true);
}
#Override
public void onError() {
btnAccept.setEnabled(false);
btnReject.setEnabled(false);
}
#Override
public void onCompletion(MediaPlayer mp) {
Log.e("VIDEO PLAY", "END VIDEO PLAY");
}
}
I'm trying to animate a set of buttons such that they disappear sequentually on click, then performs an action based on the button clicked. The action is assigned to the animation listener which triggers on animation end. This works fine.
The problem is that I want the buttons to reappear sequentually when the activity resumes. For some reason the action assigned to the animation listener re-triggers even after setting the animation to null. What am I missing?
public class MainMenu extends ActionBarActivity {
private MenuItemBuilder menuItemBuilder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
init();
}
private void init() {
menuItemBuilder = new MenuItemBuilder(this);
}
#Override
protected void onResume() {
super.onResume();
if (menuItemBuilder != null) {
menuItemBuilder.animateAllViewsEnter();
}
}
Below is the menu builder. I have three menu items: Load database, price list, and about. This class manages all the animations.
public MenuItemBuilder(Context context) {
this.context = context;
init();
}
private void init() {
initLoadDatabase();
initPriceList();
initAbout();
}
private View getViewFromId(int res) {
return ((Activity) context).findViewById(res);
}
private ImageButton getImageButtonFromId(int res) {
return (ImageButton) ((Activity) context).findViewById(res);
}
private void initLoadDatabase() {
final ImageButton button = getImageButtonFromId(R.id.imageLoadDatabase);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animateAllViewsExit(ButtonType.LOAD_DATABASE);
}
});
}
private void initPriceList() {
final ImageButton button = getImageButtonFromId(R.id.imagePriceList);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animateAllViewsExit(ButtonType.PRICE_LIST);
}
});
}
private void initAbout() {
final ImageButton button = getImageButtonFromId(R.id.imageAbout);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
animateAllViewsExit(ButtonType.ABOUT);
}
});
}
private List<View> getAnimatedViews() {
List<View> viewList = new ArrayList<>();
viewList.add(getViewFromId(R.id.imageLoadDatabase));
viewList.add(getViewFromId(R.id.priceListContainer));
viewList.add(getViewFromId(R.id.imageAbout));
return viewList;
}
public void animateAllViewsEnter() {
List<View> viewList = getAnimatedViews();
for (int i = 0; i < viewList.size(); i++) {
View view = viewList.get(i);
view.animate()
.setStartDelay((viewList.size() - i) * 250)
.alpha(1.0f);
}
}
private void animateAllViewsExit(ButtonType buttonType) {
List<View> viewList = getAnimatedViews();
for (int i = 0; i < viewList.size(); i++) {
View view = viewList.get(i);
ViewPropertyAnimator animator = view.animate()
.setStartDelay(i * 250)
.alpha(0.0f);
if (i == viewList.size() - 1) {
lastAnimation = animator;
}
}
setAnimationAction(buttonType);
}
private void setAnimationAction(final ButtonType buttonType) {
if (lastAnimation != null) {
lastAnimation.setListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
performAction(buttonType);
lastAnimation = null;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
}
private void performAction(ButtonType buttonType) {
switch (buttonType) {
case LOAD_DATABASE:
// TODO to be done
break;
case PRICE_LIST:
context.startActivity(new Intent(context, PriceList.class));
break;
case ABOUT:
context.startActivity(new Intent(context, About.class));
break;
}
}
private enum ButtonType {
LOAD_DATABASE,
PRICE_LIST,
ABOUT
}
Fixed it by setting the listener to both enter and exit animations.
public void animateAllViewsEnter() {
List<View> viewList = getAnimatedViews();
for (int i = 0; i < viewList.size(); i++) {
View view = viewList.get(i);
view.animate()
.setStartDelay((viewList.size() - i) * 250)
.alpha(1.0f)
.setListener(null);
}
}
private void animateAllViewsExit(ButtonType buttonType) {
List<View> viewList = getAnimatedViews();
for (int i = 0; i < viewList.size(); i++) {
viewList.get(i).animate()
.setStartDelay(i * 250)
.alpha(0.0f)
.setListener(getAnimatorListener(i == viewList.size() - 1, buttonType));
}
}
I have a dialog that I want to display, and I cannot. The activity that I'm calling it from has an opengl es SurfaceViewRenderer. Some code is below. The text 'here' shows, and some of the activity from the fragment is going on in the background (I see some of the println statements from there) but no fragment is visible. I do not see 'is visible' in the logs.
public void goToFrag() {
dDial = new MYDialogFragment();
Bundle args = new Bundle();
dDial.setArguments(args);
dDial.show(getFragmentManager(), "dDialog");
if (dDial.isVisible() ) System.out.println("is visible");
System.out.println("here");
}
so here's some more info. I tried to run the 'goToFrag()' method from the 'runOnUIThread()' method and the fragment appears, but only for a second. Then the PlayActivity (what I'm calling the activity that launches the Fragment and contains the GLSurfaceRenderer) disappears. After that I'm back at the activity that calls the PlayActivity. There's no error output that I can find.
//from OpenGL SurfaceViewRenderer...
public void goToFrag() {
mPlayActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
mPlayActivity.goToFrag();
}
});
}
More code might help
public class APDuellingDialogFragment extends DialogFragment {
public boolean mDebugMessages = true;
public OnFragmentReturnListener mListener;
public View v;
public ListView mListView;
public RadioGroup radio_left_right;
public interface OnFragmentReturnListener {
public void onActivityResult(int requestCode, int resultCode, Intent data);
}
public APDuellingDialogFragment() {
mBT = new APDuellingBluetooth(this);
mList = new ArrayList<APDuellingBluetooth.MenuItem>();
mSocketsLaunched = false;
}
public static APDuellingDialogFragment newInstance() {
APDuellingDialogFragment dialog = new APDuellingDialogFragment();
//dialog.setStyle(DialogFragment.STYLE_NO_FRAME, R.style.AppTheme);
dialog.setShowsDialog(true);
dialog.setRetainInstance(true);
dialog.setCancelable(false);
return dialog;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (mDebugMessages) System.out.println("on attach");
//...
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mListener = (OnFragmentReturnListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mDebugMessages) System.out.println("on create");
}
#Override
public void onDismiss(DialogInterface dialog) {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_ap_dueling, container, false);
if (mDebugMessages) System.out.println("on create view");
}
Button button_close = (Button)v.findViewById(R.id.duel_button_close);
button_close.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dismiss();
}
});
Button button_rescan = (Button)v.findViewById(R.id.duel_button_rescan);
button_rescan.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(mBT.isBluetoothSupported()) {
//...
}
}
});
radio_left_right = (RadioGroup) v.findViewById(R.id.duel_right_left_group);
radio_left_right.setOnCheckedChangeListener( new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
//...
}
});
Switch switch_audio = (Switch) v.findViewById(R.id.duel_switch_sound);
switch_audio.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//...
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
//...
return false;
}
});
return v;
}
public void restartGameFromFragment() {
if(mDebugMessages) System.out.println("restartgamefrom fragment");
Intent mIntent = prepareIntentForGame();
mListener.onActivityResult(AP.INTENT_ACTIVITY_DUEL_SETUP, Activity.RESULT_OK, mIntent);
dismiss();
}
public Intent prepareIntentForGame() {
Intent mIntent = new Intent();
//...
return mIntent;
}
#Override
public void onDestroy() {
super.onDestroy();
if (mDebugMessages) System.out.println("on destroy");
}
}
finally this:
public class MYActivityPlay extends Activity implements MYDuellingDialogFragment.OnFragmentReturnListener {
private MYGLSurfaceView myMYView;
public MYButtonManager mButtons;
public MYReadXML mXML;
public MYDuellingDialogFragment duelDialogFragment;
public RelativeLayout mTitleAndScoresView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mIntent = this.getIntent();
mMode = mIntent.getIntExtra(MY.INTENT_MODE_CONSTANT, MY.MODE_PLAY);
mIntentLevel = mIntent.getIntExtra(MY.INTENT_LEVEL_CONSTANT, 1);
mScore = mIntent.getLongExtra(MY.INTENT_SCORE_CONSTANT, 0);
mHealth = mIntent.getIntExtra(MY.INTENT_HEALTH_CONSTANT, MYDirector.FULL_HEALTH_CONST);
mPlayButtonPressedCount = mIntent.getIntExtra(MY.INTENT_PLAY_PRESSED_CONSTANT, 0);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
startSurfaceView();
if (mMode == MY.MODE_DUEL) goToFrag(); // <--here is problem!!
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//....
}
public void startSurfaceView() {
if (true ) {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Point size = new Point();
display.getSize(size);
mButtons = new MYButtonManager(this.getApplicationContext(), size.x ,size.y );
MYSound mSounds = new MYSound(this);
LayoutInflater mInflater = (LayoutInflater)getApplicationContext().getSystemService
(Context.LAYOUT_INFLATER_SERVICE);
View mTitleAndScore = mInflater.inflate(R.layout.overlay_title_score, null);
myMYView = new MYGLSurfaceView(/*some stuff here*/);
RelativeLayout mRelative = new RelativeLayout(this);
mRelative.addView(myMYView);
mRelative.addView(mTitleAndScore);
mRelative.addView(mButtons);
setContentView(mRelative);
this.setupTitleAndScore();
}
}
}
this is the final piece.