当前位置: 首页 > 知识库问答 >
问题:

如何从其片段之一在导航活动的导航抽屉中写入用户名?

侯和惬
2023-03-14

主页ctivity.java(航海活动)

   import android.app.Fragment;
   import android.app.FragmentManager;
   mport android.app.FragmentTransaction;
   import android.content.Intent;
   import android.os.Bundle;
   import android.support.design.widget.NavigationView;
   import android.support.v4.view.GravityCompat;
   import android.support.v4.widget.DrawerLayout;
   import android.support.v7.app.ActionBarDrawerToggle;
   import android.support.v7.app.AppCompatActivity;
   import android.support.v7.widget.Toolbar;
   import android.view.Menu;
   import android.view.MenuItem;
   import android.view.View;
   import android.widget.TextView;

   import com.example.dellpc.reuz_app.DTO.User;
   import com.example.dellpc.reuz_app.Fragments.BrowseAdFragment;
   import com.example.dellpc.reuz_app.Fragments.LoginFragment;
   import com.example.dellpc.reuz_app.Fragments.NetworkErrorFragment;
   import com.example.dellpc.reuz_app.Fragments.TopMainFragment;
   import com.example.dellpc.reuz_app.R;
   import com.example.dellpc.reuz_app.utils.CheckNetworkConnection;
   import com.example.dellpc.reuz_app.utils.NetworkErrorFragmentSetter;

   public class HomeActivity extends AppCompatActivity
   implements NavigationView.OnNavigationItemSelectedListener {
   private Fragment fragment;
   private String title;
   private DrawerLayout drawer;
   private NavigationView navigationView;
   private View layout;
   private User user=null;
       @Override

     protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_home);
     Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setTitle("REUZ");
    drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open,                          R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.bringToFront();
    System.out.println(getSupportActionBar().getHeight());
    View headerLayout = navigationView.getHeaderView(0);
    layout=headerLayout.findViewById(R.id.navigationHeader);
    getSupportActionBar().setTitle("REUZ");

    this.setInitialFragment();
    this.listeners();

    /*this.getUserObject();*/
}
   public void listeners(){
   layout.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     if(CheckNetworkConnection.isConnectionAvailable(HomeActivity.this))
        {
            getLoginFragment();
        }
        else{
         fragment=                         NetworkErrorFragmentSetter.getNetworkErrorFragment(HomeActivity.this);
         replaceFragment();

     }
    }
});

       getFragmentManager().addOnBackStackChangedListener(new                FragmentManager.OnBackStackChangedListener() {
    @Override
    public void onBackStackChanged() {
        Fragment currentFragment =  getFragmentManager().findFragmentById(R.id.content_frame);
        if (currentFragment instanceof TopMainFragment) {
           getSupportActionBar().setTitle("REUZ");
        }
        else if (currentFragment instanceof BrowseAdFragment) {
            getSupportActionBar().setTitle("All Categories");
        }
        else if (currentFragment instanceof LoginFragment) {
            getSupportActionBar().setTitle("LOGIN");
        }
        else if(currentFragment instanceof NetworkErrorFragment){
            getSupportActionBar().setTitle("NETWORK ERROR");
        }

               }
});
   }
@Override
    public void onBackPressed() {
     //drawer = (DrawerLayout) findViewById(R.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.home, 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_home) {
        // Handle the home action
        setInitialFragment();


    } else if (id == R.id.nav_browse) {
                fragment=new BrowseAdFragment();

    } else if (id == R.id.nav_submitAd) {
                Intent intent=new  Intent(getApplicationContext(),SubmitAdActivity.class);
                startActivity(intent);
    } else if (id == R.id.nav_help) {

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

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

    }
        replaceFragment();
     //drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    //drawer.closeDrawer(GravityCompat.START);
    return true;
}

public void setTitleOnActionBar(String title) {


    getSupportActionBar().setTitle(title);
}


