android - 如何将 View 添加到 XML 布局 android

标签 android view android-animation

我有一个 XML 布局,其中包含我所有的按钮和图像,我希望在我的布局顶部有一个移动的云。所以我创建了一个 View 并使我的云移动,但是我无法将 View 与布局链接起来。这是我的 View 代码

public class CloudView extends View {

Bitmap cloud;
int ChangingX;


public CloudView(Context context) {
    // TODO Auto-generated constructor stub
    super(context);
    cloud = BitmapFactory.decodeResource(getResources(), R.drawable.cloud);
    ChangingX = 50;

}

@Override
protected void onDraw(Canvas canvas) {
    // TODO Auto-generated method stub
    super.onDraw(canvas);
    canvas.drawBitmap(cloud, ChangingX , 50, null);
    if (ChangingX < canvas.getWidth())
        ChangingX += 2;
    else
        ChangingX = 50;
    invalidate();
}

}

这是我的 MainActivity

public class MainActivity extends Activity {

CloudView myView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myView = new CloudView(this);
    setContentView(myView);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

 }

我是 android 动画方面的新手,您能详细解释一下我如何将 View 与布局链接起来吗? 如果它不起作用,我可以使用除 View 之外的其他类。

感谢您的时间和考虑。抱歉我的英语不好。

最佳答案

这是 Android 开发人员链接,可能对您有用。

Define Custom Attributes

如何定义属性:

要定义自定义属性,请将资源添加到您的项目中。通常将这些资源放入 res/values/attrs.xml 文件中。下面是一个 attrs.xml 文件的示例:

<resources>
   <declare-styleable name="PieChart">
       <attr name="showText" format="boolean" />
       <attr name="labelPosition" format="enum">
           <enum name="left" value="0"/>
           <enum name="right" value="1"/>
       </attr>
   </declare-styleable>
</resources>

如何在XML中使用

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">
 <com.example.customviews.charting.PieChart
     custom:showText="true"
     custom:labelPosition="left" />
</LinearLayout>

请阅读更多详细信息。

关于android - 如何将 View 添加到 XML 布局 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16996355/

相关文章:

java - 如何在Achartengine(Android)中分离主代码和图表代码

Scala:通过方法进行隐式转换(例如 toString)

java - 以编程方式声明 View 时应用什么单位?

android - 如何连接多个 recyclerview 或 fragment 以显示动画

android - 如何以恒定速度连续旋转 View ?

android - 伪元素在 webview 中不起作用之后

android - 刷新抽屉导航中的标题

sql - WITH AS (SELECT) 语句的 CREATE VIEW 语法

android - translationY 动画后显示空白

android - 在 Activity 之间共享全局变量的最佳实践