从fragmet设置操作栏标题

时间:2016-08-10 19:01:15

标签: android android-fragments android-actionbar android-viewpager

我正在使用我在项目中使用视图寻呼机和片段, 我试图从片段类设置Actionbar的标题。 我的以下代码显示当前可见片段的下一个片段的标题。 你能有任何想法如何在Action Bar

中显示当前可见的片段标题


    public class MyFragment extends Fragment {

        TextView textView;
        int mCurrentPage;


        String name = null, data = null;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            /** Getting the arguments to the Bundle object */
            Bundle data = getArguments();

            /** Getting integer data of the key current_page from the bundle */
            mCurrentPage = data.getInt("current_page", 0);

        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

            setData();

            View view = inflater.inflate(R.layout.fragment_Item, container, false);

            textView = (TextView) view.findViewById(R.id.fragmentItemTextView);

            textView.setText(data);

            ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle(name);
            //this sets title of actionbar
            //but it set name of next item's name in actionbar

            return view;
        }


        void setData() {

            //here I call database to get name of item and data of item

            ItemProcess sp = new ItemProcess(getActivity().getApplicationContext());

            ArrayList temp;
            temp = sp.getSingleItem(mCurrentPage);

             name = temp.get(0).getmItemName();
             data = temp.get(0).getmItemData();


        }


    }

2 个答案:

答案 0 :(得分:0)

这是因为viewpager在当前片段上调用后加载下一个片段的onCreateView方法,并且你不能将viewPagerOffset limit设置为0。 您可以通过以下代码更改片段中的操作栏标题:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) { 
    super.setUserVisibleHint(isVisibleToUser);
    m_iAmVisible = isVisibleToUser;
    if (m_iAmVisible) { 
        Log.d(localTAG, "this fragment is now visible");
         //change your actionbartitle
    } else {  
        Log.d(localTAG, "this fragment is now invisible");
    }
}

答案 1 :(得分:0)

  

但它在操作栏中设置了下一个项目名称。

默认情况下,ViewPager Adapter会为您创建当前和下一个片段视图,请参阅:

  

预订“Android.Programming.The.Big.Nerd.Ranch.Guide”P207   enter image description here

生命周期方法:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button style="color: rgb(255, 255, 0)">Text</button>

因此,最好在Activity中更新ActionBar标题:

// when first in page0
D/Adapter (25946): getItem(0)
D/Adapter (25946): getItem(1)
D/Fragment1(25946): newInstance(Hello World, I'm li2.)
D/Fragment0(25946): onAttach()
D/Fragment0(25946): onCreate()
D/Fragment0(25946): onCreateView()
D/Fragment1(25946): onAttach()
D/Fragment1(25946): onCreate()
D/Fragment1(25946): onCreateView() // that's why it set name of next item.