Animation starts only after I've touched the screen - android

I have a layout with a top bar container and a content container. When clicking on a button in the top bar, a vertical menu is displayed using an animation. My minSdkVersion is 9.
This works well when I start the app and I still haven't clicked a menu button (i.e. the content fragment has not changed), but as soon as I have clicked an option (and then replace the fragment in the content_container), the vertical menu behaves erratically. The click event of the menu btn is properly triggered, but the vertical menu is not always shown (but sometimes it is...). However, when I click the button and then touch the screen, the animation (show or hide the menu) starts.
I guess it has something to do with the vertical menu overlapping the content fragment, and then replacing the content fragment modify it in some way, but I can't find any solution.
Anybody can help?
top bar fragment
#Override
public void onActivityCreated (Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
toggleMenu(0);
Button btn_menu = (Button) getView().findViewById(R.id.btn_menu);
btn_menu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mVerticalMenu.setVisibility(View.VISIBLE);
toggleMenu(1000);
}
});
}
private void toggleMenu(int duration){
if(mMenuIsOpen){
TranslateAnimation anim1 = new TranslateAnimation(0,0,0,-(mHeight-mMenuVerticalOffset));
anim1.setFillAfter(true);
anim1.setDuration(duration);
mVerticalMenu.setAnimation(anim1);
AlphaAnimation anim2 = new AlphaAnimation(0.7f, 0.0f);
anim2.setFillAfter(true);
anim2.setDuration(duration);
menu_option_01.setOnClickListener(null);
menu_option_02.setOnClickListener(null);
menu_option_03.setOnClickListener(null);
mMenuIsOpen = false;
}
else{
TranslateAnimation anim1 = new TranslateAnimation(0,0,-(mHeight-mMenuVerticalOffset),0);
anim1.setFillAfter(true);
anim1.setDuration(duration);
mVerticalMenu.setAnimation(anim1);
AlphaAnimation anim2 = new AlphaAnimation(0.0f, 0.7f);
anim2.setFillAfter(true);
anim2.setDuration(duration);
menu_option_01.setOnClickListener(mButtonClickListener);
menu_option_02.setOnClickListener(mButtonClickListener);
menu_option_03.setOnClickListener(mButtonClickListener);
mMenuIsOpen = true;
}
}
private OnClickListener mButtonClickListener = new OnClickListener()
{
public void onClick(View v)
{
toggleMenu(1000);
if(!v.isSelected()){
FragmentTransaction fragmentTransaction = getActivity().getSupportFragmentManager().beginTransaction();
switch(v.getId()){
case R.id.menu_option_01:
// replace content_container by fragment 1
break;
case R.id.btn_02:
// replace content_container by fragment 2
break;
case R.id.btn_03:
// replace content_container by fragment 3
break;
}
}
}
};
private OnClickListener mBgClickListener = new OnClickListener()
{
public void onClick(View v)
{
toggleMenu(1000);
}
};
Main layout
<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" >
<FrameLayout
android:id="#+id/content_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="44dp" />
<FrameLayout
android:id="#+id/top_bar_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipChildren="false" />
</RelativeLayout>
top bar layout
<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"
android:background="#00000000" >
<LinearLayout
android:id="#+id/vertical_menu"
android:layout_width="50dp"
android:layout_height="match_parent"
android:layout_marginTop="44dp"
android:background="#ffffff"
android:orientation="vertical"
android:visibility="gone" >
<!-- menu layout -->
</LinearLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="44dp"
android:background="#ffffff" >
<Button
android:id="#+id/btn_menu"
android:layout_width="50dp"
android:layout_height="44dp"
android:background="#drawable/menubtn" />
<ImageView
android:layout_width="130dp"
android:layout_height="44dp"
android:src="#drawable/logo"
android:layout_alignParentRight="true" />
</RelativeLayout>
</RelativeLayout>

At the end of my Toggle method, I invalidate the root view:
rootView.invalidate();
and now it works. Not quite clear why I must do that though...

I know there is already an accepted answer for this but I had a similar problem and the answer didnt help.
I had a view that I declared at the end of my layout to keep its Z index above its siblings. I had to touch the page to make the animation work.
So I set the Z index again through Java and it worked.
view.bringToFront();

Related

Listview gets cut off when translating by y

