首页 > 解决方案 > 更改菜单导航栏上项目的标题

问题描述

我被创建了一个导航活动。它有一些项目包括登录项目。我想在用户登录时更改它的标题。我该怎么办?导航栏在 Activity Main 中,Login 是其他活动。

这是 xml 文件。“Đăng nhập”是登录按钮。

xmlns:tools="http://schemas.android.com/tools"
tools:showIn="navigation_view">
<group android:checkableBehavior="single">
    <item
        android:id="@+id/nav_tamlinh"
        android:icon="@drawable/ic_menu_camera"
        android:title="Du lịch tâm linh" />
    <item
        android:id="@+id/nav_vanhoa"
        android:icon="@drawable/ic_menu_camera"
        android:title="Du lịch văn hóa" />
    <item
        android:id="@+id/nav_amthuc"
        android:icon="@drawable/ic_menu_camera"
        android:title="Du lịch ẩm thực" />
    <item
        android:id="@+id/nav_thangcanh"
        android:icon="@drawable/ic_menu_camera"
        android:title="Du lịch thắng cảnh" />
    <item
        android:id="@+id/nav_lichsu"
        android:icon="@drawable/ic_menu_camera"
        android:title="Du lịch lịch sử" />
    <item
        android:id="@+id/nav_trainghiem"
        android:icon="@drawable/ic_menu_camera"
        android:title="Du lịch trải nghiệm" />
    <item
        android:id="@+id/nav_login"
        android:icon="@drawable/ic_menu_manage"
        android:title="Đăng nhập" />
</group>
<item android:title="Communicate">
    <menu>
        <item
            android:id="@+id/nav_share"
            android:icon="@drawable/ic_menu_share"
            android:title="Share" />
        <item
            android:id="@+id/nav_send"
            android:icon="@drawable/ic_menu_send"
            android:title="Send" />
    </menu>
</item>

这是登录活动。如何编写更改标题的方法

public class Login extends AppCompatActivity {
boolean isLogined= false;
LoginButton loginButton;
CallbackManager callbackManager;
ImageView imageView;
ImageView avatar;
TextView txtUsername, txtEmail;
String image_url;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    loginButton = findViewById(R.id.login_button);
    imageView = findViewById(R.id.imageView);
    avatar = findViewById(R.id.avatar);
    txtUsername = findViewById(R.id.txtUsername);
    txtEmail = findViewById(R.id.txtEmail);
    boolean loggedOut = AccessToken.getCurrentAccessToken() == null;
    if (!loggedOut) {       Picasso.with(this).load(Profile.getCurrentProfile().getProfilePictureUri(200, 200)).into(imageView);
        Log.d("TAG", "Username is: " + Profile.getCurrentProfile().getName());
        getUserProfile(AccessToken.getCurrentAccessToken());
    }
    AccessTokenTracker fbTracker = new AccessTokenTracker() {
        @Override
        protected void onCurrentAccessTokenChanged(AccessToken accessToken, AccessToken accessToken2) {
            if (accessToken2 == null) {
                txtUsername.setText(null);
                txtEmail.setText(null);
                imageView.setImageResource(0);
                image_url = "ssss";
                Toast.makeText(getApplicationContext(),"User Logged Out.",Toast.LENGTH_LONG).show();
            }
        }
    };
    fbTracker.startTracking();
    loginButton.setReadPermissions(Arrays.asList("email", "public_profile"));
    callbackManager = CallbackManager.Factory.create();
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            boolean loggedOut = AccessToken.getCurrentAccessToken() == null;
            if (!loggedOut) {
                isLogined = true;
                Picasso.with(Login.this).load(Profile.getCurrentProfile().getProfilePictureUri(200, 200)).into(imageView);
                Log.d("TAG", "Username is: " + Profile.getCurrentProfile().getName());
                getUserProfile(AccessToken.getCurrentAccessToken());
                Intent i = new Intent(Login.this, MainActivity.class);
                Bundle Sender = new Bundle();
                Sender.putString("id", Profile.getCurrentProfile().getId());
                Sender.putBoolean("status", isLogined);
                i.putExtras(Sender);
            }
        }
        @Override
        public void onCancel() {
            // App code
        }
        @Override
        public void onError(FacebookException exception) {
            // App code
        }
    });
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    callbackManager.onActivityResult(requestCode, resultCode, data);
    super.onActivityResult(requestCode, resultCode, data);
}
private void getUserProfile(AccessToken currentAccessToken) {
    GraphRequest request = GraphRequest.newMeRequest(
            currentAccessToken, new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    Log.d("TAG", object.toString());
                    try {
                        String first_name = object.getString("first_name");
                        String last_name = object.getString("last_name");
                        String email = object.getString("email");
                        String id = object.getString("id");
                        image_url = "https://graph.facebook.com/" + id + "/picture?type=normal";
                        txtUsername.setText("First Name: " + first_name + "\nLast Name: " + last_name);
                        txtEmail.setText(email);
                        Picasso.with(Login.this).load(image_url).into(imageView);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "first_name,last_name,email,id");
    request.setParameters(parameters);
    request.executeAsync();
}
@Override
public void onBackPressed() {
    Bundle bundle = new Bundle();
    bundle.putString("ava",image_url);
    Intent intent = new Intent();
    intent.putExtras(bundle);
    setResult(111, intent);
    super.onBackPressed();
}}

