从内部viewpager片段调用活动方法

时间:2015-08-29 15:02:13

标签: android android-fragments android-viewpager

我正在使用Android应用程序而且我有一个包含4个片段的viewPager。 在每个片段中都有一些输入视图。

是否可以在活动中声明一个读取每个输入视图值的方法,并在每个输入视图状态更改时调用?

谢谢

的Alessandro

1 个答案:

答案 0 :(得分:7)

是的,有可能。请按照以下步骤操作。

  1. 创建一个界面并声明一个方法。
  2. 让活动实现该接口
  3. 现在从接口覆盖该方法并编写该函数的定义。
  4. 在片段中创建接口的对象。
  5. 在需要时使用对象调用该方法。
  6. 使用代码的示例: -

    接口代码: -

    //use any name
    public interface onInputChangeListener {
    
        /*To change something in activty*/
        public void changeSomething(//parameters that will hold the new information);
    
    
    }
    

    活动代码: -

    public class MyActivity extends AppCompatActivity implements onInputChangeListener {
    
        onCreate();
    
        @override
        public void changeSomething(/*Arguments with new information*/){
    
        //do whatever this function need to change in activity
        // i.e give your defination to the function
        }
    }
    

    片段代码: -

    public class MyFragment extends Fragment {
    
        onInputChangeListener inputChangeCallback;
    
    /*This method onAttach is optional*/
    @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 {
                inputChangeCallback = (onInputChangeListener) activity;
            } catch (ClassCastException e) {
                throw new ClassCastException(activity.toString()
                        + " must implement onFragmentChangeListener");
            }
        }
    
    
        @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    
            View v = inflater.inflate(R.layout.fragment_my,container,false);
            inputChangeCallback.changeSomething(//pass the new information);
            return v;
        }
    
    }
    

    这样做..干杯!

    如果您想要快速修复: -

    片段中: -

    public class MyFragment extends Fragment {
    
    MyActivity myActivity;
    
     onCreateView(){
      ...
    
      myActivity = (MyActivity)getActivity;
    
      myActivity.callAnyFunctionYouWant();
    
      ...
     }
    }
    
相关问题