Ale*_*t83 2 android android-fragments android-viewpager
我正在开发一个Android应用程序,我有一个包含4个片段的viewPager.在每个片段中都有一些输入视图.
是否可以在活动中声明一个读取每个输入视图值的方法,在每个输入视图状态变化时调用?
谢谢
亚历山德罗
对的,这是可能的.跟着这些步骤.
使用代码的示例: -
接口代码: -
//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)
| 归档时间: |
|
| 查看次数: |
2225 次 |
| 最近记录: |