片段中的onClick at按钮不起作用

时间:2018-04-27 16:35:47

标签: android android-fragments android-button

在我的应用程序中,我使用两个片段标记了活动。在片段我想使用按钮打开对话框警报。但现在我花了五个小时才真正点击按钮。我尝试了使用xml onClick,实现OnClickListener但没有任何效果。按钮无所事事。我试图调试它,似乎根本没有调用onCreateView方法。有什么提示吗?

public class PlayersFragment extends Fragment {

public PlayersFragment() {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_players, container, false);
    Button addButton = (Button) view.findViewById(R.id.add_button);
    addButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(getContext(), "YES is clicked!",
                    Toast.LENGTH_LONG).show();
        }
    });

    return view;
}

1 个答案:

答案 0 :(得分:1)

覆盖片段类中的onViewCreated方法。然后使用方法将onClickListener放在Button上。