如何在单击后退按钮时更改操作栏上的名称

时间:2016-05-19 11:24:14

标签: java android android-fragments

我正在尝试创建一个应用。我没有在Action栏上获得名字。当我们回到主要活动的时刻从片段返回主要活动但是在操作栏上的名称没有更改显示在返回主要活动后片段的名称使用以下代码 -

 public class MainActivity extends FragmentActivity implements OnMapReadyCallback, ConnectionCallbacks, OnConnectionFailedListener,LocationListener{
 DrawerLayout mDrawerLayout;
 ListView mDrawerList;
 @SuppressWarnings("deprecation")
ActionBarDrawerToggle mDrawerToggle;
 String mTitle="";
 private final String  TAG = this.getClass().getSimpleName();

    LocationRequest mLocationRequest;
    GoogleApiClient mGoogleApiClient;

    LatLng latLng;
    GoogleMap mMap;
    SupportMapFragment mFragment;
    Marker CurrentMarker,NearbyPlace,FindMarker;
    EditText editplace = null;
    Button findbtn = null;
    boolean firstRun = true;
    private Boolean exit = false;


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

    //for connectivity service
    ConnectivityManager cManager = (ConnectivityManager) getSystemService(this.CONNECTIVITY_SERVICE);
    NetworkInfo nInfo = cManager.getActiveNetworkInfo();
    if (nInfo != null && nInfo.isConnected()) {
        Toast.makeText(this, "Network is available ", Toast.LENGTH_SHORT).show();

        AdView adView = (AdView)findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder()
        //.addTestDevice("abc")
        .build();
        adView.loadAd(adRequest);
    mFragment=(SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
    mFragment.getMapAsync(this);

    }


    else{
        Toast.makeText(this, "Network is not available ", Toast.LENGTH_SHORT).show();
        Fragment newFragment;
        FragmentTransaction transaction = getFragmentManager().beginTransaction();
        newFragment = new NetworkCheck();
        transaction.replace(R.id.content_frame, newFragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }

    editplace = (EditText) findViewById(R.id.editplace);
    findbtn = (Button) findViewById(R.id.findbtn);

    setListnerOnWidget();

    mTitle = (String) getTitle();
    // Getting reference to the DrawerLayout
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.drawer_list);

    // Getting reference to the ActionBarDrawerToggle
    mDrawerToggle = new ActionBarDrawerToggle( this,
        mDrawerLayout,
        R.drawable.ic_drawer,
        R.string.drawer_open,
        R.string.drawer_close){

            /** Called when drawer is closed */
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu();
            }

            /** Called when a drawer is opened */
            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle("Select a menu");
                invalidateOptionsMenu();
            }
    };

    // Setting DrawerToggle on DrawerLayout
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    mDrawerToggle.setDrawerIndicatorEnabled(true);

    // Creating an ArrayAdapter to add items to the listview mDrawerList
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
        getBaseContext(),
        R.layout.drawer_list_item ,
        getResources().getStringArray(R.array.menu)
    );

    mDrawerList.setAdapter(adapter);

    getActionBar().setHomeButtonEnabled(true);
    getActionBar().setDisplayHomeAsUpEnabled(true);


    // Setting item click listener for the listview mDrawerList
    mDrawerList.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent,
            View view,
            int position,
            long id) {
            displayView(position);
            // Updating the action bar title
            String[] menu = getResources().getStringArray(R.array.menu);
            mTitle = menu[position];

            mDrawerLayout.closeDrawer(mDrawerList);

        }

        private void displayView(int position) {
            // TODO Auto-generated method stub
            Fragment newFragment;
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            switch (position) {
            case 0:

                newFragment = new Help();
                transaction.replace(R.id.content_frame, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
                break;

            case 1:

                newFragment = new ContactUs();
                transaction.replace(R.id.content_frame, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
                break;

              case 2:
                  transaction.addToBackStack(null);
                try
                { Intent i = new Intent(Intent.ACTION_SEND);  
                  i.setType("text/plain");
                  i.putExtra(Intent.EXTRA_SUBJECT, "My application name");
                  String sAux = "\nLet me recommend you this application\n\n";
                  sAux = sAux + "https://play.google.com/store/apps/details?id=com.iqwiner\n\n";
                  i.putExtra(Intent.EXTRA_TEXT, sAux);  
                  startActivity(Intent.createChooser(i, "Choose an action"));

                }
                catch(Exception e)
                { //e.toString();
                }   
                Log.e(TAG, "share button is clicked");
                break;

              case 3:
                newFragment = new Suggestion_Address();
                transaction.replace(R.id.content_frame, newFragment);
                transaction.addToBackStack(null);
                transaction.commit();
                Log.e(TAG, "Suggestion Address button is clicked");
                break;

            }

        }

    });



}

private void setListnerOnWidget() {
    // TODO Auto-generated method stub
    OnClickListener listener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            String location = editplace.getText().toString();
            if(location!=null && !location.equals("")){
                  new GeocoderTask().execute(location); 

                }
    }
    };
   findbtn.setOnClickListener(listener);

}



@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}


@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}

//for back button 

@Override
public void onBackPressed() {

    if (getFragmentManager().getBackStackEntryCount() > 1) {
        getFragmentManager().popBackStack();

    } else {
        super.onBackPressed();
    }
         }

从片段返回主要活动时,请告诉我主要活动的操作栏上的显示名称。

由于

2 个答案:

答案 0 :(得分:1)

您可以在主活动中设置一个方法,设置操作栏,您可以在主要活动的Onresume中调用。

示例主要活动方法

public void setActionBar(CharSequence title) {
         toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setTitle(title);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
       }

答案 1 :(得分:0)

在您的片段中使用此行代码,从那里返回MainActivity

@Override
public void onDestroyView() {
    super.onDestroyView();
    (AppCompatActivity) getActivity()).getSupportActionBar().setTitle("You Main Activity Title");

}

或尝试此

@Override
public void onDestroyView() {
    super.onDestroyView();
    getActivity().getSupportActionBar().setTitle("You Main Activity Title");

}