我已经在mainActivity的两个片段之一中创建了一个ImageView“ reddot”。在mainActivity的onCreate部分中,使用findViewById(R.id.reddot)查找ImageView'reddot'之后,将setOnClickListener附加到'RedDot'。但是,每次单击红点时,吐司都会出现两次。您能帮我看看我的代码出了什么问题吗?谢谢!

我试图将代码排列在其片段中,结果是相同的,在“ reddot”上单击一次,toast文本将出现两次。我还检查了ImageView'reddot'的XML中没有可点击的设置。

“ reddot”的XML代码为其片段:

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

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawContainer"
android:layout_width="match_parent"

android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginLeft="38dp"
android:background="@color/white" >


<ImageView
android:id="@+id/reddot"
android:layout_width="21dp"
android:layout_height="21dp"
android:layout_marginLeft="60dp"
android:layout_marginTop="120dp"
android:src="@drawable/red20px"
android:adjustViewBounds="true"
android:scaleType="fitXY" />

</RelativeLayout>

</LinearLayout>


mainActivity的onCreate中的代码:

ImageView reddot = (ImageView) findViewById(R.id.reddot);

reddot.setOnClickListener(
        new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String redMsg = "red dot";
                Toast.makeText(getApplicationContext(),
                        redMsg, Toast.LENGTH_SHORT).show();

                }
            }
    );


每当每次单击reddot时,Logcat中的警告消息如下,例如“ W / NotificationService:吐司已经被杀死。pkg = com.example.application callback=android.app.ITransientNotification$Stub$Proxy@f4ef1bd”:

2019-11-10 00:28:01.190 1631-3134/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 24257815 , only wrote 24257520
2019-11-10 00:28:02.529 1631-3134/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 24321795 , only wrote 24321600
2019-11-10 00:28:03.838 1631-3134/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 24384412 , only wrote 24384240
2019-11-10 00:28:04.409 1631-1730/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 24438504 , only wrote 24411600

    --------- beginning of system
2019-11-10 00:28:04.435 1905-4496/? W/NotificationService: Toast already killed. pkg=com.example.application callback=android.app.ITransientNotification$Stub$Proxy@f4ef1bd
2019-11-10 00:28:04.983 1745-2227/? W/SurfaceFlinger: Attempting to destroy on removed layer: 4f1404e Toast#0

最佳答案

您不能在主要活动中的片段视图上设置onClick()。您可以在片段的onCreateView()(红点所在的片段)中使用以下代码:

ImageView reddot = (ImageView) getView.findViewById(R.id.reddot);

reddot.setOnClickListener(
    new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String redMsg = "red dot";
            Toast.makeText(getContext(),redMsg, Toast.LENGTH_SHORT).show();

            }
        }
);


在返回片段视图之前编写此代码。

10-07 18:44