public void setInitialFragment(){
    fragment=new TopMainFragment();
    FragmentTransaction ft=getFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, fragment);
   // ft.addToBackStack(null);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.commit();

    drawer.closeDrawer(GravityCompat.START);
}
public void getLoginFragment(){
    fragment=new LoginFragment();
    FragmentTransaction ft=getFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(null);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.commit();

    drawer.closeDrawer(GravityCompat.START);

}
public void replaceFragment(){
    FragmentTransaction ft=getFragmentManager().beginTransaction();
    ft.replace(R.id.content_frame, fragment);
    ft.addToBackStack(null);
    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
    ft.commit();

    drawer.closeDrawer(GravityCompat.START);
}
@Override
public void onResume() {
    super.onResume();
    // Set the title

}
public void getUserObject(User user){
    this.user=user;

    if(user!=null){
        changeLayoutName();
    }
}
public void changeLayoutName(){
   TextView name= (TextView)layout.findViewById(R.id.textView8);
    name.setText(user.getName());
}
}

登录碎片。java(片段)

         import android.app.Fragment;
        import android.content.Intent;
        import android.os.Bundle;
        import android.support.design.widget.NavigationView;
        import android.support.v7.widget.Toolbar;
        import android.text.Editable;
        import android.text.TextWatcher;
        import android.view.LayoutInflater;
        import android.view.View;
        import android.view.ViewGroup;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.widget.Toast;

        import com.example.dellpc.reuz_app.Activities.HomeActivity;
        import com.example.dellpc.reuz_app.Activities.RegisterActivity;
        import com.example.dellpc.reuz_app.Activities.UnableToLoginActivity;
        import com.example.dellpc.reuz_app.DTO.User;
        import com.example.dellpc.reuz_app.R;
        import com.example.dellpc.reuz_app.Validator.IValidation;
        import com.example.dellpc.reuz_app.Validator.Validation;
        import com.example.dellpc.reuz_app.dao.IUserDAO;
        import com.example.dellpc.reuz_app.dao.UserDAO;


        public class LoginFragment extends Fragment {

    private EditText emailET, passwordET;
    private Button loginBTN;
    private TextView utlTV, registerTV, invalidEmailTV, invalidPasswordTV;
    private View view;
    private NavigationView navigationView;
    private User user;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // keep the fragment and all its data across screen rotation
        setRetainInstance(true);
    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view = inflater.inflate(R.layout.fragment_login, container, false);
        Toolbar toolbar = (Toolbar)view.findViewById(R.id.toolbar);

        ((HomeActivity)getActivity()).getSupportActionBar().setTitle("LOGIN");
        this.mapping();
        this.listeners(view);
        return view;
    }


    public void mapping(){
        emailET = (EditText)view.findViewById(R.id.emailET);
        passwordET = (EditText)view.findViewById(R.id.passwordET);
        loginBTN = (Button)view.findViewById(R.id.loginBTN);
        utlTV = (TextView)view.findViewById(R.id.utlTV);
        invalidEmailTV = (TextView)view.findViewById(R.id.invalidEmailTV);
        invalidPasswordTV = (TextView)view.findViewById(R.id.invalidPasswordTV);
        registerTV = (TextView)view.findViewById(R.id.registerTV);
    }

    public void listeners(View view){
        loginBTN.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String email = emailET.getText().toString();
                String password = passwordET.getText().toString();
                validateAndMoveToActivity(email, password);

            }
        });

        utlTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent utlIntent = new Intent(getActivity(), UnableToLoginActivity.class);
                startActivity(utlIntent);
            }
        });

        registerTV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent registerIntent = new Intent(getActivity(), RegisterActivity.class);
                startActivity(registerIntent);
            }
        });

        emailET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                invalidEmailTV.setText("");
                invalidPasswordTV.setText("");
            }
        });

        passwordET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s)
            {
                invalidEmailTV.setText("");
                invalidPasswordTV.setText("");
            }
        });
    }

    public void validateAndMoveToActivity(String email, String password){
        IValidation iValidation = new Validation();
        if(!iValidation.isFilled(email) && iValidation.isFilled(password)){
            invalidEmailTV.setText("This field is required");
        }
        else if(iValidation.isFilled(email) && !iValidation.isFilled(password)) {
            invalidPasswordTV.setText("This field is required");
        }
        else if(!iValidation.isFilled(email) && !iValidation.isFilled(password)){
            invalidEmailTV.setText("This field is required");
            invalidPasswordTV.setText("This field is required");
        }
        else
        {
            IUserDAO iUserDAO = new UserDAO(getActivity().getApplicationContext());

          /*
                if(iUserDAO.isEmailPasswordExist(email, password))*/
            if(iUserDAO.isEmailExist(email)){
            user=iUserDAO.isEmailPasswordExist(email,password);
            if(user!=null)
            {
                    Toast.makeText(view.getContext(), "Successful Login", Toast.LENGTH_SHORT).show();
                HomeActivity home=new HomeActivity();
                    home.getUserObject(user);
                   /* Intent homeACIntent = new Intent(view.getContext(), HomeActivity.class);
                    homeACIntent.putExtra("user",user);
                    startActivity(homeACIntent);*/
                    // Remove this fragment.
                    getActivity().getFragmentManager().popBackStack();
                }
                else {
                    invalidPasswordTV.setText("Invalid email or password");
                }
            }
            else {
                // After successful login where do you want to move your activity.
                invalidEmailTV.setText("Invalid phone number or email");
            }
        }
    }
