从内部 viewpager 片段调用 activity 方法

call activity method from inner viewpager fragments

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

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

谢谢

亚历山德罗

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

  1. 创建一个接口并声明一个方法。
  2. 让 activity 实现该接口
  3. 现在重写接口中的方法并编写函数的定义。
  4. 在片段中制作界面的对象。
  5. 在需要时使用对象调用该方法。

使用代码的示例:-

界面代码:-

//use any name
public interface onInputChangeListener {

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


}

Activity代码:-

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();

  ...
 }
}