【问题标题】:Android onClick method is not invoked未调用 Android onClick 方法
【发布时间】:2013-03-08 22:08:49
【问题描述】:

我在fragment2.xml中的按钮上添加了onclick方法

   <Button
        android:id="@+id/getTextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Kliknij do fragment 1"
        android:onClick="onClick" />

然后在Fragment2.java中定义了这个方法

public void onClick(View view){}

但是当我点击它时,应用程序崩溃了?什么是错的完整 下面是 XML 和 java 文件

package com.example.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class Fragment2 extends Fragment {


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance){
        Log.d("Fragment 2", "metoda");
        return inflater.inflate(R.layout.fragment2, container, false);
    }

    public void onClick(View view){}

}

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

    <TextView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Fragment 2"
        android:textColor="#0000FF"
        android:textSize="25sp"/> <!-- moze byc px dp sp -->

    <Button
        android:id="@+id/getTextButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Kliknij do fragment 1"
        android:onClick="onClick" />

</LinearLayout>

【问题讨论】:

  • 你怎么知道没有被调用?
  • 这只对Activity有效

标签: android xml button onclick


【解决方案1】:

将在布局充气器的上下文中调用的 onClick 函数。

尝试将 onClick 函数放在 Activity 而不是 Fragment 中,它应该可以工作。

我之前有一个similar problem

【讨论】:

    【解决方案2】:

    由于某些未知原因,我遇到了类似的问题,我在 XML 中声明的 onClick 在某些设备上工作,而在其他设备上却没有工作

    我分配了一个

    OnClickListener
    

    到同一个视图,在这个监听器中我调用了

    activity.onClick(view)
    

    手动,成功了

    android 中的一个愚蠢的错误!!!!

    【讨论】:

      【解决方案3】:

      在我的情况下,在活动中具有“onClick”功能,我只需要清理项目...... 来自 xml 的 onClick 调用在此之后起作用。

      【讨论】:

        猜你喜欢
        • 2016-07-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多