Note: These are randomly generated addresses
Hey Guys, Learning Xamarin and I am trying to scroll my Frame Layour down and reveal a search bar for my list view. Here is what is happening:
I color coded my layouts to see if the sizes where a problem, but I dont think they are since my orange layout is plenty big to hold my two entries. Am I using the wrong layouts for this kind of application? I would appreciate any help!
Here is my translation code:
frameLayout.Animate().TranslationYBy(editSearch.Height).SetDuration(500).Start();
And my layout file:
<android.support.v4.widget.SwipeRefreshLayout 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:id="#+id/swipeLayout">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxHeight="100dp"
android:id="#+id/frameLayoutParent"
android:background="#android:color/holo_green_dark">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/frameLayout"
android:background="#android:color/holo_green_light">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="300dp"
android:background="#android:color/holo_orange_light">
<Button
android:text="Add New Address"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/addNewAddress"
android:maxHeight="20dp" />
</LinearLayout>
<ListView
android:paddingTop="50dp"
android:minWidth="25px"
android:minHeight="300dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/myListView"
android:maxHeight="300dp"/>
</FrameLayout>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editSearch"
android:hint="Search ZipCodes"
android:textColor="#000"/>
</FrameLayout>
</android.support.v4.widget.SwipeRefreshLayout>
EDIT:
Here is my OnOptionsItemSelected Code, where my animation is triggered.
public override bool OnOptionsItemSelected(IMenuItem item)
{
switch (item.ItemId)
{
case Resource.Id.action_search:
//search icon has been clicked
if (isAnimating)
return true;
else
{
if (animateBool)
{
//list view is up
animation anim = new animation(myListView, myListView.Height - editSearch.Height);
anim.Duration = 500;
myListView.StartAnimation(anim);
anim.AnimationStart += Anim_AnimationStartDown; //listener for when animation has started
anim.AnimationEnd += Anim_AnimationEndDown;
classSwipeRefresh.Animate().TranslationYBy(editSearch.Height).SetDuration(500).Start();
}
else
{
animation anim = new animation(myListView, myListView.Height + editSearch.Height);
anim.Duration = 500;
myListView.StartAnimation(anim);
anim.AnimationStart += Anim_AnimationStartUp; //listener for when animation has started
anim.AnimationEnd += Anim_AnimationEndUp;
classSwipeRefresh.Animate().TranslationYBy(-editSearch.Height).SetDuration(500).Start();
}
animateBool = !animateBool;
return true;
}
default:
return base.OnOptionsItemSelected(item);
}
}
Learning Xamarin and I am trying to scroll my Frame Layour down and reveal a search bar for my list view. Here is what is happening:
I use your code to test, but I have no problem when translating by Y in SwipeRefreshLayout__Refresh event.
public class MainActivity : AppCompatActivity
{
string[] items;
ListView listview1;
SwipeRefreshLayout swiplayout;
FrameLayout framelayout;
EditText edittext;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
listview1 = FindViewById<ListView>(Resource.Id.myListView);
swiplayout = FindViewById<SwipeRefreshLayout>(Resource.Id.swipeLayout);
framelayout = FindViewById<FrameLayout>(Resource.Id.frameLayout);
edittext = FindViewById<EditText>(Resource.Id.editSearch);
swiplayout.Refresh += Swiplayout_Refresh;
items = new string[] { "Vegetables", "Fruits", "Flower Buds", "Legumes", "Bulbs", "Tubers" };
listview1.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, items);
}
private void Swiplayout_Refresh(object sender, EventArgs e)
{
framelayout.Animate().TranslationYBy(edittext.Height).SetDuration(500).Start();
}
}
This is my screenshot:
If you want to filter ListView, I suggest you can use SearchView in Toolbar to filter listview data, please take a look this sample:
https://github.com/Cheesebaron/SearchView-Sample/tree/master/SearchViewSample

Translate Animation incorrect view move

