我正在使用Android应用程序而且我有一个包含4个片段的viewPager。 在每个片段中都有一些输入视图。
是否可以在活动中声明一个读取每个输入视图值的方法,并在每个输入视图状态更改时调用?
谢谢
的Alessandro
答案 0 :(得分:7)
是的,有可能。请按照以下步骤操作。
使用代码的示例: -
接口代码: -
//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();
...
}
}