onClick inside fragment called on Activity

后端 未结 6 931
北恋
北恋 2020-12-02 22:14

i am encapsulating stuff into a fragment at the moment and run into a problem that is hard to google. Inside my fragment are some buttons with onClick attributes but they a

6条回答
  •  渐次进展
    2020-12-02 23:08

    ISSUE:

    1.In XML onClick attribute will call activity's public method.

    2.Fragment's public method not called.

    3.Fragment reusability.

    SOLUTION:

    In Fragment's layout add this to the View.

    android:onClick="onFragmentViewClick"
    

    In each activity the fragment may belong..

    public void onFragmentViewClick(View v) {
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.container);
        if (fragment != null && fragment.isVisible()) {
            if (fragment instanceof SomeFragment) {
                ((SomeFragment) fragment).onViewClicked(v);
            }
        }
    }
    

    In the Fragment include this method..

    public void onViewClicked(View v) {
        switch (v.getId()) {
            case R.id.view_id:
                Log.e("onViewClicked", "yehhh!!");
                break;
        }
    }
    

提交回复
热议问题