Android添加按钮到片段内的操作栏

时间:2013-11-03 21:22:38

标签: android android-fragments android-actionbar android-fragmentactivity

在我的片段中,如果网络不可用,我需要在操作栏中添加刷新按钮。

例如:

    private void beginRetriveData() {

            final StringBuilder Request = "some_url_here"

            if(!isNetworkAvailable()) {     

                Toast.makeText(getSherlockActivity(), "No active internet connection", Toast.LENGTH_LONG).show(); 
// I NEED TO ADD REFRESH BUTTON TO ACTIONBAR    

            } else {
                     //AsyncTasc here

            }   
        }

这是最好的方法吗?

我尝试了以下内容:

public MenuItem mRefreshMenuItem;

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        getSupportMenuInflater().inflate(R.menu.main, menu);

        mRefreshMenuItem = menu.findItem(R.id.navigation_refresh);
        mRefreshMenuItem.setVisible(false);

        return true;
    }

    @Override
    public void onNetworkUnavailable()
    {
        mRefreshMenuItem.setVisible(true); //ERROR HERE 
    }

然后在片段中我打电话给:

 if(getActivity() instanceof FragmentsHolderActivity){
      FragmentsHolderActivity myactivity = (FragmentsHolderActivity) activity;
      myactivity.onNetworkUnavailable();
 }

但是当我调用onNetworkUnavailable()时,出现了NullPointerException。

1 个答案:

答案 0 :(得分:2)

在Activity中覆盖onCreateOptionsMenu()并向菜单添加刷新MenuItem(可以通过膨胀菜单资源或以编程方式实例化来实现)。然后使刷新项不可见,并将其保存为实例变量,以便稍后访问。

添加到您的活动:

private MenuItem mRefreshMenuItem;

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // add your refresh button to res/menu/main.xml
    getMenuInflater().inflate(R.menu.main, menu);

    mRefreshMenuItem = menu.findItem(R.id.refresh);
    mRefreshMenuItem.setVisible(false);

    return true;
}

接下来,添加一个界面,以便Fragment可以在发生网络错误时让您的活动知道Communicating with Other Fragments中所述。

添加到您的片段:

private OnNetworkUnavailableListener mListener;

public interface OnNetworkUnavailableListener
{
    public void onNetworkUnavailable();
}

@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity);
    try
    {
        mListener = (OnNetworkUnavailableListener)activity;
    }
    catch (ClassCastException ex)
    {
        throw new ClassCastException(activity.getClass().getSimpleName() + " must implement OnNetworkUnavailableListener");
    }
}

此外,当网络不可用时,请在您的界面上调用该方法:

private void beginRetriveData()
{
    ...
    if(!isNetworkAvailable())
    {     
        mListener.onNetworkUnavailable();
    }
    ...
}

最后,在Activity中实现您的界面,并在发生网络错误时将MenuItem的可见性设置为可见。请记住将“implements OnNetworkUnavailableListener”添加到您的Activity中。

public class MainActivity extends Activity implements OnNetworkUnavailableListener
{
    ...

    @Override
    public void onNetworkUnavailable()
    {
        mRefreshMenuItem.setVisible(true);
    }
}