【问题标题】:how to programmatically show and hide action bar on one activity如何以编程方式显示和隐藏一项活动的操作栏
【发布时间】:2014-04-06 08:02:55
【问题描述】:

我得到了一项活动,其中我需要在登录界面上隐藏操作栏,然后登录后它将显示操作栏。我只有一项活动。如果我将 getActionBar 放在主要活动上,它会给我错误。

代码如下:

@SuppressLint("NewApi")
public class MainActivity extends Activity {


ViewPager viewPager;
PagerAdapter adapter;
ProgressDialog pDialog;
ImageView imgLogo;
Menu menu1;

ImageView header;
ImageView footer;


int[] bookCover = new int[] { 

                    R.drawable.image1, 
                    R.drawable.image2,
                    R.drawable.image3,

                    };


@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    setupFacebookConnect(savedInstanceState);

    imgLogo = (ImageView)findViewById(R.id.logo);
    share = (ImageView) findViewById(R.id.share);

    // Locate the ViewPager in viewpager_main.xml
    viewPager = (ViewPager) findViewById(R.id.pager);
    // Pass results to ViewPagerAdapter Class
    adapter = new ViewPagerAdapter(this, bookCover);
    // Binds the Adapter to the ViewPager
    viewPager.setAdapter(adapter);

    final OnPageChangeListener pageChangeListener = new ViewPager.SimpleOnPageChangeListener() {

        @SuppressLint("NewApi")
        @Override
        public void onPageSelected(int position) {

            final int pos = position;
            share.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {

                    switch(pos) {
                    case 0:

                        break;
                    case 1: 

                        break;
                    case 2:

                        break;                                              
                    case 3:

                        break;                                              

                    }

                }
            });
         // When changing pages, reset the action bar actions since they are dependent
         // on which page is currently active. An alternative approach is to have each
         // fragment expose actions itself (rather than the activity exposing actions),
         // but for simplicity, the activity provides the actions in this sample.           
        invalidateOptionsMenu();

        }

    };      
    viewPager.setOnPageChangeListener(pageChangeListener);
    pageChangeListener.onPageSelected(0);


    facebook_connect = (Button) findViewById(R.id.facebook_login);
    facebook_connect.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if (isFacebookConnected()) {
                disConnectFacebook();
            } else {
                connectFacebook();
            }

        }
    });


    // Shared Preferences
    mSharedPreferences = getApplicationContext().getSharedPreferences("MyPref", 0);

}

 @SuppressLint({ "InlinedApi", "NewApi" })
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        this.menu1 = menu;

        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.main, menu);

        menu.findItem(R.id.action_previous).setEnabled(viewPager.getCurrentItem() > 0);

        // Add either a "next" or "finish" button to the action bar, depending on which page
        // is currently selected.
        MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,(viewPager.getCurrentItem() == adapter.getCount() - 1)
                        ? R.string.action_finish
                        : R.string.action_next);

        item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return true;

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int itemId = item.getItemId();
        if (itemId == R.id.action_previous) {
            // Go to the previous step in the wizard. If there is no previous step,
            // setCurrentItem will do nothing.
            viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
            return true;
        } else if (itemId == R.id.action_next) {
            // Advance to the next step0.0 in the wizard. If there is no next step, setCurrentItem
            // will do nothing.
            viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


private Session.StatusCallback statusCallback = new FBSessionStatus();

public void setupFacebookConnect(Bundle savedInstanceState) {
    Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);

    Session session = Session.getActiveSession();
    if (session == null) {
        if (savedInstanceState != null) {
            session = Session.restoreSession(this, null, statusCallback,
                    savedInstanceState);
        }
        if (session == null) {
            session = new Session(this);
        }
        Session.setActiveSession(session);
        if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
            session.openForRead(new Session.OpenRequest(this)
                    .setCallback(statusCallback));
        }
    }
}

public boolean isFacebookConnected() {
    Session session = Session.getActiveSession();
    return (session.isOpened()) ? true  : false;

}

