2015-07-12 41 views
1

我使用android-badgeviewer来显示选项卡中的通知数量。我的代码如下所示。如何从另一个活动或类更新tabhost android中的徽章

@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; 
} 

现在我需要从另一个活动或类更新我的徽章。我该怎么做?。

回答

0

我认为你可以使用这里记录的活动/片段交流: 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例子中一个片段定义的接口。如果你有多个标签都会获得徽章,我会在它自己的类/文件中定义接口。