【问题标题】:onClick at button in Fragment desn't workonClick 片段中的按钮不起作用
【发布时间】:2018-10-08 13:25:13
【问题描述】:

在我的应用程序中,我有两个片段的选项卡式活动。在我想使用按钮打开对话框警报的片段处。但是现在五个小时我一直在努力实际点击按钮。我尝试了使用 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;
}

【问题讨论】:

  • 添加标签活动代码
  • 确保 xml 视图 R.layout.fragment_players 包含带有视图 id 的 R.id.add_button 的 Button 小部件,并且如上所述使用 onViewCreated 回调进行小部件视图层次结构初始化。

标签: android android-fragments android-button


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2020-05-21
    • 2014-06-22
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多