public void connectFacebook() {
    Session session = Session.getActiveSession();
    if (!session.isOpened() && !session.isClosed()) {
        getActionBar().show();
        session.openForRead(new Session.OpenRequest(this)
                .setCallback(statusCallback));       
    } else {
    Session.openActiveSession(this, true, statusCallback);

    }
}

@Override
public void onStart() {
    super.onStart();
    Session.getActiveSession().addCallback(statusCallback);
}

@Override
public void onStop() {
    super.onStop();
    Session.getActiveSession().removeCallback(statusCallback);
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Session session = Session.getActiveSession();
    Session.saveSession(session, outState);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode,
            resultCode, data);
}

public class FBSessionStatus implements Session.StatusCallback {
     @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
}

public void disConnectFacebook() {
    Session session = Session.getActiveSession();
    if (!session.isClosed()) {
        session.closeAndClearTokenInformation();
        viewPager.setVisibility(View.INVISIBLE);
        MenuItem item1 = menu1.findItem(R.id.action_next);
        item1.setVisible(false);
        MenuItem item2 = menu1.findItem(R.id.action_previous);
        item2.setVisible(false);



        imgLogo.setVisibility(View.VISIBLE);
        //btnLoginTwitter.setVisibility(View.VISIBLE);

        share.setVisibility(View.INVISIBLE);

    }

}

private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        // Check if the user is authenticated and
        // a deep link needs to be handled.
        if (state.isOpened()) {

            MenuItem item1 = menu1.findItem(R.id.action_next);
            item1.setVisible(true);
            MenuItem item2 = menu1.findItem(R.id.action_previous);
            item2.setVisible(true);
            //getActionBar().show();

            share.setVisibility(View.VISIBLE);

            //btnLoginTwitter.setVisibility(View.INVISIBLE);
            //btnShare.setVisibility(View.VISIBLE);     

            viewPager.setVisibility(View.VISIBLE);

            imgLogo.setVisibility(View.INVISIBLE);



        } 
    }

public void shareImage(String name, String caption, String desc, String link, String picture ) {

    Bundle params = new Bundle();
    params.putString("name", name);
    params.putString("caption", caption);
    params.putString("description", desc);
    params.putString("link", link);
    //params.putString("picture", "https://www.facebook.com/photo.php?fbid=10203610233686079&set=a.10203610230766006.1073741829.1523023247&type=1&theater");
    params.putString("picture", picture);

    WebDialog feedDialog = (
        new WebDialog.FeedDialogBuilder(MainActivity.this,
            Session.getActiveSession(),
            params))
        .setOnCompleteListener(new OnCompleteListener() {

            @Override
            public void onComplete(Bundle values,
                FacebookException error) {
                if (error == null) {
                    // When the story is posted, echo the success
                    // and the post Id.
                    final String postId = values.getString("post_id");
                    if (postId != null) {
                        Toast.makeText(MainActivity.this,
                            "Successfuly posted!",
                            Toast.LENGTH_SHORT).show();
                    } else {
                        // User clicked the Cancel button
                        Toast.makeText(MainActivity.this, 
                            "Publish cancelled", 
                            Toast.LENGTH_SHORT).show();
                    }
                } else if (error instanceof FacebookOperationCanceledException) {
                    // User clicked the "x" button
                    Toast.makeText(MainActivity.this, 
                        "Publish cancelled", 
                        Toast.LENGTH_SHORT).show();
                } else {
                    // Generic, ex: network error
                    Toast.makeText(MainActivity.this,
                        "Error posting story", 
                        Toast.LENGTH_SHORT).show();
                }
            }



        })
        .build();
        feedDialog.show();

    }

    @SuppressWarnings("unused")
    private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
        for (String string : subset) {
            if (!superset.contains(string)) {
                return false;
            }
        }
        return true;
     }





}

【问题讨论】:

标签: android


【解决方案1】:

对于扩展类Activity

getActionBar().hide();
getActionBar().show();

