有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在XML文件中使用视图组件的java(Android)

首先,如果我的问题很基本,我想道歉——我不知道哪些关键词对找到答案有用

我知道如何编写两种“类型”的应用程序——由用户运行的应用程序。xml文件(例如,从摄氏度到华氏度的转换器、一些选项菜单等),以及与扩展视图的类一起运行的文件(对于具有图形组件的应用程序)。我的问题是,如何将它们结合起来?更准确地说,如何将视图组件添加到XML文件中?实用示例:在“选项”菜单中绘制一个圆圈,一旦触碰它就会移动

先谢谢你


共 (2) 个答案

  1. # 1 楼答案

    我不知道如何在选项菜单中画一个圆圈,但一般来说,您可以像这样在布局XML中使用自定义视图类

    <com.testing.MyCustomView
      id="@+id/my_view"
      ... />
    

    与使用文本视图、图像视图等相比,使它们非常相似

  2. # 2 楼答案

    要在XML中使用自定义视图,您需要

    • 对视图进行编码,使其接受AttributeSet。例如:

      公共活动标题视图(上下文、属性集属性)

    • 定义可设置样式的属性。它们进入res/values/attr。xml

    <resources>
        <declare-styleable name="ActivityTitleView">   
            <attr name="text" format="string"/>
            <attr name="helpContext" format="string"/>   
        </declare-styleable>
    </resources
    
    • 使用自己的名称空间在XML中包含视图。如果需要属性,则自己的命名空间很重要:

    < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:yournamespace="http://schemas.android.com/apk/res/com.yourpackage" >

    <com.yourpackage.ActivityTitleView yournamespace:text="Bla Bla"  
               android:layout_width="fill_parent"
               android:layout_height="wrap_content"/>
    
    • 提取代码中的属性
         TypedArray array = context.obtainStyledAttributes(attrs,
              R.styleable.ActivityTitleView, 0, 0);
         String text = array.getString(R.styleable.ActivityTitleView_text);
         helpContext = array.getString(R.styleable.ActivityTitleView_helpContext);
    

    抱歉,StackOverflow似乎无法很好地格式化我的代码段。请随意编辑格式