android - 通过 Activity 中在 xml 中声明的 id 获取自定义 View 的引用

标签 android android-layout view reference

我有一个扩展 ImageView 的自定义 View ,我在这样的 XML 布局中使用它:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:layout_gravity="center"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp">

        <com.android.example.MyView
            android:id="@+id/myview1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />

        <com.android.example.MyView
            android:id="@+id/myview2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp" />

    </LinearLayout>

</LinearLayout>

在我的 Activity 中,我执行通常的操作:setContentView(R.layout.myLayout)。

现在,我需要获取我的类/ View “MyView”的引用以便设置自定义监听器,但我无法从 ID 中获取它。

myview (MyView) findViewById(R.id.myview1);

返回空值。

我试图查看类似的问题,但没有找到任何对我有帮助的问题。

请注意,如果我从 Activity 以编程方式将 View 添加到布局,一切都工作正常,但我希望能够找到这里的问题所在。

提前致谢。

最佳答案

它确实有效。

您用于 setContentView 的布局必须与您添加自定义 View 的布局相同。

关于android - 通过 Activity 中在 xml 中声明的 id 获取自定义 View 的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15041788/

相关文章:

php - 当相关表结构改变时mysql自动更新 View ?

java - 在膨胀布局上调用度量时出现空指针异常

android - imageView.getWidth();返回屏幕而不是位图宽度

mysql - 查看mysql中计算余额

android - RSRuntimeException : Loading of ScriptC script failed (build tools 19. 0.2)

XLarge 设备的 Android 布局

ruby-on-rails - 如何在 Rails 的 application.html.erb 中显示不同的 header ?

android - 嵌套的线性布局权重对一纵一横不利吗

android - 在设备发现开启时连接蓝牙套接字

android - 键盘一直挡住我的视线...如何解决?