我有一个扩展 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/