且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android-处理活动中的片段onClick

更新时间:2022-12-26 11:29:57

如果您需要一堆 Fragments .也许在这种情况下,***使用 ListView (或其他任何类型,例如 RecyclerView ).您可以轻松地监听click事件,并在列表项数不限的情况下执行任何操作.

In case you need to have a bunch of Fragments. Maybe in this case it is better to use ListView (or any other type of it, for example RecyclerView). You can easily listen for click event and do whatever you want having number of list item.

如果您确实需要使用片段.您可以采用不同的方法.
首先,在您的 reviewClick(View view)中,您获得的不是片段标签,而是视图标签.为什么将 View 作为参数?
如果需要片段在 Activity 中使用回调方法,则可以遵循最常用的方法.
这里的问题是您的 Framgent 可能包含不同的视图,并且如果不使用叠加布局,则无法直接获得整个片段的onClick,但是在这种情况下,您还必须处理布局onclick事件.>正如我已经提到的,可能的解决方案是使用回调方法.

If you really need to use Fragments. You can follow different ways.
Firstly in your reviewClick(View view) you are getting not fragment tag, but view tag. Why you are having View as an argument ?
You can follow most common used approach in case you need fragments use callback method in your Activity.
The problem here that your Framgent may contain different views and you cannot get onClick directly on whole fragment, if you are not using overlay layout, but in this case you also have to handle layout onclick event.
Possible solution as I have already mentioned is to use callback method.

以下是实现此步骤的几个步骤:

Here are several steps to implement this :

在片段中创建内部接口,例如

Create inner interface in your fragment,for example

 public interface       OnReviewSelectedListener {
        public void onReviewSelected(int position);  }

您的活动现在必须实现此接口

Your activtiy now have to implement this interface

public static class MainActivity extends Activity
        implements ReviewFragment.OnReviewSelectedListener

您可以在

 public void onReviewSelected(int position) {
          if(position==YOUR_TAG) {

          }
    }

onAttach 方法的 ReviewFragment 中,您必须将活动投射到界面上.

And in ReviewFragment in onAttach method you have to cast activity to your interface.

   @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnReviewSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnReviewSelectedListener");
        }
    }

如果您真的想将片段与标签一起使用,则可以在片段中执行以下操作.

And if you really wanna to use fragment with tags you can do following in your fragment.

public void onCommentClick() {
      // do some stuff
     mCallback.onReviewSelected(getFramgentTag());
}