如何更改导航抽屉中的标题

时间:2015-11-18 11:07:59

标签: android

我希望菜单中的标题会因点击的片段名称而改变。我得到的代码是,每个片段中的实际标题是“Home”,它不会改变。但我发现,当我点击菜单中的一个项目时,标题会改变一秒并返回“主页”标题。我实施了拉杆机,但我仍然不知道是什么原因造成的。

我的代码:

 package com.example.matant.gpsportclient;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.example.matant.gpsportclient.Controllers.Fragments.CreateEventFragmentController;
import com.example.matant.gpsportclient.Controllers.DBcontroller;
import com.example.matant.gpsportclient.Controllers.Fragments.GoogleMapFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ManageEventFragmentController;
import com.example.matant.gpsportclient.Controllers.Fragments.ProfileFragmentController;
import com.example.matant.gpsportclient.InterfacesAndConstants.AsyncResponse;
import com.example.matant.gpsportclient.InterfacesAndConstants.Constants;
import com.example.matant.gpsportclient.Utilities.DrawerItem;
import com.example.matant.gpsportclient.Utilities.DrawerItemCustomAdapter;
import com.example.matant.gpsportclient.Utilities.SessionManager;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;


public class MainScreen extends AppCompatActivity implements AsyncResponse {

    private String[] mNavigationDrawerItemTitles;
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private DBcontroller dbController;
    private ProgressDialog progress = null;
    private SessionManager sm;


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

        if (getIntent().getBooleanExtra("EXIT", false)) {
            finish();
            return;
        }

        mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        sm = SessionManager.getInstance(this);

        mTitle = mDrawerTitle = "Home";
        DrawerItem [] drawerItems = new DrawerItem[Constants.MENU_SIZE];
        drawerItems[0] = new DrawerItem(R.drawable.home,"Home");
        drawerItems[1] = new DrawerItem(R.drawable.profile,"Profile");
        drawerItems[2] = new DrawerItem(R.drawable.search,"Search Events");
        drawerItems[3] = new DrawerItem(R.drawable.create,"Create Event");
        drawerItems[4] = new DrawerItem(R.drawable.manage,"Manage Event");
        drawerItems[5] = new DrawerItem(R.drawable.attending,"Attending List");
        drawerItems[6] = new DrawerItem(R.drawable.recent_search_24,"Recent Searches");
        drawerItems[7] = new DrawerItem(R.drawable.logout,"Log Out");

        DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItems);
        mDrawerList.setAdapter(adapter);
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_menu, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu();
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu();
            }
        };

        mDrawerLayout.setDrawerListener(mDrawerToggle);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu);
        getSupportActionBar().setTitle(mNavigationDrawerItemTitles[0]);

        if (savedInstanceState == null) {
            // on first time display view for first nav item
            selectItem(0);
        }

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    public void handleResponse(String resStr) {
        try
        {
            if((this.progress!= null )&& this.progress.isShowing())
            {
                this.progress.dismiss();
            }
        }catch (final IllegalArgumentException e){
            Log.d("Dialog error",e.getMessage());
        }catch (final Exception e){
            Log.d("Dialog error",e.getMessage());
        }
            finally {
            this.progress = null;
        }

        Log.d("handleResponse", resStr);
        if(resStr!=null)
        {
            try {
                JSONObject jsonObj = new JSONObject(resStr);
                String flg = jsonObj.getString(Constants.TAG_FLG);
                switch (flg) {
                    case "user logged out":
                    {
                        sm.logoutUser();
                        break;
                    }
                    case "query failed": {
                        Toast.makeText(getApplicationContext(),"Error Connection",Toast.LENGTH_LONG).show();
                        break;
                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void sendDataToDBController() {

        String user = sm.getUserDetails().get(Constants.TAG_EMAIL);
        BasicNameValuePair tagReq = new BasicNameValuePair("tag","logout");
        BasicNameValuePair userNameParam = new BasicNameValuePair("username",user);
        List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();
        nameValuePairList.add(tagReq);
        nameValuePairList.add(userNameParam);
        dbController =  new DBcontroller(this,this);

        dbController.execute(nameValuePairList);

    }

    @Override
    public void preProcess() {
        this.progress = ProgressDialog.show(this, "Log Out",
                "Logging out...", true,false);
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {

        Fragment fragment = null;

        switch (position) {
            case 0: //Home
                fragment = new GoogleMapFragmentController();
                break;
            case 1: //Profile
                fragment = new ProfileFragmentController();
                break;
            case 2: //Search Events
                //fragment = new SearchEventFragmentController();
                break;
            case 3: //Create Events
                fragment = new CreateEventFragmentController();
                break;
            case 4: //Manage Events
                fragment = new ManageEventFragmentController();
                break;
            case 5: //Attending List
                //fragment = new AttendingListFragmentController();
                break;
            case 6: //Recent Searches
                //fragment = new RecentSearchesFragmentController();
                break;
            case 7: { //Log Out
                logout();
                finish(); //destroy the main activity
            }
                break;

            default:
                break;
        }

        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            getSupportActionBar().setTitle(mNavigationDrawerItemTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            Log.e("MainActivity", "Error in creating fragment");
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getSupportActionBar().setTitle(mTitle);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
    public void logout()
    {

        sendDataToDBController();
    }
    /*@Override
    protected void onDestroy() {
        super.onDestroy();
        logout();
    }*/
}

7 个答案:

答案 0 :(得分:9)

为所有片段设置它。这应该做的工作!!

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.id.your_fragment_layout, container,
            false);
    getActivity().setTitle("<your title>");

    return rootView;
}

答案 1 :(得分:7)

试试这个:

SELECT * FROM (
   SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table1 WHERE product_name LIKE '%$search%'
                    UNION ALL
   SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table2 WHERE product_name LIKE '%$search%'
 ) AS big_table1 ORDER BY product_price LIMIT 1

UNION

SELECT * FROM (
    SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table1 WHERE product_name LIKE '%$search%'
                        UNION ALL
    SELECT id_product, picture_url, product_name, product_price, tracking_link, '$ecommerce2->nama_ecommerce' AS table_identity FROM table2 WHERE product_name LIKE '%$search%'
 ) AS big_table2 ORDER BY product_price DESC LIMIT 1

答案 2 :(得分:3)

好的,我发现了问题,你的答案很好,我每次都从片段中更改标题,但另外我需要禁用此行:

getSupportActionBar().setTitle(mDrawerTitle);

来自onDrawerOpened和onDrawerClosed

答案 3 :(得分:2)

不要将标题设置为ActionBar,将标题设置为Activity,您可以通过activity或fragment执行此操作。 对于活动:

setTitle("New Title");

或片段:

getActivity().setTitle("New Title");

答案 4 :(得分:0)

在片段

中添加此内容
getActivity().setTitle("title");

添加从抽屉活动

中移除此行
getActivity().setTitle("title");

答案 5 :(得分:0)

尝试这个对我有用的

  

在app_bar活动的工具栏中放置一个Textview

     

在片段的oncreateView内放置此代码

 TextView heading;
    heading=(TextView)getActivity().findViewById(R.id.Id_title);
    heading.setText("your text");

使用此功能,您可以使用自己的文本命名每个片段

答案 6 :(得分:0)

在onCreateView()中编写以下代码:

//Sidebar Filter Genre Tracks
$(document).ready(function () {
    $('.genreTag').on('change', function (e)
    {

        $('input.filter-playlist, .popularGenreTag, .mood-emotion, .production-type, .vocals, .all-tracks, .last-year, .last-month, .last-week, .last-day').each(function() {
            var $this = $(this);
            $this.prop('checked', false);
            $this.parent().find('> div').removeClass('chk-checked').addClass('chk-unchecked');
        });

        e.preventDefault();
        id = [];

        $('.genreTag:checked').each(function()
        {
            id.push($(this).attr('id'));
        });

        $.get("/genre-tags/", {id: id}, function(data)
        {
            hideLoader();
            refreshedPage = $(data);
            newDemo = refreshedPage.find(".libraryWrapper, .albumWrapper, .composersWrapper, .albumsListWrapper, .albumsWrapper, .accountWrapper, .distributionsWrapper, .PaymentsWrapper, .contactWrapper, .contractsWrapper, .toolsWrapper, .blogWrapper, .pageWrapper, .cartWrapper, .pageWrapper").html();

            $('.libraryWrapper, .albumsWrapper, .albumWrapper, .composersWrapper, .albumsListWrapper, .accountWrapper, .distributionsWrapper, .PaymentsWrapper, .contactWrapper, .contractsWrapper, .toolsWrapper, .blogWrapper, .pageWrapper, .cartWrapper, .pageWrapper').html(newDemo);
            activatePlayer()
            initTrackInfo();
        });
    });
});


//route
Route::get('genre-tags/', ['as' => 'tag.popular-genres', 'uses' => 'SideFilterController@genresFilter']);

//checkbox blade file

<li class="lib">
            <label><input class="genreTag"  id="{{ $genreTag->id}}" type="checkbox" name="" value="{{ $genreTag->name }}">{{{ $genreTag->name }}} ({{count(json_decode($genreTag->elements, true))+ count(json_decode($genreTag->tracks, true))}}) </label>
        </li>