簡體   English   中英

App停止工作在CircleImageView的setImageResource上

[英]App Stopped Working On setImageResource of CircleImageView

我必須在app中水平地使用java代碼動態顯示一些圖像。 我可以使用簡單的ImageView來做到這一點。 但是,使用CircleImageView通過“hdodenhof”。 我只能在XML文件中使用硬編碼的靜態圖像。 我希望從我的java代碼中動態選擇源代碼。 我嘗試了一些選擇。 但該應用程序似乎停止工作。 有什么我能做的嗎? 先感謝您。

這是我的DisplayMessageActivity.java文件

import de.hdodenhof.circleimageview.CircleImageView;

LinearLayout pages=findViewById(R.id.pages);
LayoutInflater inflater=LayoutInflater.from(this);

for(int i=0;i<6;i++){
    View view = inflater.inflate(R.layout.item,pages,false);
    CircleImageView circleImageView=findViewById(R.id.circleimage);
    circleImageView.setImageResource(R.drawable.test);
    pages.addView(view);
}

item.xml文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <de.hdodenhof.circleimageview.CircleImageView
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/circleimage"
        android:layout_width="96dp"
        android:layout_height="96dp"
        android:src="@mipmap/ic_launcher"
        app:civ_border_width="4dp"
        app:civ_border_color="#00000000"/>
</LinearLayout>

最后是activity_display_message.xml文件

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DisplayMessageActivity">

    <HorizontalScrollView
        android:layout_width="0dp"
        android:layout_height="190dp"
        android:scrollbars="none"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <LinearLayout
            android:id="@+id/pages"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="horizontal" />
    </HorizontalScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

應用程序在對話框中顯示以下消息,應用程序崩潰。

Testingapp停止工作了

我猜你得到一個空指針異常,這就是應用程序崩潰的原因。 您的活動看起來將內容視圖設置為onCreate函數中setContentView中的activity_display_message.xml布局。 因此, findViewById只能從該布局中找到引用。

CircleImageView以不同的布局定義,在你的活動中沒有膨脹,因此當你在做findViewById(R.id.circleimage); - 您正在獲取空指針異常,因為指令未找到您要查找的視圖。

您需要從您在for循環中充氣的視圖中CircleImageView的布局參考。 我認為以下內容可以解決您的問題。

CircleImageView circleImageView = view.findViewById(R.id.circleimage);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM