android - 带有 subview 的自定义布局

标签 android android-custom-view

我在这方面遇到了错误。无法弄清楚如何在我的自定义 View (相对布局)中使用 subview 。

   <RelativeLayout >   

    <com.xxxxxx.FavouriteImageView
        android:id="@+id/favorite_status"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="15dp"
        android:clickable="true" >

        <ImageView
            android:id="@+id/favourite_iv"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/yellow_star"
            android:clickable="false" />

        <ProgressBar
            android:id="@+id/favorite_spinner"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"
            android:clickable="false" />

    </com.xxxxxxxx.FavouriteImageView>

public class FavouriteImageView extends RelativeLayout{

ImageView star;
ProgressBar spinner;
boolean isFavorite;

Context context;

public FavouriteImageView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context= context;
    findChildViews();}

public FavouriteImageView(Context context, AttributeSet attrs) {
    super(context, attrs);
    this.context= context;
    findChildViews();
}

public FavouriteImageView(Context context) {
    super(context);
    this.context= context;
    findChildViews();}


private void findChildViews(){

    star = (ImageView) findViewById(R.id.favourite_iv);
    spinner = (ProgressBar) findViewById(R.id.favorite_spinner);
}

问题是每当我尝试使用 starspinner 时,我总是遇到 NPE。不知道如何使用 subview 。

最佳答案

您无法在构造函数中找到这些 View 。 subview 尚未添加到父 View 。

对于您的情况,您可以覆盖 addView() 方法并执行相同的操作:

@Override
public void addView(View child, int index, LayoutParams params) {
    super.addView(child, index, params);
    switch (child.getId()) {
    case R.id.favourite_iv:
        spinner = (ProgressBar) child;
        break;
    case R.id.favorite_spinner:
        star = (ImageView) child;
        break;
    }
}

关于android - 带有 subview 的自定义布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26970540/

相关文章:

javascript - 如何直接从手机使用 .apk 链接下载 Android 应用程序?

android - 如何检查图库中的图像是从相机还是屏幕截图中拍摄的?

Android:如何捕捉软键盘的每一次触摸输入?

java - 在 Android 中 inflatedView 后,自定义 View 子项为空

Android 如何在images目录下创建自己的文件夹?

android - 使用 Glide 使用生成器生成位图

android - 在android中保存/恢复自定义 View 的状态

android - 在使线性布局容器无效后未调用 subview 的 ondraw()

android - 有没有像ICS的解锁屏一样 "Drag and Drop to unlock"组件的开源项目?

android - CustomLayout 的 subview 中出现意外的命名空间前缀应用程序