简体   繁体   English

如何通过 model 将用户输入从登录传递到主片段

[英]How to pass user input from Login to home fragment through model

I recently started learning Android development and have trouble passing data.我最近开始学习 Android 开发,在传递数据时遇到了麻烦。

I started with the navigation drawer template on android studio.我从 android studio 上的导航抽屉模板开始。 I have a login page that requires username & password fields.我有一个需要用户名和密码字段的登录页面。 When entered, the login page redirects to a MainActivity.java.输入后,登录页面重定向到 MainActivity.java。 But this MainActivity.java comprises of various fragments - HomeFragment, GalleryFragment and Slideshow (these were default from the template).但是这个 MainActivity.java 包含各种片段 - HomeFragment、GalleryFragment 和 Slideshow(这些是模板的默认设置)。 Along with the fragments there are HomeViewModel, GalleryViewModel and SlideshowViewModel.除了片段之外,还有 HomeViewModel、GalleryViewModel 和 SlideshowViewModel。

Requirements: This username should be stored until the app is closed.要求:此用户名应保存到应用程序关闭。 I do not need to save any session etc because this app is mainly for testing purposes (to test an API and SDK).我不需要保存任何 session 等,因为这个应用程序主要用于测试目的(测试 API 和 SDK)。 I have some confusion on when to use SharedPreferences, Bundle passing, LiveModel etc and how I should be passing it.我对何时使用 SharedPreferences、Bundle 传递、LiveModel 等以及我应该如何传递它有些困惑。

I've been able to do the saving of username and displaying it on HomeFragment - but I doubt this is the right approach because I think should be passing it through HomeModel?我已经能够保存用户名并将其显示在 HomeFragment 上 - 但我怀疑这是正确的方法,因为我认为应该通过 HomeModel 传递它? Any help is appreciated.任何帮助表示赞赏。 Thanks!!谢谢!!

Most of the code here is from the template.这里的大部分代码都来自模板。

Login.java登录.java

package com.developer.tmx_android_v6;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.developer.tmx_android_v6.ui.home.HomeFragment;
import com.developer.tmx_android_v6.ui.home.HomeViewModel;
import com.google.android.material.textfield.TextInputEditText;

public class Login extends AppCompatActivity {

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

    public void signUpHandler(View target) {
        Intent myintent = new Intent(this, SignUp.class);
        startActivity(myintent);

    }


    public void LoginHandler(View target) {

        Intent myintent = new Intent(this, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("key1", "GFG :- Main Activity");

////        pass user input
        TextInputEditText username = (TextInputEditText) findViewById(R.id.username);
        TextInputEditText password = (TextInputEditText) findViewById(R.id.password);

        String usernameText = username.getText().toString();
        String passwordText = password.getText().toString();

        bundle.putString("username", usernameText);
        bundle.putString("password", passwordText);

        myintent.putExtras(bundle);
        startActivity(myintent);

    }
}

MainActivity.java MainActivity.java

package com.developer.tmx_android_v6;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Menu;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.navigation.NavigationView;

import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

public class MainActivity extends AppCompatActivity {

    private AppBarConfiguration mAppBarConfiguration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
//
//        Bundle bundle = getIntent().getExtras();
//
//        String username = bundle.getString("username", "DefaultUsername");
//        String password = bundle.getString("password", "DefaultPassword");
//        Log.i("print values", "Main Activity: username and pw is: " + username + " " + password);

        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        NavigationView navigationView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        mAppBarConfiguration = new AppBarConfiguration.Builder(
                R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow)
                .setDrawerLayout(drawer)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
        NavigationUI.setupWithNavController(navigationView, navController);
    }



    @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 onSupportNavigateUp() {
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        return NavigationUI.navigateUp(navController, mAppBarConfiguration)
                || super.onSupportNavigateUp();
    }
}

HomeFragment.java首页Fragment.java


import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.developer.tmx_android_v6.R;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {

//        works but not sure if I should be passing it directly to fragment
//        String username = getActivity().getIntent().getExtras().getString("username");
//        String password = getActivity().getIntent().getExtras().getString("password");
//
//        Log.i("print values", "Home Fragment Activity: username and pw is: " + username  + " " + password);

        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);

        TextView usernameTextView = (TextView) root.findViewById(R.id.username);
        usernameTextView.setText("Welcome, " + username + "!" );

        final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        return root;
    }
}

HomeViewModel.java主页查看型号.java

package com.developer.tmx_android_v6.ui.home;


import android.os.Bundle;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

public class HomeViewModel extends ViewModel {

    private MutableLiveData<String> mText;

    public HomeViewModel() {

//      how to get data and pass it here?

        mText = new MutableLiveData<>();
//        mText.setValue("Welcome! -HomeViewModel-");

    }


    public LiveData<String> getText() {
        return mText;
    }
}

You can pass the LoginActivity 's username fields to the MainActivity with an IntentExtra and then access the passed fields from any Fragment .您可以使用IntentExtraLoginActivity的用户名字段传递给MainActivity ,然后从任何Fragment访问传递的字段。

  1. Declare a public static field where the username and password can be stored and accessed by the fragments.声明一个public static字段,其中usernamepassword可以被片段存储和访问。 In your MainActvity declare:在您的MainActvity声明中:

    public static String userNameText;
    public static String passwordText;

  1. In the onCreate() of MainActivity fetch the Intent 's Extra :MainActivityonCreate()中获取IntentExtra

    Intent intent = getIntent();
    userNameText = intent.getStringExtra("username");
    passwordText = intent.getStringExtra("passoword");

  1. Then you can access those fields from any fragment by getting the values from the MainActivity since the fields are public and static .然后,您可以通过从MainActivity获取值来从任何片段访问这些字段,因为这些fieldspublic的和static In your HomeFragment 's onCreateView() get the values:在您的HomeFragmentonCreateView()中获取值:

    String userNameText  = MainActivity.userNameText;
    String passwordText = MainActivity.passwordText;

Use SharedPreferences for small data with key value pairs like username or password.将 SharedPreferences 用于具有键值对(如用户名或密码)的小数据。 Use Bundle to pass data from one activity to another.使用 Bundle 将数据从一个活动传递到另一个活动。 Use ViewModel to store large data which will survive during screen orientation changes.使用 ViewModel 存储在屏幕方向更改期间将保留的大数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 用主页片段替换登录片段 - replace login fragment by home fragment 如何通过 RecyclerViewAdapter 将数据从活动传递到片段? - How to pass data from an activity to fragment through RecyclerViewAdapter? 如何通过清单 <Model> 从活动到片段 - How can I pass List<Model> from Activity to Fragment 通过单击按钮将数据从片段传递到片段 - Pass Data from Fragment to Fragment Through Button Click 通过底部导航视图通过活动将价值从一个片段传递到另一个片段 - Pass value from fragment to fragment through activity with bottom navigation view 如何将 ParcelableArrayList 从 Fragment 传递到 Fragment? - How to pass ParcelableArrayList from Fragment to Fragment? 如何将数据从 Fragment 传递到 Tablayout Fragment - How to pass data from Fragment to Tablayout fragment 用户通过 inte.net 进行身份验证后,如何从登录活动转发或移动到主页活动? - How to forward or move to home activity from login activity after user is authenticated over internet? Android:在Fragment中处理用户输入 - Android: handle user input from within a Fragment 用户输入未通过 Python 中的 if 语句,但能够在 Java 中通过 - user input not passing through if statement in Python, but is able to pass through in Java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM