带按钮的片段:onClick()与XML onClick

时间:2015-10-13 15:05:35

标签: android android-layout android-fragments

我有一个相当简单的屏幕,只有4个按钮。我将它像片段一样实现:

public class MainFragment extends Fragment implements View.OnClickListener {
   // ...

   @Override
   public void onClick(View view) {}
}

每个按钮已经为片段附加的活动中的某个功能指定了onClick。我遇到的问题是,单击按钮时不会调用onClick个函数。我已经将MainFragment.onClick()留空了 - 但这是正确的做法吗?是否需要为要调用的函数实现?如果是这样,Button布局中的onClick属性似乎是多余的。

任何帮助将不胜感激。

由于

3 个答案:

答案 0 :(得分:2)

正确的方法是使用片段监听器与活动进行通信:

mYourButton.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View arg0) {
        if (mListener != null) {
            mListener.onFragmentInteraction();
        }
    }
});

然后在你的片段中:

FacebookFieldRetriever

答案 1 :(得分:1)

如果在XML中设置onClick,则点击事件将转到您的容器活动中。但是,您可以通过将onClickListener设置为Fragment的实现来将点击事件直接发送到您的片段。因此,在您的片段onCreateView()方法中,您会夸大您的布局,然后将Button的onClickListener设置为您的片段实现,就像这样...

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.your_fragment, container, false);
    Button button = (Button) view.findViewById(R.id.your_button);
    button.setOnClickListener(this);
    return view;
}

通过将setOnClickListener()设置为this,您可以将该按钮的所有点击事件发送到您的片段而不是您的活动。然后,您只需处理onClick事件,就像您已经在做的那样......

@Override
public void onClick(View view) {
    Log.d("YOUR BUTTON", "This is called from your Fragment instead of your Activity");
}

答案 2 :(得分:1)

FWIW我从不使用xml onClick属性。虽然它们可以节省几行打字,但是它们使得更难以跟踪代码中发生的事情。

如果您的班级implements View.OnClickListener并且您已正确覆盖onClick方法(您看起来像这样),那么您可以安全地删除onClick个您的layout文件,而是通过以下方式为您的小部件点击分配方法:

public class MainFragment extends Fragment implements View.OnClickListener {
    private Button viewOne, viewTwo, viewThree;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.your_layout, container, false);

        viewOne = (Button) rootView.findViewById(R.id.view_one);
        viewTwo = //etc...

        //"this" refers to the current object. As the object is of a class that implements OnClickListener, 
        //passing "this" satisfies the View.OnClickListener parameter required for the setOnClickListener() method.
        viewOne.setOnClickListener(this);
        viewTwo.setOnClickListener(this);
        viewThree.setOnClickListener(this);

        return rootView;
    }


   @Override
   public void onClick(View view) {
       //To identify the correct widget, use the getId() method on the view argument
       int id = view.getId();
       switch (id) {
           case R.id.view_one:
               //viewOne clicked
               break;
           case R.id.view_two:
               //And so on...
       }
   }
}
相关问题