和 MainActivity

public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ListView evtList;
ArrayList<ListEvent> listEV;
EVAdapter adapterEV;
ImageView imageView;
@Override

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(layout.activity_main);
    anhXa();
    adapterEV = new EVAdapter(this, layout.item_event,listEV);
    evtList.setAdapter(adapterEV);
    Toolbar toolbar = (Toolbar) findViewById(id.toolbar);
    setSupportActionBar(toolbar);
    DrawerLayout drawer = (DrawerLayout) findViewById(id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, string.navigation_drawer_open, string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();
    NavigationView navigationView = (NavigationView) findViewById(id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);

}
private void anhXa() {
    evtList = findViewById(id.listev);
    listEV = new ArrayList<>();
    listEV.add(new ListEvent("Lễ hội đền Hùng", drawable.gthv, "Bài viết về giỗ tổ Hùng Vương sẽ hiện ở đây"));
    //listEV.add(new ListTL("Tứ Trấn","Hà Nội", R.drawable.tutran));
    listEV.add(new ListEvent("Lễ hội chùa Yên Tử", drawable.yentu, "Bài viết về lễ hội chùa Yên Tử sẽ hiện ở đây"));
}
@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


@SuppressWarnings("StatementWithEmptyBody")

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_tamlinh) {
        Intent dl_tamlinh = new Intent(this, DLTamLinh.class);
        startActivity(dl_tamlinh);

    } else if (id == R.id.nav_vanhoa) {
        Intent dl_vanhoa = new Intent(this, DLVanHoa.class);
        startActivity(dl_vanhoa);

    } else if (id == R.id.nav_amthuc) {

    } else if (id ==R.id.nav_login) {
        Intent login = new Intent(this, Login.class);
        startActivityForResult(login, 111);
     //   startActivity(login);

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        if (bundle != null) {
            String uri = bundle.getString("ava");
            Toast.makeText(this, "" + uri, Toast.LENGTH_SHORT).show();
            imageView = (ImageView)findViewById(id.avatar);
            Picasso.with(this).load(uri + "").placeholder(drawable.vietnam).into(imageView);
        }

    }
}

标签: androiduinavigationbar

解决方案


在您的登录活动中:

                // If the login was successful
                Intent intent = new Intent();

                // If you need to pass anything back
                intent.putExtra("has_changed", hasChanged); 
                intent.putExtra("location", theLocation);

                // Set the successful Result code or if not successful set the failed or cancled result code
                setResult(RESULT_OK, intent);
                finish();

在您的主要活动中:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == android.app.Activity.RESULT_OK){  
           //Change the Nav Menu Text Here
        } 
}

推荐阅读