@Override
public void onSaveInstanceState(Bundle state) {
    super.onSaveInstanceState(state);
    state.putSerializable("user",user);
}


}

HomeActivity包含两个片段-Login和Top最初它显示Top fragment Login fragment在成功注册后有一个注册选项用户被导航到登录片段现在登录后控件必须到达“Top”并且用户的名称必须写在导航抽屉中怎么做?

这是我的抽屉。我不想写用户名而不是欢迎来到Reuz

首页活动

共有1个答案

邹桐
2023-03-14

我看到您正在将用户详细信息保存在本地数据库中,然后在用户成功登录后尝试加载数据。您面临的问题是没有更新文本视图。一种可能的解决方案是,您可以从TopMainFragment本身的onViewCreated()方法调用changeLayoutName()方法。

 类似资料:
  • 我不是Android方面的专家,但对片段非常感兴趣。非常感谢您的帮助! 我在我的应用程序中实现了一个导航抽屉。有一个基本抽屉活动和一些片段,用户可以从抽屉菜单中切换。如果我想转移到另一个片段,没有问题,但当我使用意图开始一个新的活动时,它是有效的。如果你看一下我下面的代码,你会发现我使用了两个独立的菜单:一个用于操作栏图标(购物车和搜索),意图在其中完美工作,另一个用于导航抽屉在片段之间跳转。有没

  • 我试过了。我不成功。我正在写我的步骤。如果有人能帮我。 > 使用Android Studio创建新项目并选择“导航抽屉活动” 我将FrameLayout放在主活动中,如下所示 我使用v4创建了新类,如下所示。应用程序。碎片 我制作了碎片管理器,如下所示, 调用**public boolean onNavigationItemSelected(MenuItem项)** 我学了一点,但没能成功。这不是

  • 我已经从Android官方网站下载了示例项目http://developer.android.com/training/implementing-navigation/nav-drawer.html.我试图了解导航抽屉是如何工作的。所以,我有一个疑问,他们从左侧菜单中为每个项目调用一个片段。在我的项目中,我有一个大活动,我试图通过这个片段调用它: 公共类HomeFragment扩展了片段{ } 但

  • 我有一个活动a,一个列表片段P和两个片段Q和R。 当应用程序启动时,会创建一个,加载P。根据用户点击的内容,它被Q或R取代。 现在,通过参考本教程,我实现了一个导航抽屉,向用户显示某些项目。然而,由于我在活动中实现了导航抽屉,它显示了所有片段。我希望它只对P可用。 (非常类似于谷歌Gmail应用程序。当用户在主屏幕上时,抽屉就出现了。当用户点击打开电子邮件时,抽屉就会切换到后退按钮) 我不知道如何

  • 我是android新手。我想实现一个由项目列表组成的导航抽屉,单击它会打开一个新活动。基本上是所有活动的导航抽屉。当我从导航抽屉中选择一个项目时,特定的活动就会打开。导航抽屉代码是通过执行空活动来实现的。我想在所有活动中实现导航抽屉功能,这些活动被视为空活动,这些活动已经有了一些功能,导航抽屉功能也可以工作。请帮帮我。 这是activity_header档案 这是我的主要活动 这是头活动java代