0

onclick メソッドをボタンに追加しますfragment2.xml

   <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>
4

3 に答える 3

1

で呼び出される onClick 関数は、レイアウト インフレータのコンテキストにあります。

フラグメントではなくアクティビティに onClick 関数を配置してみてください。動作するはずです。

以前も同様の問題がありました。

于 2013-03-20T00:19:31.730 に答える
0

なんらかの不明な理由で、同様の問題が発生しました。XML で宣言されている onClick は、一部のデバイスでは機能し、他のデバイスでは機能しませんでした

私は

OnClickListener

同じビューに、そしてこのリスナーで私は呼び出しました

activity.onClick(view)

手動で、それは働いた

アンドロイドの愚かなバグ!!!!

于 2015-09-10T20:49:37.240 に答える
0

私の場合、アクティビティに「onClick」機能があるため、プロジェクトをクリーンアップする必要がありました...その後、xml からの onClick 呼び出しが機能しました。

于 2016-08-03T17:15:13.230 に答える