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

问题描述 投票:0回答:1

我有一个database,提供一系列Strings,从Fragment访问。我希望这些字符串返回到Fragment附带的活动,并在ViewPager中设置标签的标题。我怎样才能做到这一点?

这就是我想要的方式:

数据库字符串[]→片段→附加活动的ViewPager→新选项卡

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

这是我的碎片code

java android android-fragments android-viewpager
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.