如何从片段内部以编程方式设置ViewPager选项卡?

时间:2018-09-04 16:04:52

标签: java android android-fragments android-viewpager

我有一个database,它提供了一个Strings数组,可以从Fragment内部进行访问。我希望这些字符串返回到Fragment附带的活动,并在ViewPager中设置选项卡的标题。我该怎么办?

这就是我想做的:

  

数据库字符串[]→片段→附加活动的ViewPager→新建   标签

编辑:这是我的整个活动和PagerAdapter code

这是我的片段code

1 个答案:

答案 0 :(得分:0)

假设您有Strings的数组,并且想将其从activity发送到Fragment,像这样制作interface

public class MyFragment extends Fragment {
CustomStrings mCallback;

// Container Activity must implement this interface
public interface CustomStrings {
    public void onStringRecieved(String[] stringss);
} 


@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 {
        mCallback = (CustomStrings) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnHeadlineSelectedListener");
    }
}

然后在需要发送数据时简单使用它

mCallback.onStringRecieved(yourStrings); //your data here

然后在您的活动中实现它

public class MainActivity extends Activity
    implements MyFragment.CustomStrings{
...

public void onStringRecieved(String[] stringss) {

    // Do something here to use these strings
    Toast.makeText(getContext(), ""+strings, Toast.LENGTH_SHORT).show();
}

希望这可以解决您的问题,有关更多信息,请参见this