简体   繁体   English

如何将变量从.java文件传递到android中的.xml文件?

[英]How to pass a variable from .java file to .xml file in android?

I am new to android and I want to simulate a car steering wheel. 我是Android新手,我想模拟汽车方向盘。 I found it easy to insert an Image(of steering wheel) and use tween animation to rotate it though XML. 我发现插入图像(方向盘)并使用补间动画通过XML旋转图像很容易。

I measured the rotation of the phone using sensor classes in .java file. 我使用.java文件中的传感器类测量了手机的旋转角度。

Now I need to pass this measured value from .java file to .xml (under res\\anim) so as to rotate the image as per the roation of the phone. 现在,我需要将此测量值从.java文件传递到.xml (在res \\ anim下),以便按照手机的旋转方式旋转图像。

Kindly help me by advicing a way to do this. 请提出一种方法来帮助我。

It's impossible to pass calculated value to xml resource, since resources are static. 由于资源是静态的,因此无法将计算出的值传递给xml资源。

But you can load the xml animation with 但是您可以使用以下方式加载xml动画

Animation anim = AnimationUtils.loadAnimation(context, id)

modify its properties 修改其属性

and apply it to the desired view with 并将其应用于所需的视图

desiredView.startAnimation(anim);

M1shk4 and Chet Haase, as told "It's impossible to pass calculated value to xml resource" M1shk4和Chet Haase,被告知“不可能将计算值传递给xml资源”

So to implement my requirement, we need to do it using code in . 因此,要实现我的要求,我们需要使用中的代码来实现。 Java file. Java文件。

The below was the code I got from Chet Haase: 以下是我从Chet Haase获得的代码:

public void turn()  
{ 
RotateAnimation anim = new RotateAnimation(currentRotation, currentRotation + 30,Animation.RELATIVE_TO_SELF, 0.5f,nimation.RELATIVE_TO_SELF,0.5f);     
currentRotation = (currentRotation + 30) % 360;     
anim.setInterpolator(new LinearInterpolator());     
anim.setDuration(1000);     
anim.setFillEnabled(true);      
anim.setFillAfter(true);     
turnImg.startAnimation(anim); 
} 

Its working fine: ) 工作正常:)

For more info 欲了解更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM