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

Ale*_*t83 2 android android-fragments android-viewpager

我正在开发一个Android应用程序,我有一个包含4个片段的viewPager.在每个片段中都有一些输入视图.

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

谢谢

亚历山德罗

Aks*_*rma 7

对的,这是可能的.跟着这些步骤.

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

使用代码的示例: -

接口代码: -

//use any name
public interface onInputChangeListener {

    /*To change something in activty*/
    public void changeSomething(//parameters that will hold the new information);


}
Run Code Online (Sandbox Code Playgroud)

活动代码: -

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
    }
}
Run Code Online (Sandbox Code Playgroud)

片段代码: -

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;
    }

}
Run Code Online (Sandbox Code Playgroud)

这样做..干杯!

如果你想快速修复: -

在你的片段中: -

public class MyFragment extends Fragment {

MyActivity myActivity;

 onCreateView(){
  ...

  myActivity = (MyActivity)getActivity;

  myActivity.callAnyFunctionYouWant();

  ...
 }
}
Run Code Online (Sandbox Code Playgroud)