片段活动中的onclick事件不起作用

时间:2016-09-15 07:01:36

标签: android android-fragments

我有一个活动A,其中我有一个片段。

在此活动中,片段根据活动A中的用户输入更改为片段A(调用活动A时的默认值)或片段B.

在片段A和A中。 B我有一个点击监听器的按钮。 但此按钮仅适用于活动A开始时的第一次。

当用户更改片段时,这些片段中的按钮会在点击时停止响应。

请建议我需要做些什么才能在片段A和A中制作按钮。 B在用户更改片段时起作用。

我将根据此代码的用户输入替换片段:

fr = new FragmentOneDice();
FragmentManager fm = getFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_place, fr);
fragmentTransaction.commit();

在片段活动代码中对于单击侦听器按钮是这样的。

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import java.util.ArrayList;
import java.util.Collections;

public class FragmentOneDice extends Fragment implements View.OnClickListener {

    Button button1;
    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        //Inflate the layout for this fragment


        view = inflater.inflate(R.layout.activity_fragment_one, container, false);


        button1 = (Button) view.findViewById(R.id.button_one);
        button1.setOnClickListener(this);

        return view;


    }

    @Override
    public void onClick(View v) {
        //MY CODE HERE
}

2 个答案:

答案 0 :(得分:1)

问题出在我的activity_main.XML中,我将<Fragment>定义为所有片段的占位符,并将一个片段设置为默认值。因此,当加载其他片段时,它会重叠,导致按钮上的点击事件无效,我将<Fragment>更改为<FrameLayout>作为占位符。我的问题解决了。

答案 1 :(得分:0)

首先你记得一件事,
片段到片段直接事务,或片段到片段直接替换是不可能的。它只能抛出活动。

在第一个片段中定义一个接口,并使容器Activity实现该接口,这样就可以将数据从Fragment发送到Activity。另一方面,创建Second Fragment并在其中定义一个接口。在Content Activity里面的First Fragment接口的实现方法中定义了一个Second Fragment,这里我们通过接口将数据分配给第二个Fragment。

相关问题