我使用android-badgeviewer来显示选项卡中的通知数量。代码如下所示:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_homepage_x,container, false);
mTabHost = (FragmentTabHost)rootView.findViewById(android.R.id.tabhost);
mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("HOME").setIndicator(getTabIndicatorhome(mTabHost.getContext(), "HOME")),
homepage.class, null);
mTabHost.addTab(mTabHost.newTabSpec("NOTIFICATIONS").setIndicator(getTabIndicator(mTabHost.getContext(), "NOTIFICATIONS")),
notificationfragment.class, null);
return rootView;
}
private View getTabIndicator(Context context, String title) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_layout, null);
TextView tv = (TextView) view.findViewById(R.id.tab_text);
tv.setText(title);
TextView tv_counter = (TextView) view.findViewById(R.id.tab_counter);
BadgeView badge = new BadgeView(getActivity(), tv_counter);
badge.setText("1");
badge.show();
return view;
}
private View getTabIndicatorhome(Context context, String title) {
View view = LayoutInflater.from(context).inflate(R.layout.tab_layout_home, null);
TextView tv = (TextView) view.findViewById(R.id.tab_text_home);
tv.setText(title);
return view;
}
现在我需要从另一个活动或类更新我的徽章。
我认为你可以使用这里记录的活动/片段通信:http://developer.android.com/training/basics/fragments/communicating.html。
的例子:
public class SomeFragment extends Fragment {
OnDataChanged mCallback;
// Container Activity must implement this interface
public interface OnDataChangedListener {
public void onDataChanged(int numberOfThingsChanged);
}
@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 = (OnDataChangedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnDataChangedListener");
}
}
// When your data actually changes call back to the tab fragment
private void somethingChanged() {
// No need to check if we have a callback, onAttach already did that
// notif change
mCallback(27); // 27 things changed.
}
}
然后在你的主标签片段实现该接口(你的类在你的问题):
public class MyTabFragment implements OnDataChangedListener {
...
@Override
public void OnDataChangedListener(int numberOfThings) {
// update your badge here
}
...
}
Android的例子在一个片段中定义了接口。如果你有多个选项卡,都将获得徽章,我会在自己的类/文件中定义接口