I have 3 view objects(essentially ImageView's) with in a LinearLayout that in turn is within a RelativeLayout , The views are aligned within the LinearLayout as follows:
1 - 2 - 3 - -
The 3 views are wrapped under the Linear layout as demonstrated above.
Basically the idea is to get the side views(1st and 3rd views) move with animation to the place of the middle view onClick() .(so if 3rd view is clicked it should move to middle view's place and the middle moves right to the 3rd view's place.)
I implemented the translate animation as such that the 3rd view when clicked over 100dp to left and 2nd view moves to right, happens fine, but when I apply the translate animation on the onClick() of 1st view to make it move to right and 2nd to move to left then the 2nd and 3rd views both move collectively!! , This means the views are mapped next to each other automatically by the Android!!(note: that's why I used a LinearLayout so that alignment problems don't occur like 2nd view is aligned_below 1st view and aligned_left of 3rd view problems. )
also another problem is that though the views make a move land on another position that was originally belonging to the other view before the animated movement they still maintain the original view ID ?? For.Example that when 3rd view moves left to 2nd views place and 2nd mvoes to 3rd views place the onClick() still is mapped to their original location's?
XML file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
<RelativeLayout
android:id="#+id/Container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#138AF8" >
<RelativeLayout
android:id="#+id/RelativeLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="#138AF8" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:orientation="horizontal" >
<ImageView
android:id="#+id/ImageView01"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/cost" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/cost" />
<ImageView
android:id="#+id/ImageView02"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#drawable/cost" />
</LinearLayout>
</RelativeLayout>
</RelativeLayout>
</LinearLayout>
Those 3 ImageViews with the names of ImageView1, ImageView01, ImageView02 are the one's I'm trying to animate.
Animation code:
final TranslateAnimation moveLefttoRight = new TranslateAnimation(0,
100, 0, 0);
final TranslateAnimation moveRightToLeft = new TranslateAnimation(0,
-100, 0, 0);
moveRightToLeft.setDuration(1000);
moveLefttoRight.setDuration(1000);
moveRightToLeft.setFillAfter(true);
moveLefttoRight.setFillAfter(true);
final ImageView image1 = (ImageView) findViewById(R.id.imageView1);
final ImageView image2 = (ImageView) findViewById(R.id.ImageView01);
final ImageView image3 = (ImageView) findViewById(R.id.ImageView02);
image1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "image1 clicked",
Toast.LENGTH_SHORT).show();
}
});
image2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "image2 clicked",
Toast.LENGTH_SHORT).show();
image2.startAnimation(moveLefttoRight);
image1.startAnimation(moveRightToLeft);
}
});
image3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
Toast.makeText(getApplicationContext(), "image3 clicked",
Toast.LENGTH_SHORT).show();
image2.startAnimation(moveLefttoRight);
image3.startAnimation(moveRightToLeft);
}
});
Translate animation doesn't actually move the view, it just makes it look like that. You have to set the params before the end of the animation so that the button moves as well.example
with the other issue can you post your xml layout file? do you use weights in the imageviews?
I ended up using ObjectAnimator builtin animating API and this moves the view's position permanently to the co-ords. requested.

LinearLayout larger than screen

