【问题标题】:Android: Using Object to define View in LayoutAndroid:在布局中使用对象定义视图
【发布时间】:2014-07-12 20:33:34
【问题描述】:

我的帖子是基于之前的帖子,并且大大简化了。

(Android: Two Views On Top of Each Other Using XML)

文件/对象 DrawV 用粉红色的圆圈填充屏幕,并允许触摸一个圆圈使其消失。在另一个文件中,private DrawV drawView = new DrawV(this);这会填充屏幕但不参与布局。

setContentView(drawView) 显示点,所以我知道它有效。我想使用名为 setContentView(R.layout.activity_title); 的布局其中包括屏幕顶部的两个按钮和下方的点。换句话说,我想知道是否有一种方法可以将显示的点放在某种视图中,这种视图可以包含在同一布局中的按钮中。

有什么帮助吗?请问?

如果你需要什么,请告诉我。

【问题讨论】:

    标签: android xml layout view setcontentview


    【解决方案1】:

    如果DrawV 是一个Android 视图(或扩展视图),您可以将它包含在一个常规的xml 布局文件中,然后将该布局文件与setContentView(int) 一起使用。

    要在布局中引用 DrawV 类,您需要使用完全限定名称(与包一起)。

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"
      android:layout_height="match_parent">
    
      <LinearLayout
        android:id="@+id/buttons"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
    
        <Button
          android:id="@+id/button_one"
          android:text="One"
          android:layout_width="0dp"
          android:layout_height="wrap_content"
          android:layout_weight="1.0" />
    
        <Button
          android:id="@+id/button_two"
          android:text="Two"
          android:layout_width="0dp"
          android:layout_height="wrap_content"
          android:layout_weight="1.0" />
      </LinearLayout>
    
      <com.example.views.DrawV
        android:layout_below="@id/buttons"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    
    </RelativeLayout>
    

    上面,RelativeLayout 是你的根视图。 LinearLayout,buttons,是一个 ViewGroup,只是为了保持两个按钮并保持它们的宽度相等(注意layout_width=0dp 和相等的layout_weight)。您的DrawV 视图将布置在buttons 视图下方,然后将匹配父容器的宽度和高度(填充它)。

    如果你把它保存在src/main/res/layout/activity_circles.xml 下,你就可以在你的Activity 中使用setContentView(R.layout.activity_circles) 来设置布局。

    【讨论】:

    • 我赞成你的方法,只是它们不起作用: 给我错误“应用程序 TAP(进程 com.category.tap)已意外停止。请重试。”
    • @user963070 这是在设备上显示给用户的错误。编辑您的问题并将堆栈跟踪放在 LogCat 中可见。
    • 嘿,添加了 logcat。不确定它是否是用于稍微不同版本的布局的 logcat,但确实存在。
    • 你在哪里添加了 logcat?您应该添加在发生崩溃时显示错误的 logcat。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-06
    相关资源
    最近更新 更多