我正在开发一个 Android 应用程序,我有一个包含 4 个 fragment 的 viewPager。 在每个 fragment 中都有一些输入 View 。
是否可以在 Activity 中声明一个方法来读取每个输入 View 值,并在每个输入 View 状态更改时调用?
谢谢
亚历山德罗
最佳答案
是的,这是可能的。请按照以下步骤操作。
- 创建一个接口(interface)并声明一个方法。
- 让 Activity 实现该接口(interface)
- 现在覆盖接口(interface)中的方法并编写函数的定义。
- 在 fragment 中制作界面的对象。
- 在需要时使用对象调用该方法。
使用代码示例:-
接口(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/