I am trying to create a horizontal LinearLayout which is wider than the screen of the device. It contains a Button which will move the layout to view the part outside the screen when it is clicked. The problem is that android is not creating the part outside the screen, so when I press the button, the view moves to show black screen where the remaining view should have been.
My code-
MainActivity.java
public class MainActivity extends BaseGameActivity implements OnClickListener {
private Context mContext;
private int mScreenHeight;
private int mScreenWidth;
private LinearLayout mViewContainer;
private View mTransparentContainer;
private Button mSliderBtn;
private View mSlidingView;
private View mHomeView;
private int mSlidingWidth;
private boolean mIsSlidingMenuVisible = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getApplicationContext();
mScreenHeight = UserScreen.getHeight(mContext);
mScreenWidth = UserScreen.getWidth(mContext);
mSlidingWidth = (int) (getResources().getDimension(R.dimen.sliding_menu_offset) + 0.5f);
mViewContainer = new LinearLayout(mContext);
mViewContainer.setOrientation(LinearLayout.HORIZONTAL);
mViewContainer.setLayoutParams(new LinearLayout.LayoutParams(mScreenWidth + mSlidingWidth, mScreenHeight));
setContentView(mViewContainer);
LinearLayout homeContainer = new LinearLayout(mContext);
LinearLayout.LayoutParams homeContainerParams = new LinearLayout.LayoutParams(mScreenWidth, LayoutParams.MATCH_PARENT);
mHomeView = getLayoutInflater().inflate(R.layout.activity_main, homeContainer);
mHomeView.setBackgroundColor(0x80ffffff);
mViewContainer.addView(homeContainer, homeContainerParams);
LinearLayout slidingContainer = new LinearLayout(mContext);
LinearLayout.LayoutParams slidingContainerParams = new LinearLayout.LayoutParams(mSlidingWidth, LayoutParams.MATCH_PARENT);
mSlidingView = getLayoutInflater().inflate(R.layout.slider_menu, slidingContainer);
mViewContainer.addView(slidingContainer, slidingContainerParams);
initUi();
// other code
}
public void initUi() {
mSliderBtn = (Button) mHomeView.findViewById(R.id.button_slider);
mSliderBtn.setOnClickListener(this);
mTransparentContainer = mHomeView.findViewById(R.id.transparent_container);
mTransparentContainer.setOnClickListener(this);
// other code
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button_slider:
mSliderBtn.setEnabled(false);
mIsSlidingMenuVisible = true;
mTransparentContainer.setVisibility(View.VISIBLE);
mTransparentContainer.bringToFront();
tableMoveLeft(mViewContainer, mSlidingWidth);
break;
case R.id.transparent_container:
mSliderBtn.setEnabled(true);
mIsSlidingMenuVisible = false;
mTransparentContainer.setVisibility(View.GONE);
tableMoveRight(mViewContainer, mSlidingWidth);
break;
// other cases
}
}
// Animation Functions
public void tableMoveLeft(final View container, final float newPos){
ObjectAnimator moveLeft = ObjectAnimator.ofFloat(container, "translationX", 0, -newPos);
moveLeft.setDuration(300);
moveLeft.start();
}
public void tableMoveRight(final View container, final float newPos){
ObjectAnimator moveRight = ObjectAnimator.ofFloat(container, "translationX", -newPos, 0);
moveRight.setDuration(300);
moveRight.start();
}
// other code
}
activity_main.xml
<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"
android:background="#drawable/bg_menu"
tools:context="${relativePackage}.${activityClass}" >
<!-- other code -->
<Button
android:id="#+id/button_slider"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="10dip"
android:layout_marginTop="30dip"
android:background="#drawable/move" />
<View
android:id="#+id/transparent_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#80800000"
android:visibility="gone" />
</RelativeLayout>
slider_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/image_info_bg_popup"
android:orientation="vertical" >
<!-- Other Code -->
</LinearLayout>
My Output on clicking the button
Using a ScrollView is not a solution because I dont want the user to freely scroll the view, and also there is a ViewPager in the main layout which will conflict with it. Please help. Thanks.
Android officially introduced sliding panel menu by introducing a newer concept called Navigation Drawer. Most of the time Sliding Menu (Navigation Drawer) will be hidden and can be shown by swiping the screen from left edge to right or tapping the app icon on the action bar.
For example, the following layout uses a DrawerLayout with two child views: a FrameLayout to contain the main content (populated by a Fragment at runtime), and a ListView for the navigation drawer.
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- The main content view -->
<FrameLayout
android:id="#+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView android:id="#+id/left_drawer"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#111"/>
for additional info about NavigationDrawer, please take a look into these links :
http://www.androidhive.info/2013/11/android-sliding-menu-using-navigation-drawer/
http://developer.android.com/training/implementing-navigation/nav-drawer.html
The problem was that the layout with size larger than screen size was set as the root container of the activity. I don't know what was the problem caused by that, but to fix it-
#Override
public void onCreate(Bundle savedInstanceState) {
super(savedInstanceState);
LinearLayout rootContainer = new LinearLayout(mContext);
setContentView(rootContainer);
// other code
rootContainer.addView(mViewContainer);
}
Any explanations of why having a root view larger than screen size created a problem are welcome :)

Translate animation is behind other layout

