Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (4k points)

I am creating all of the elements in my android project dynamically. I am trying to get the width and height of a button so that I can rotate that button around. I am just trying to learn how to work with the android language. However, it returns 0.

I did some research and I saw that it needs to be done somewhere other than in the onCreate() method. If someone can give me an example of how to do it, that would be great.

Here is my current code:

package com.animation;

import android.app.Activity;

import android.os.Bundle;

import android.view.animation.Animation;

import android.view.animation.LinearInterpolator;

import android.view.animation.RotateAnimation;

import android.widget.Button;

import android.widget.LinearLayout;

public class AnimateScreen extends Activity {

//Called when the activity is first created.

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    LinearLayout ll = new LinearLayout(this);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);

    layoutParams.setMargins(30, 20, 30, 0);

    Button bt = new Button(this);

  bt.setText(String.valueOf(bt.getWidth()));

    RotateAnimation ra = new RotateAnimation(0,360,bt.getWidth() / 2,bt.getHeight() / 2);

    ra.setDuration(3000L);

    ra.setRepeatMode(Animation.RESTART);

    ra.setRepeatCount(Animation.INFINITE);

    ra.setInterpolator(new LinearInterpolator());

    bt.startAnimation(ra);

    ll.addView(bt,layoutParams);

    setContentView(ll);

}

Any help is appreciated.

1 Answer

0 votes
by (46k points)

Don't call getWidth() too early. The UI has not been sized and set out on the screen yet.

I suspect you want to be making what you are making, nevertheless -- widgets remaining animated don't alter their clickable areas, and so the button will still react to clicks in the initial orientation regardless of how it has rotated.

That being stated, you can practice a dimension resource to establish the button size, then reference that dimension resource from your layout file and your source code, to bypass this problem. 

Here's an example:

@Override

 public void onWindowFocusChanged(boolean hasFocus) {

  super.onWindowFocusChanged(hasFocus);

  //you can get the size here.

 }

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...