android - 从内部 viewpager fragment 调用 Activity 方法

标签 android android-fragments android-viewpager

我正在开发一个 Android 应用程序,我有一个包含 4 个 fragment 的 viewPager。 在每个 fragment 中都有一些输入 View 。

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

谢谢

亚历山德罗

最佳答案

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

  1. 创建一个接口(interface)并声明一个方法。
  2. 让 Activity 实现该接口(interface)
  3. 现在覆盖接口(interface)中的方法并编写函数的定义。
  4. 在 fragment 中制作界面的对象。
  5. 在需要时使用对象调用该方法。

使用代码示例:-

接口(interface)代码:-

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

fragment 代码:-

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

}

这会……干杯!

如果您想要快速修复:-

在您的 fragment 中:-

public class MyFragment extends Fragment {

MyActivity myActivity;

 onCreateView(){
  ...

  myActivity = (MyActivity)getActivity;

  myActivity.callAnyFunctionYouWant();

  ...
 }
}

关于android - 从内部 viewpager fragment 调用 Activity 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32287430/

相关文章:

android - 为整个 Activity 设置字体设置

android - 如何在我的一个 viewpager 页面中访问我的按钮?

android - 错误膨胀类 com.google.android.youtube.player.YouTubePlayerView

android 在所有 Activity 前保持一个 View

Java android xml文本框没有文本=没有按钮点击

android - 在 addThis android 应用程序中添加签名

android - 从方向更改恢复时,DialogFragment onCreateDialog() 在 onServiceConnected() 之前被调用

java - 使用fragment在Activity中创建新的Activity

android - 您尚未登录。请登录并重试

android - 如何处理 3rd 方 android 库中的库不匹配?