I have four linear layouts in my screen.
The first layout contain a textview.
I'm trying to move my textView to the the fourth layout of the right with a translate animation.
But when i do that the text view move behind the other layout and if i move my layout from the fourth layout of the right to the first at the left it's ok.
Im my xml i have put : in all layouts
android:clipChildren="false"
image
Can you help me ?
Thank you
Use setZAdjustment to put your View in front of the other Views.
http://developer.android.com/reference/android/view/animation/Animation.html#setZAdjustment%28int%29
Pre-Kitkat :
yourLayout.bringToFront();
((View)yourLayout.getParent()).requestLayout();
((View)yourLayout.getParent()).invalidate();
KitKat :
yourLayout.bringToFront();
Android linear layout construction starts from first element from the beginning. So any element defined first will be created and then rest, so no matter what you do, you cannot achieve with linear layout. Try with relative layout
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:id="#+id/testAnimTranslate"
android:layout_width="wrap_content"
android:layout_height="80dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:gravity="center_vertical"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="30dp"
android:layout_height="70dp"
android:background="#0000dd"
android:orientation="vertical" />
<LinearLayout
android:layout_width="30dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:background="#0dd0dd"
android:orientation="vertical" />
<LinearLayout
android:layout_width="30dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:background="#ddd0dd"
android:orientation="vertical" />
<LinearLayout
android:layout_width="30dp"
android:layout_height="70dp"
android:layout_alignParentBottom="true"
android:background="#44d0dd"
android:orientation="vertical" />
</LinearLayout>
<TextView
android:id="#+id/textAnimate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#id/testAnimTranslate"
android:layout_alignTop="#id/testAnimTranslate"
android:layout_toLeftOf="#id/testAnimTranslate"
android:gravity="center"
android:background="#00000000"
android:text="qweqwew" />
</RelativeLayout>
Define your translate anim in anim folder or programatically. make sure to add
LinearInterpolator
setFillAfter to true
and start the anim
I think you create the view in the code, so you should add setClipChildren(false)
in your constructor too.
Look at the docs:
ZORDER_TOP: Requests that the content being animated be forced on top of all other content for the duration of the animation.
Please check that setFillAfter(true) does not match this usage.
Does it help?
The main problem with what you are trying to do, is that you want to draw a View outside of its parent. It goes behind the other LinearLayouts because they are drawn after the LinearLayout parent of the View. Even if it is brought to the front, it seems that only relates to children within a single parent?
If you look at how Fragment animations work, you need to recreate the Fragment to translate a from one Frame into another. You also need two separate animations.
BlackBeard's solution will work because it makes the TextView a child of the outermost parent and declares it last. This means the TextView is drawn after everything else and therefore will be drawn on top of everything else.
This doesn't achieve what I think you are trying to do. If you want the TextView to belong to its destination LinearLayout after the animation you'll need to recreate the TextView and add it to the LinearLayout in the correct position in the hierarchy. You'll also need a second animation to move the new TextView into its position.
If done properly the animations should overlay each other perfectly and if in a LinearLayout one or the other of the animated Views will pass on top of everything else.
activity_main.xml
<LinearLayout
android:id="#+id/frame"
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"
android:clipChildren="false"
android:orientation="horizontal"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/layout1"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFAABBCC"
android:orientation="vertical">
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="24sp"
android:text="I'm some text"/>
</LinearLayout>
<LinearLayout
android:id="#+id/layout2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFBBCCAA"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="#+id/layout3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFCCAABB"
android:orientation="vertical">
</LinearLayout>
<LinearLayout
android:id="#+id/layout4"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#FFBBAACC"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
MainActivity.java
private LinearLayout mLayout1;
private LinearLayout mLayout2;
private LinearLayout mLayout3;
private LinearLayout mLayout4;
private TextView mTextView;
private View.OnTouchListener mOnTouchListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLayout1 = (LinearLayout) findViewById(R.id.layout1);
mLayout2 = (LinearLayout) findViewById(R.id.layout2);
mLayout3 = (LinearLayout) findViewById(R.id.layout3);
mLayout4 = (LinearLayout) findViewById(R.id.layout4);
mTextView = (TextView) findViewById(R.id.textView);
mOnTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// simple trigger to start the animation.
startAnimation();
mTextView.setOnTouchListener(null);
return true;
}
};
mTextView.setOnTouchListener(mOnTouchListener);
}
private void startAnimation() {
final LinearLayout origin = (LinearLayout) mTextView.getParent();
LinearLayout destination = null;
// I'm not sure what kind of behaviour you want. This just randomises the destination.
do {
switch (new Random().nextInt(4)) {
case 0:
destination = mLayout1;
break;
case 1:
destination = mLayout2;
break;
case 2:
destination = mLayout3;
break;
case 3:
destination = mLayout4;
break;
default:
}
// if destination == origin or is null, try again.
} while (destination == origin || destination == null);
// Create another TextView and initialise it to match mTextView
final TextView textViewNew = new TextView(this);
textViewNew.setText(mTextView.getText());
textViewNew.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextView.getTextSize());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
textViewNew.setLayoutParams(params);
textViewNew.setOnTouchListener(mOnTouchListener);
// Add the new TextView to the destination LinearLayout
destination.addView(textViewNew);
// Create animations based on origin and destination LinearLayouts
ObjectAnimator outAnimator = getOutAnimator(origin, destination);
// The in animator also requires a reference to the new TextView
ObjectAnimator inAnimator = getInAnimator(textViewNew, origin, destination);
// All animators must be created before any are started because they are calculated
// using values that are modified by the animation itself.
outAnimator.start();
inAnimator.start();
// Add a listener to update mTextView reference to the new TextView when complete.
inAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
origin.removeView(mTextView);
mTextView = textViewNew;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
}
/**
* This method creates an ObjectAnimator to move the existing TextView out of its parent
* towards its destination
*/
private ObjectAnimator getOutAnimator(View origin, View destination) {
// Calculate the difference between x of destination and of origin
float layoutDifferenceX = destination.getX() - origin.getX();
// initialX is simply mTextView.getX()
// the distance moved == layoutDifferenceX
float finalX = mTextView.getX() + layoutDifferenceX;
ObjectAnimator animator = ObjectAnimator.ofFloat(mTextView, "x",
mTextView.getX(), finalX);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.setDuration(500);
return animator;
}
/**
* This method creates an ObjectAnimator to move the new TextView from the initial position
* of mTextView, relative to the new TextView's parent, to its destination.
*/
private ObjectAnimator getInAnimator(View newView, View origin, View destination) {
// Calculate the difference between x of destination and of origin
float layoutDifferenceX = destination.getX() - origin.getX();
// initialX relative to destination
float initialX = mTextView.getX() - layoutDifferenceX;
// finalX relative to destination == initialX relative to origin
float finalX = mTextView.getX();
ObjectAnimator animator = ObjectAnimator.ofFloat(newView, "x",
initialX, finalX);
animator.setInterpolator(new AccelerateDecelerateInterpolator());
animator.setDuration(500);
return animator;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
EDIT: You could also declare the TextView in xml and inflate it to get rid of all the code initialising it.

On animation, part of listview is not showing

I have researched the questions thoroughly, but could not yet find the answer. Also, my excuses for my poor english since I am not a native speaker.
The problem: in my android layout we have a status_text with a listview below the status_text. When the status_text is touched, we animate a 'move down' on the status_text and listview so that only the first of the listview row is still on screen. The listview is now still usable.
When the status_text is touched again, we move the status_text and listview up so that the listview uses half of the screen.
The problem we are facing is that during the 'move up' only the first row is animated. After the 'move up' the other rows suddenly appear.
What we would like to have is a 'move up' where the previously hidden rows slide onto the screen.
The layout:
We are using this layout (slightly simplified to focus on the problem at hand):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/fragment_declareren_choose_verzekerden"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- Dummy anchor to put top of listview in the middle of the screen -->
<RelativeLayout
android:id="#+id/anchor"
style="#style/anchor_status_container"
android:layout_centerVertical="true" >
</RelativeLayout>
<!-- Example image -->
<ImageView
android:id="#+id/my_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/footer"
android:adjustViewBounds="true"
android:contentDescription="#string/image_description"
android:scaleType="centerCrop"
android:src="#drawable/empty" />
<!-- Clickable text which moves up and down on click -->
<RelativeLayout
android:id="#+id/status_container"
style="#style/status_container"
android:layout_alignTop="#id/anchor"
android:background="#color/white" >
<TextView
android:id="#+id/status_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginRight="#dimen/spacing_sml"
android:layout_alignTop="#id/status_container" />
</RelativeLayout>
<!-- Listview which moves up and down with the status_container -->
<RelativeLayout
android:id="#+id/listView_container"
style="#style/padding_content_horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/status_container"
android:background="#color/white" >
<ListView
android:id="#+id/mylistView"
style="#style/myListviewStyle"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:divider="#null"
android:dividerHeight="0dp" />
</RelativeLayout>
<!-- Footer with buttons -->
<RelativeLayout
android:id="#+id/footer_button_container"
style="#style/footer"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/button_again"
style="#style/btn_secondary"
android:layout_width="wrap_content"
android:layout_alignParentLeft="true"
android:text="#string/opnieuw"
android:visibility="gone" />
<Button
android:id="#+id/button_next"
style="#style/btn_primary"
android:layout_width="wrap_content" />
</RelativeLayout>
</RelativeLayout>
And the code (again a bit simplified to show only the problem at hand. Some fade-in/out and rotations are removed):
// The code
#Override
public void onClick(View view)
{
int viewId = view.getId();
if (viewId == R.id.status_container)
{
// Someone clicked the text, move the statusbar (and so the listview) up or down
if (this.viewIsInUpperPosition)
{
startStatusAnimation();
}
}
}
private void startStatusAnimation()
{
if (animationIsRunning)
{
return;
}
setAnimationIsRunning(animValues.START);
// 0. Initialisation
final View statusContainer = (View) getView().findViewById(R.id.status_container);
final View listContainer = (View) getView().findViewById(R.id.listView_container);
final ListView listView = (ListView) getView().findViewById(R.id.myListView);
final View footerButtonContainer = (View) getView().findViewById(R.id.footer_button_container);
// 1. Calculate distance for animation
if (toggleViewDistance == 0)
{
int listViewContainerHeight = listContainer.getHeight();
int footerHeight = footerButtonContainer.getHeight();
int spaceForListView = listViewContainerHeight - footerHeight;
toggleViewDistance = spaceForListView;
}
// 2. Decide if the movement is up or down
float translationDistance = (viewIsInUpperPosition) ? toggleViewDistance : 0 - toggleViewDistance;
// 3. Create the animation
TranslateAnimation yMove = new TranslateAnimation(0, 0, 0, translationDistance);
yMove.setDuration(animValues.ANIMATION_Y_DURATION);
yMove.setInterpolator(new AccelerateDecelerateInterpolator());
// Do here something with scaling and rotating of other objects, not relevant for the question on StackOverflow
// 4. Actions after animation
yMove.setAnimationListener(new AnimationListener()
{
#Override
public void onAnimationEnd(Animation arg0)
{
// Fade de listView in als je van onderen naar boven animeert
if (!viewIsInUpperPosition)
{
// Do some fading, outside scope of question
}
// Create layout after the animation
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) statusContainer.getLayoutParams();
if (viewIsInUpperPosition)
{
// View was previously in upper position, now put the statusbar aligned with the footer
params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ABOVE, footerButtonContainer.getId());
}
else
{
// View was previously in bottom position, so put it under the anchor
params = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_TOP, R.id.anchor);
}
}
statusContainer.setLayoutParams(params); // Set the new layout params
viewIsInUpperPosition = !viewIsInUpperPosition;
setAnimationIsRunning(animValues.END);
}
#Override
public void onAnimationRepeat(Animation arg0)
{
// Empty
}
#Override
public void onAnimationStart(Animation arg0)
{
// empty
}
});
// 5. Start the animation
statusContainer.startAnimation(yMove);
listContainer.startAnimation(yMove);
}
Any advice on how to have the rows of the listview 'slide in' on the screen? Much appreciated!
I figured it out. So I am answering my own question in case someone stumbles upon this question.
What needs to be done is that the listview is drawn off-screen. This can be forced by calling the measure- and layout-methods with the off-screen coordinates of the listview.
This fixed it for my code:
// 5a. Draw the listview off-screen
if (translationDistance < 0)
{
// Do this only when the listview is sliding up, e.g. sliding the window in.
int listViewContainerVerticalPos = listContainer.getTop(); // De positie van de listview
// The required height of the listview
int listContainerHeight = (int) Math.abs(translationDistance) + statusContainer.getHeight();
int measureWidth = View.MeasureSpec.makeMeasureSpec(listContainer.getWidth(), View.MeasureSpec.EXACTLY);
int measureHight = View.MeasureSpec.makeMeasureSpec(listContainerHeight, View.MeasureSpec.EXACTLY);
listContainer.measure(measureWidth, measureHight);
listContainer.layout(0, listContainerVerticalPos, listContainer.getMeasuredWidth(), listContainerVerticalPos
+ listContainerHeight);
}

Categories

Resources