Hi I am new to android and I am doing one simple application. My application contain one simple activity in witch it contains view pager. my view pager having no of screens 3. SO my view pager working fine. my first and second screen contains one button when i click on that button it will goes to third screen setCurrentItem(2);.
now what i want is when i go third screen it will render one view and few sec only like after completely rendering that view do some animation like flip animation.
what happen in reality when i click on buttons it directly go to that screen but not rendering that default view. it directly starts animation...
My code looks like
public class HelpActivity extends Activity {
private final int NUM_SCREENS = 3;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
mInflater = LayoutInflater.from(this);
vp = (ViewPager) findViewById(R.id.pager);
PagerAdapter pagerAdapter = new MyPagerAdapter();
vp.setAdapter(pagerAdapter);
}
private OnClickListener signin = new OnClickListener() {
#Override
public void onClick(View arg0) {
vp.setCurrentItem(2);
// ******* do some animation on view 3 in pager views ....
}
};
private class MyPagerAdapter extends PagerAdapter {
#Override
public int getCount() {
return NUM_SCREENS;
}
#Override
public Object instantiateItem(View collection, int position) {
View view = null;
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/sf_cartoonist_hand_bold.ttf");
if (position == 0) {
// display view1
// on button click call sign in
} else if (position == 1) {
//display view 2
//on button click call sign in
} else if (position == 2) {
//display view 3
}
((ViewPager) collection).addView(view, 0);
return view;
}
}
}
what i need after clicking on button it skips to view3 display for few sec and after that do animation... how to do that?
need help.....
thank you .....
Using Runnable you can hold your animation until your view is not load it properly, you have to measure that in how much seconds your view get load, so you can pass delay as per your view get load time, something like below:
Runnable runnableimage = new Runnable() {
public void run() {
//HERE YOUR ANIMATION
image.startAnimation(animFast);
}
};
It start your animation after 2000 MilliSec
handler.postDelayed(runnableimage, 2000);
Use animate() with start delay:
mView.animate().rotationBy(360).setDuration(3000).setStartDelay(2000).start();
Related
I am using ViewPager which contains Fragment which contains RecyclerView. There I am trying to auto-refresh only current(which is visible) page view every 10 seconds. But the problem is after 10 seconds handler.postDelayed() is updating view of the next page view (not which is visible). I know it's because pager loads 1 extra page and this is causing holder to update with that next view and handler.postDelayed() is updating that next view in holder.
How to solve this problem.
here is my autorefresh method, I am calling it from onBindViewHolder();
private void startAutoRefresh(final ViewHolder holder, final String exchange,
final int currentPosition, final int timer){
new FetchData(holder, exchange, firstTimeLoadPosition).execute(
Configuration.exchangesAPI.get(exchange));
if (MainActivity.pagerPosition == currentPosition) {
counterView.setText(timer + "");
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (timer > 0) {
counterView.setText(timer + "");
startAutoRefresh(holder, exchange, currentPosition, timer - 1);
} else {
Log.wtf("Reloading", currentPosition+"");
new FetchData(holder, exchange, currentPosition).execute(
Configuration.exchangesAPI.get(exchange));
startAutoRefresh(holder, exchange, MainActivity.pagerPosition, counter);
}
}
}, 1000);
}
}
use an interface and pass that interface as a parameter of the adapter... in the interface interface GetPositionFromMainActivity extends Parcelable{int getPosition();} and in MainActivity after setting adapter of view paper GetPositionFromMainActivity getpos = new GetPositionFromMainActivity { #override getpos{ return viewpager.getPosition()} and in recycler adapter if(interface.getPos == currentPosition) instead of a static variable.. I mean just use an interface instead of a static variable...
pass the interface to the adapter of viewpager ..and in the getItem of viewPagerAdapter pass the interface as putParcelable as bundle arguments.. get the arguments the fragment and pass the imterface to the recycler adapter...
You can use onPageSelected method of ViewPager.OnPageChangeListenr for this. For example,
ViewPager.OnPageChangeListener mPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(final int position) {
// It returns the position of currently visible page.
// Write your code here, according to your slide position using switch or if else.
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
Currently, by using the default animator android.support.v7.widget.DefaultItemAnimator, here's the outcome I'm having during sorting
DefaultItemAnimator animation video : https://youtu.be/EccI7RUcdbg
public void sortAndNotifyDataSetChanged() {
int i0 = 0;
int i1 = models.size() - 1;
while (i0 < i1) {
DemoModel o0 = models.get(i0);
DemoModel o1 = models.get(i1);
models.set(i0, o1);
models.set(i1, o0);
i0++;
i1--;
//break;
}
// adapter is created via adapter = new RecyclerViewDemoAdapter(models, mRecyclerView, this);
adapter.notifyDataSetChanged();
}
However, instead of the default animation during sorting (notifyDataSetChanged), I prefer to provide custom animation as follow. Old item will slide out via right side, and new item will slide up.
Expected animation video : https://youtu.be/9aQTyM7K4B0
How I achieve such animation without RecylerView
Few years ago, I achieve this effect by using LinearLayout + View, as that time, we don't have RecyclerView yet.
This is how the animation is being setup
PropertyValuesHolder alpha = PropertyValuesHolder.ofFloat("alpha", 1.0f, 0f);
PropertyValuesHolder translationX = PropertyValuesHolder.ofFloat("translationX", 0f, (float) width);
ObjectAnimator animOut = ObjectAnimator.ofPropertyValuesHolder(this, alpha, translationX);
animOut.setDuration(duration);
animOut.setInterpolator(accelerateInterpolator);
animOut.addListener(new AnimatorListenerAdapter() {
public void onAnimationEnd(Animator anim) {
final View view = (View) ((ObjectAnimator) anim).getTarget();
Message message = (Message)view.getTag(R.id.TAG_MESSAGE_ID);
if (message == null) {
return;
}
view.setAlpha(0f);
view.setTranslationX(0);
NewsListFragment.this.refreshUI(view, message);
final Animation animation = AnimationUtils.loadAnimation(NewsListFragment.this.getActivity(),
R.anim.slide_up);
animation.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
view.setVisibility(View.VISIBLE);
view.setTag(R.id.TAG_MESSAGE_ID, null);
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
view.startAnimation(animation);
}
});
layoutTransition.setAnimator(LayoutTransition.DISAPPEARING, animOut);
this.nowLinearLayout.setLayoutTransition(layoutTransition);
and, this is how the animation is being triggered.
// messageView is view being added earlier in nowLinearLayout
for (int i = 0, ei = messageViews.size(); i < ei; i++) {
View messageView = messageViews.get(i);
messageView.setTag(R.id.TAG_MESSAGE_ID, messages.get(i));
messageView.setVisibility(View.INVISIBLE);
}
I was wondering, how I can achieve the same effect in RecylerView?
Here is one more direction you can look at, if you don't want your scroll to reset on each sort (GITHUB demo project):
Use some kind of RecyclerView.ItemAnimator, but instead of rewriting animateAdd() and animateRemove() functions, you can implement animateChange() and animateChangeImpl(). After sort you can call adapter.notifyItemRangeChanged(0, mItems.size()); to triger animation.
So code to trigger animation will look pretty simple:
for (int i = 0, j = mItems.size() - 1; i < j; i++, j--)
Collections.swap(mItems, i, j);
adapter.notifyItemRangeChanged(0, mItems.size());
For animation code you can use android.support.v7.widget.DefaultItemAnimator, but this class has private animateChangeImpl() so you will have to copy-pasted code and changed this method or use reflection. Or you can create your own ItemAnimator class like #Andreas Wenger did in his example of SlidingAnimator. The point here is to implement animateChangeImpl Simmilar to your code there are 2 animations:
1) Slide old view to the right
private void animateChangeImpl(final ChangeInfo changeInfo) {
final RecyclerView.ViewHolder oldHolder = changeInfo.oldHolder;
final View view = oldHolder == null ? null : oldHolder.itemView;
final RecyclerView.ViewHolder newHolder = changeInfo.newHolder;
final View newView = newHolder != null ? newHolder.itemView : null;
if (view == null) return;
mChangeAnimations.add(oldHolder);
final ViewPropertyAnimatorCompat animOut = ViewCompat.animate(view)
.setDuration(getChangeDuration())
.setInterpolator(interpolator)
.translationX(view.getRootView().getWidth())
.alpha(0);
animOut.setListener(new VpaListenerAdapter() {
#Override
public void onAnimationStart(View view) {
dispatchChangeStarting(oldHolder, true);
}
#Override
public void onAnimationEnd(View view) {
animOut.setListener(null);
ViewCompat.setAlpha(view, 1);
ViewCompat.setTranslationX(view, 0);
dispatchChangeFinished(oldHolder, true);
mChangeAnimations.remove(oldHolder);
dispatchFinishedWhenDone();
// starting 2-nd (Slide Up) animation
if (newView != null)
animateChangeInImpl(newHolder, newView);
}
}).start();
}
2) Slide up new view
private void animateChangeInImpl(final RecyclerView.ViewHolder newHolder,
final View newView) {
// setting starting pre-animation params for view
ViewCompat.setTranslationY(newView, newView.getHeight());
ViewCompat.setAlpha(newView, 0);
mChangeAnimations.add(newHolder);
final ViewPropertyAnimatorCompat animIn = ViewCompat.animate(newView)
.setDuration(getChangeDuration())
.translationY(0)
.alpha(1);
animIn.setListener(new VpaListenerAdapter() {
#Override
public void onAnimationStart(View view) {
dispatchChangeStarting(newHolder, false);
}
#Override
public void onAnimationEnd(View view) {
animIn.setListener(null);
ViewCompat.setAlpha(newView, 1);
ViewCompat.setTranslationY(newView, 0);
dispatchChangeFinished(newHolder, false);
mChangeAnimations.remove(newHolder);
dispatchFinishedWhenDone();
}
}).start();
}
Here is demo image with working scroll and kinda similar animation
https://i.gyazo.com/04f4b767ea61569c00d3b4a4a86795ce.gif
https://i.gyazo.com/57a52b8477a361c383d44664392db0be.gif
Edit:
To speed up RecyclerView preformance, instead of adapter.notifyItemRangeChanged(0, mItems.size()); you probably would want to use something like:
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
int firstVisible = layoutManager.findFirstVisibleItemPosition();
int lastVisible = layoutManager.findLastVisibleItemPosition();
int itemsChanged = lastVisible - firstVisible + 1;
// + 1 because we start count items from 0
adapter.notifyItemRangeChanged(firstVisible, itemsChanged);
First of all:
This solution assumes that items that are still visible, after the dataset changed, also slide out to the right and later slide in from the bottom again (This is at least what I understood you are asking for)
Because of this requirement I couldn't find an easy and nice solution for this problem (At least during the first iteration). The only way I found was to trick the adapter - and fight the framework to do something that it was not intended for. This is why the first part (How it normally works) describes how to achieve nice animations with the RecyclerView the default way. The second part describes the solution how to enforce the slide out/slide in animation for all items after the dataset changed.
Later on I found a better solution that doesn't require to trick the adapter with random ids (jump to the bottom for the updated version).
How it normally works
To enable animations you need to tell the RecyclerView how the dataset changed (So that it knows what kind of animations should be run). This can be done in two ways:
1) Simple Version:
We need to set adapter.setHasStableIds(true); and providing the ids of your items via public long getItemId(int position) in your Adapter to the RecyclerView. The RecyclerView utilizes these ids to figure out which items were removed/added/moved during the call to adapter.notifyDataSetChanged();
2) Advanced Version: Instead of calling adapter.notifyDataSetChanged(); you can also explicitly state how the dataset changed. The Adapter provides several methods, like adapter.notifyItemChanged(int position),adapter.notifyItemInserted(int position),... to describe the changes in the dataset
The animations that are triggered to reflect the changes in the dataset are managed by the ItemAnimator. The RecyclerView is already equipped with a nice default DefaultItemAnimator. Furthermore it is possible to define custom animation behavior with a custom ItemAnimator.
Strategy to implement the slide out (right), slide in (bottom)
The slide to the right is the animation that should be played if items are removed from the dataset. The slide from bottom animation should be played for items that were added to the dataset. As mentioned at the beginning I assume that it is desired that all elements slide out to the right and slide in from the bottom. Even if they are visible before and after the dataset change. Normally RecyclerView would play to change/move animation for such items that stay visible. However, because we want to utilize the remove/add animation for all items we need to trick the adapter into thinking that there are only new elements after the change and all previously available items were removed. This can be achieved by providing a random id for each item in the adapter:
#Override
public long getItemId(int position) {
return Math.round(Math.random() * Long.MAX_VALUE);
}
Now we need to provide a custom ItemAnimator that manages the animations for the added/removed items. The structure of the presented SlidingAnimator is very similar to theandroid.support.v7.widget.DefaultItemAnimator that is provided with the RecyclerView. Also Notice this is a prove of concept and should be adjusted before used in any app:
public class SlidingAnimator extends SimpleItemAnimator {
List<RecyclerView.ViewHolder> pendingAdditions = new ArrayList<>();
List<RecyclerView.ViewHolder> pendingRemovals = new ArrayList<>();
#Override
public void runPendingAnimations() {
final List<RecyclerView.ViewHolder> additionsTmp = pendingAdditions;
List<RecyclerView.ViewHolder> removalsTmp = pendingRemovals;
pendingAdditions = new ArrayList<>();
pendingRemovals = new ArrayList<>();
for (RecyclerView.ViewHolder removal : removalsTmp) {
// run the pending remove animation
animateRemoveImpl(removal);
}
removalsTmp.clear();
if (!additionsTmp.isEmpty()) {
Runnable adder = new Runnable() {
public void run() {
for (RecyclerView.ViewHolder addition : additionsTmp) {
// run the pending add animation
animateAddImpl(addition);
}
additionsTmp.clear();
}
};
// play the add animation after the remove animation finished
ViewCompat.postOnAnimationDelayed(additionsTmp.get(0).itemView, adder, getRemoveDuration());
}
}
#Override
public boolean animateAdd(RecyclerView.ViewHolder holder) {
pendingAdditions.add(holder);
// translate the new items vertically so that they later slide in from the bottom
holder.itemView.setTranslationY(300);
// also make them invisible
holder.itemView.setAlpha(0);
// this requests the execution of runPendingAnimations()
return true;
}
#Override
public boolean animateRemove(final RecyclerView.ViewHolder holder) {
pendingRemovals.add(holder);
// this requests the execution of runPendingAnimations()
return true;
}
private void animateAddImpl(final RecyclerView.ViewHolder holder) {
View view = holder.itemView;
final ViewPropertyAnimatorCompat anim = ViewCompat.animate(view);
anim
// undo the translation we applied in animateAdd
.translationY(0)
// undo the alpha we applied in animateAdd
.alpha(1)
.setDuration(getAddDuration())
.setInterpolator(new DecelerateInterpolator())
.setListener(new ViewPropertyAnimatorListener() {
#Override
public void onAnimationStart(View view) {
dispatchAddStarting(holder);
}
#Override
public void onAnimationEnd(View view) {
anim.setListener(null);
dispatchAddFinished(holder);
// cleanup
view.setTranslationY(0);
view.setAlpha(1);
}
#Override
public void onAnimationCancel(View view) {
}
}).start();
}
private void animateRemoveImpl(final RecyclerView.ViewHolder holder) {
View view = holder.itemView;
final ViewPropertyAnimatorCompat anim = ViewCompat.animate(view);
anim
// translate horizontally to provide slide out to right
.translationX(view.getWidth())
// fade out
.alpha(0)
.setDuration(getRemoveDuration())
.setInterpolator(new AccelerateInterpolator())
.setListener(new ViewPropertyAnimatorListener() {
#Override
public void onAnimationStart(View view) {
dispatchRemoveStarting(holder);
}
#Override
public void onAnimationEnd(View view) {
anim.setListener(null);
dispatchRemoveFinished(holder);
// cleanup
view.setTranslationX(0);
view.setAlpha(1);
}
#Override
public void onAnimationCancel(View view) {
}
}).start();
}
#Override
public boolean animateMove(RecyclerView.ViewHolder holder, int fromX, int fromY, int toX, int toY) {
// don't handle animateMove because there should only be add/remove animations
dispatchMoveFinished(holder);
return false;
}
#Override
public boolean animateChange(RecyclerView.ViewHolder oldHolder, RecyclerView.ViewHolder newHolder, int fromLeft, int fromTop, int toLeft, int toTop) {
// don't handle animateChange because there should only be add/remove animations
if (newHolder != null) {
dispatchChangeFinished(newHolder, false);
}
dispatchChangeFinished(oldHolder, true);
return false;
}
#Override
public void endAnimation(RecyclerView.ViewHolder item) { }
#Override
public void endAnimations() { }
#Override
public boolean isRunning() { return false; }
}
This is the final result:
Update: While Reading the post again I figured out a better solution
This updated solution doesn't require to trick the adapter with random ids into thinking all items were removed and only new items were added. If we apply the 2) Advanced Version - how to notify the adapter about dataset changes, we can just tell the adapter that all previous items were removed and all the new items were added:
int oldSize = oldItems.size();
oldItems.clear();
// Notify the adapter all previous items were removed
notifyItemRangeRemoved(0, oldSize);
oldItems.addAll(items);
// Notify the adapter all the new items were added
notifyItemRangeInserted(0, items.size());
// don't call notifyDataSetChanged
//notifyDataSetChanged();
The previously presented SlidingAnimator is still necessary to animate the changes.
I have a class where I include another layout on a button click. This included layout has some buttons and a code which executes on clicking these buttons. I have used a counter which indicates the number of times the button is clicked. First time clicking on the button includes the layout and the second time clicking removes the views and so on. Here's the code
public class Home extends Fragment implements OnClickListener {
int c = 0;
Button bmain, bnew, bolder;
RelativeLayout r1;
View rootView;
Animation slidedown, slideup;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.home, container, false);
bmain = (Button) rootView.findViewById(R.id.btn2);
bmain.setOnClickListener(this);
return rootView;
}
#Override
public void onClick(View arg0) {
ViewGroup con = null;
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
FrameLayout flContainer = (FrameLayout)rootView.findViewById(R.id.flContainer);
//Loading animation
slidedown = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_down);
slideup = AnimationUtils.loadAnimation(getActivity(), R.anim.slide_up);
//The counter indicates the number of clicks.
//Needs to be replaced for a better solution.
//If it's even add view
if(c%2==0)
{
//Adding layout here
flContainer.addView(layoutInflater.inflate(R.layout.test1,con,false ));
//Starting Animation
flContainer.startAnimation(slidedown);
//After adding layout we can find the Id of the included layout and proceed from there
bnew = (Button) rootView.findViewById(R.id.btntest);
bnew.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
Toast.makeText(getActivity(), "You Clicked New", Toast.LENGTH_LONG).show();
}
});
bolder = (Button) rootView.findViewById(R.id.btntest1);
bolder.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
Intent form = new Intent(getActivity(),FeedbackForm.class);
startActivity(form);
}
});
c++;
} //If ends here
//If it's odd remove view
else
{
flContainer.removeAllViews();
flContainer.startAnimation(slideup);
//flContainer.removeView(flContainer);
//flContainer.removeView(layoutInflater.inflate(R.layout.test1, con, false));
c++;
}
}
}
The code at the end
flContainer.removeAllViews();
flContainer.startAnimation(slideup);
removes the view but fails to process the animation. I have tried using removeView but in that case the buttonclicks in the if statement fail to execute the second time. What am I missing here? How can I achieve it?
The answer is pretty simple. You have to remove the view after the animation is finished. This can be achieved pretty simple, first you have to set an animation listener for your animation and in the onAnimationEnd callback - which is called when the animation is finished - you remove the views.
EDIT:
Replace this:
flContainer.removeAllViews();
flContainer.startAnimation(slideup);
With this:
slideup.setAnimationListener(new Animation.AnimationListener() {
#Override
public void onAnimationStart(Animation animation) {
}
#Override
public void onAnimationEnd(Animation animation) {
flContainer.removeAllViews();
}
#Override
public void onAnimationRepeat(Animation animation) {
}
});
flContainer.startAnimation(slideup);
If there are any further problems let me know.
I am following this tutorial.
there are 3 tabs in my App. in tab3 I m making changes to some views (like buttons and EditText spinners etc) and on the behalf of these changes i have to perform some actions in tab2. Simply you can say that i Change some values in tab3 and effect takes places in tab2. I know how to do this. I just want that my values of view becomes resets every time to default values when switching between the tab2 and tab3
My question is that how can i save the states of my views. so that on resuming the tabs i must get the default look of my views as i had left previously.
One thing more i tell you that i m doing all the work in onCreateView() methos. is this correct way. like this.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Toast.makeText(getActivity(), "onCreateView", Toast.LENGTH_SHORT)
.show();
if (container == null) {
return null;
}
View vi = inflater.inflate(R.layout.settings, container, false);
btnInsert = (Button) vi.findViewById(R.id.btnInsert);
btnInsert.setOnClickListener(this);
btnPosition = (Button) vi.findViewById(R.id.btnPosition);
btnPosition.setOnClickListener(this);
txtPosition = (TextView) vi.findViewById(R.id.txtPosition);
txtLogo = (TextView) vi.findViewById(R.id.txtLogo);
imgLogoPreview = (ImageView) vi.findViewById(R.id.imgLogoPreview);
imgLogoPreview.setOnClickListener(this);
edTxtUserText = (EditText) vi.findViewById(R.id.edTxtPreview);
relLogo = (RelativeLayout) vi.findViewById(R.id.RelLogo);
relText = (RelativeLayout) vi.findViewById(R.id.RelText);
logoWheel = (WheelView) vi.findViewById(R.id.wheelLogo);
logoWheel.setAdapter(new ArrayWheelAdapter<String>(logoWheelList));
logoWheel.setVisibleItems(4);
logoWheel.setCurrentItem(1);
positionWheel = (WheelView) vi.findViewById(R.id.wheelPosition);
positionWheel.setAdapter(new ArrayWheelAdapter<String>(
positionWheelTextList));
// LogoWheel changed listener
changedListenerLogo = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
logoWheel.addChangingListener(changedListenerLogo);
// Wheel scrolled listener
scrolledListenerLogo = new OnWheelScrollListener() {
public void onScrollStarts(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollEnds(WheelView wheel) {
wheelScrolled = false;
btnInsert.setText(logoWheelList[wheel.getCurrentItem()] + "");
wheel.setVisibility(View.INVISIBLE);
if (wheel.getCurrentItem() == 2) {
txtPosition.setVisibility(View.INVISIBLE);
btnPosition.setVisibility(View.INVISIBLE);
relText.setVisibility(View.INVISIBLE);
relLogo.setVisibility(View.INVISIBLE);
} else if (wheel.getCurrentItem() == 1) {
relText.setVisibility(View.VISIBLE);
relLogo.setVisibility(View.INVISIBLE);
txtPosition.setVisibility(View.VISIBLE);
btnPosition.setVisibility(View.VISIBLE);
btnPosition.setText("Top");
positionWheel.setAdapter(new ArrayWheelAdapter<String>(
positionWheelTextList));
positionWheel.setVisibleItems(4);
positionWheel.setCurrentItem(1);
} else if (wheel.getCurrentItem() == 0) {
relLogo.setVisibility(View.VISIBLE);
relText.setVisibility(View.INVISIBLE);
txtPosition.setVisibility(View.VISIBLE);
btnPosition.setVisibility(View.VISIBLE);
btnPosition.setText("Top Left");
positionWheel.setAdapter(new ArrayWheelAdapter<String>(
positionWheelLogoList));
positionWheel.setVisibleItems(4);
positionWheel.setCurrentItem(1);
}
}
};
logoWheel.addScrollingListener(scrolledListenerLogo);
// /////////////////////Positon Wheel Listners///////////
// LogoWheel changed listener
changedListenerPosition = new OnWheelChangedListener() {
public void onChanged(WheelView wheel, int oldValue, int newValue) {
if (!wheelScrolled) {
}
}
};
positionWheel.addChangingListener(changedListenerPosition);
// Wheel scrolled listener
scrolledListenerPosition = new OnWheelScrollListener() {
public void onScrollStarts(WheelView wheel) {
wheelScrolled = true;
}
public void onScrollEnds(WheelView wheel) {
wheelScrolled = false;
String btnStatus = btnInsert.getText().toString();
if (btnStatus.equals("Logo")) {
btnPosition.setText(positionWheelLogoList[positionWheel
.getCurrentItem()] + "");
} else if (btnStatus.equals("Text")) {
btnPosition.setText(positionWheelTextList[positionWheel
.getCurrentItem()] + "");
}
wheel.setVisibility(View.INVISIBLE);
}
};
positionWheel.addScrollingListener(scrolledListenerPosition);
return vi;
}
at what point i must save the states and at what point i should retrieve the savedstates?
Please tell me the how to implement the lifecycle of fragment in simple words.
i also tried the saveInstance() method of fragment. but not called.
Thanks
If I understand you correctly then this might be useful. Instead of recreating Fragments each time you can hide and show them.
This of course preserves your Fragments so is possibly only something you'd do it you had a few tabs. The advantage of this is that
You don't need to worry about saving data and recreating the fragment
Changes are available immediately to the user as soon as the relevant tab is selected.
I have created a class of type BaseAdapter that is populated with buttons - when you click on a button I want to load a new intent. This has proven difficult on two levels:
You cannot associate the event with the button (one that creates a new intent) inside the Adapter. This is why I send the Buttons as an array to my Adapter (this solution works, but it is messy)
Even though my buttons are created inside the same Activity - they cannot create a new intent from that Activity. The exeption is so great that I have not even gotten a try...catch statement to work.
I have tried reflection, creating the buttons inside the activity and passing them through, passing the context (to call context.startIntent(...))
My question: can someone show me how to create a ButtonAdapter where each button creates a new Intent - even of the same type as the original Activity?
UPDATE: Here is the code because I am getting answers from people who think I am struggling with onClickListeners:
public class ButtonAdapter extends BaseAdapter
{
private Context _context;
private Button[] _button;
public ButtonAdapter(Context c, Button[] buttons)
{
_context = c;
_button = buttons;
}
// Total number of things contained within the adapter
public int getCount()
{
return _button.length;
}
// Require for structure, not really used in my code.
public Object getItem(int position)
{
return _button[position];
}
// Require for structure, not really used in my code. Can
// be used to get the id of an item in the adapter for
// manual control.
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
_button[position].setId(position);
return _button[position];
}
}
---------------
The Activity:
public class MainActivity extends Activity
{
private GridView _gv;
private TextView _heading;
private ButtonAdapter _adapter;
public void LoadActivity(String heading)
{
try
{
Itent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Level", "NextPage");
intent.putExtra("Heading", heading);
startActivity(intent);
}
catch (Exception ex)
{
Toast.makeText(getApplicationContext(), String.format("Error LoadActivity: %s", ex.getMessage()), Toast.LENGTH_SHORT).show();
}
}
private void createButtonsAdapter(Button _button[])
{
_buttonadapter = new ButtonAdapter(getApplicationContext(), _button);
_gv.setAdapter(_adapter);
}
private void setupButtons()
{
Button[] _buttons = new Button[2];
String names[] = new String[]{"Button1","Button2"};
for (int i = 0; i < 2; i++)
{
_buttons[i] = new Button(this);
_buttons[i].setText(names[i]);
_buttons[i].setTag(names[i]);
_buttons[i].setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
try
{
LoadActivity(((Button)arg0).getTag().toString());
}
catch(Exception ex)
{
Toast.makeText(getApplicationContext(), String.format("Error button.onClick: %s", ex.getMessage()), Toast.LENGTH_SHORT).show();
}
}
});
}
createButtonsAdapter(_buttons);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_gv = (GridView)findViewById(R.id.gridview);
_heading = (TextView)findViewById(R.id.tv_heading);
Bundle params = getIntent().getExtras();
if (params == null)
{
setupButtons();
}
else if (params.containsKey("Level"))
{
_heading.setText(params.getString("Heading"));
if (params.getString("Level").equals("NextPage"))
{
//code not here yet
}
else if (params.getString("Level").equals("Chapters"))
{
//future code
}
}
}
}
Excuse the bold and caps but I have had enough silly answers to warrent this:
I HAVE TRIED PUTTING THE ONCLICKLISTENER INSIDE THE GRIDVIEW AND IT DOES NOT WORK EITHER
You cannout load an activity from a class outside that activity, even if you pass the context as a parameter. That is why I have resorted to this method, which completely bombs android, even though I have try catch statements.
Please try give me a solution in the form of a correction to my code, other code, or a tutorial that achieves what I want here. I know how to do a button adapter properly, it is the act of loading an Intent that has forced me to implement it this way.
I suggest the following,
Using a common onClick listner for all the buttons in your grid view
Set tag for all the butons in the getView func. of adapter.
Use the tag Object to decide on the intent to fire from the onClick listener.
I hope it helps..
I guess you can easily manipulate your buttons created in your class extending Base adapter. In the getView method .... if you have button b.. then do it as follows
b.setOnClickListener(new OnClickListener()
{
public void onClick()
{
// Do your stuff here ...
}
});
and if you want to start another activity on Click of this button then you need to pass the calling context to this adapter.
Once again I am answering my own question:
http://bottlecapnet.blogspot.com/2012/01/android-buttons-have-no-place-inside.html
I will just have to style TextViews as I want to see them.