对于扩展类 AppCompatActivity

getSupportActionBar().hide();
getSupportActionBar().show();

【讨论】:

  • 我认为,在try catch中使用,可以解决各种情况。
【解决方案2】:

很简单。

getActionbar().hide();
getActionbar().show();

【讨论】:

  • 我使用它时的问题,它给了我 javanullpointer。并且很难用 viewpager 实现它
  • 顺便说一下,为了命名约定,它是 getActionBar().hide();您必须大写“Bar”。 :^)
【解决方案3】:

您可以使用 hide()/show() 功能在 Android 4.1(API 级别 16)及更高版本上 hide/Show 状态栏

     // Hide the status bar.
    ActionBar actionBar = getActionBar();
    actionBar.hide();

   // Show the status bar.
    actionBar.show();

更多详情可以访问https://developer.android.com/training/system-ui/status.html

http://developer.android.com/guide/topics/ui/actionbar.html

【讨论】:

    【解决方案4】:

    从清单文件中更改您的 Theme 以用于所需的 Activity...

     Theme.AppCompat.NoActionBar 
        or 
     Theme.AppCompat.Light.NoActionBar
    

    您可以通过这行代码以编程方式隐藏您的工具栏

    如果您通过 Activity 类扩展您的活动,则使用下面的代码行来显示或隐藏工具栏

    getActionBar().hide();
    getActionBar().show();
    

    如果您从 AppCompact Activity 扩展您的活动,则使用

    对于扩展 Activity 的类:

    getActionBar().hide(); getActionBar().show(); 对于扩展 AppCompatActivity 的类:

    getSupportActionBar().hide();
    getSupportActionBar().show();
    

    【讨论】:

      【解决方案5】:

      ActionBar 通常与Fragments 一起存在,因此您可以从Activity 隐藏它

      getActionbar().hide();
      getActionbar().show();
      

      您可以通过Fragment 做到这一点

      getActivity().getActionbar().hide();
      getActivity().getActionbar().show();
      

      【讨论】:

        【解决方案6】:

        你可以像下面这样使用 sharedpreference 来保存它

        public class MainActivity extends Activity 
        {
        Button btn;
        
        @Override
        protected void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        
            loadActionbar();
            btn=(Button)findViewById(R.id.mainButton1);    
         btn.setOnClickListener(new OnClickListener(){
        
                    @Override
                    public void onClick(View p1)
                    {
                        if(getActionBar().isShowing()==true){
                            getActionBar().hide();
                            saveActionBar();       
                        }
                        else{
                            getActionBar().show();
                            saveActionBar();
                        }
                    }
                })
        
        
         public void saveActionBar(){
            SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());     
            SharedPreferences.Editor editor=pref.edit();     
            editor.putBoolean("save",getActionBar().isShowing());   
            editor.apply();
        }
        
        public void loadActionbar(){
            SharedPreferences pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());     
            boolean i=pref.getBoolean("save",getActionBar().isShowing());
            if(i!=true){
                getActionBar().hide();
            }
            else
                getActionBar().show();
        
        }
        

        【讨论】:

          【解决方案7】:

          对于活动

          getActionBar().show();
          getActionBar().hide();
          

          对于AppCompatActivity

          getSupportActionBar().show();
          getSupportActionBar().hide();
          

          对于片段

          getActivity().getActionbar().show();
          getActivity().getActionbar().hide();
          

          【讨论】:

            【解决方案8】:

            这对我有用:

            supportActionBar?.hide()
            

            【讨论】:

            • 请对您的回答进行解释。仅代码的答案很少有帮助,通常会被删除。对于像这样的老问题,OP 已经解决或从他们的问题继续前进,尤其如此。
            猜你喜欢
            • 1970-01-01
            • 2016-09-29
            • 1970-01-01
            • 1970-01-01
            • 2020-01-27
            • 2018-12-29
            • 1970-01-01
            • 1970-01-01
            • 2011-05-06
            相关资源
            最近更新 更多