【问题标题】:android fragment button in include tag does not work包含标签中的android片段按钮不起作用
【发布时间】:2017-05-11 11:20:43
【问题描述】:

我遇到了一个问题,我的按钮在我使用时不起作用

这是我的 fragment_category_sub xml 文件:

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

      ...

    <include
        layout="@layout/content_unavailable"
        />

    ....

这是我的包含 xml 文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/content_unavailable"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
android:padding="16dp">

<Button
    android:id="@+id/try_again"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/error_default_tryAgain"/>

</LinearLayout>

这是我尝试实现 setOnClickListener 的片段:

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

    rootView = inflater.inflate(R.layout.fragment_category_sub, container, false);
    ButterKnife.bind(this, rootView);

    contentUnavailable = rootView.findViewById(R.id.content_unavailable);

    Button buttonAgain = (Button) 
    contentUnavailable.findViewById(R.id.try_again);

    buttonAgain.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (utils.isConnectingToInternet()) {

               categorySubPresenter.getAllListItems(uid, category_id);
            }
        }
    });

    return rootView;
}

有谁知道为什么这个按钮在片段中按下时不起作用以及如何解决?因为 Activity 中的相同代码可以正常工作。提前谢谢你。

【问题讨论】:

  • 何时何地让按钮可见?
  • 您的按钮可见性已消失
  • 可见性消失了
  • ahhh,我忘了从代码中删除它,当在我的 rxjava 调用中出现 onError 时,它变为可见
  • 你确定onClick没有被调用吗?如果调用了侦听器,问题可能出在categorySubPresenter.getAllListItems(uid, category_id);

标签: android xml button include fragment


【解决方案1】:

我不认为这是因为include 标签。曾经有人警告我不能在片段中设置侦听器。因此,如果您想在某个按钮上设置侦听器,则必须在 Activity 中进行。

有一个fragment回调onActivityCreated()在activity创建时被调用,所以从这一刻开始你可以调用Fragment的getActivity() method

这是一个例子

    @Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    final Activity activity = getActivity();

    activity.findViewById(R.id.toast).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(activity, "My toast", Toast.LENGTH_SHORT).show();
        }
    });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-13
    相关资源
    最近更新 更多