簡體   English   中英

如何在新用戶登錄時更改文本視圖?

[英]How to change the text view when a new user is logged in?

我正在創建一個Android工資單應用程序,當用戶登錄時,它應該在導航屏幕中顯示他/她的詳細信息。 當新用戶登錄時,它應該自動更改詳細信息,我該怎么做才能幫助我。

我知道我之前已經問過這個問題,但是當我舉個例子時

  1. Login.xml

      <android.support.v7.widget.LinearLayoutCompat android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.v7.widget.AppCompatImageView android:layout_width="300dp" android:layout_height="200dp" android:layout_gravity="center_horizontal" android:layout_marginTop="40dp" android:src="@drawable/civilsoft" /> <android.support.design.widget.TextInputLayout android:id="@+id/textInputLayoutName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" app:errorEnabled="true"> <android.support.design.widget.TextInputEditText android:id="@+id/editTextName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="User Name" android:inputType="textEmailAddress" android:textColor="@android:color/white" /> </android.support.design.widget.TextInputLayout> <android.support.design.widget.TextInputLayout android:id="@+id/textInputLayoutPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="8dp" app:errorEnabled="true" app:passwordToggleEnabled="true" app:passwordToggleTint="@color/colorAccent"> <android.support.design.widget.TextInputEditText android:id="@+id/editTextPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Password" android:inputType="textPassword" android:textColor="@android:color/white" /> </android.support.design.widget.TextInputLayout> <Button android:id="@+id/buttonLogin" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" android:layout_marginTop="16dp" android:background="@drawable/btn_rounded" android:text="login" android:textColor="@android:color/white" /> <TextView android:id="@+id/textViewCreateAccount" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="16dp" android:layout_marginTop="16dp" android:gravity="center_horizontal" android:textColor="@android:color/white" /> </android.support.v7.widget.LinearLayoutCompat> 
  2. 登錄活動

      //Declaration EditTexts EditText editTextName; EditText editTextPassword; //Declaration TextInputLayout TextInputLayout textInputLayoutName; TextInputLayout textInputLayoutPassword; //Declaration Button Button buttonLogin; //Declaration DatabaseHelper DatabaseHelper DH; private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); DH = new DatabaseHelper(this); initCreateAccountTextView(); initViews(); //set click event of login button buttonLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // Check user input is correct or not if (validate()){ // Get values from edit text fields. String Name = editTextName.getText().toString(); String Password = editTextPassword.getText().toString(); // Authenticate User User currentUser = DH.Authenticate(new User(null, null, Name, Password)); //Check Authentication is successful or not if (currentUser != null) { //Snackbar.make(buttonLogin, "Login Successful!", Snackbar.LENGTH_LONG).show(); //User Logged in successfully Launch You home screen activity Intent intent = new Intent (Login.this,Navigation.class); intent.putExtra("EmpID", Employee.getEmpID()); intent.putExtra("EmpCode", Employee.getEmpCode()); intent.putExtra("EmpName", Employee.getEmpName()); startActivity(intent); finish(); } else { // User Logged in failed. Snackbar.make(buttonLogin, "Login Failed, please try again!", Snackbar.LENGTH_LONG).show(); } } } // This method is used to validate input given by user private boolean validate() { boolean valid = false; // Get values from editText fields String Name = editTextName.getText().toString(); String Password = editTextPassword.getText().toString(); // Handling validation for User Name field. if(Name.isEmpty()){ valid = false; textInputLayoutName.setError("Please enter valid User Name!"); } else { valid = true; textInputLayoutName.setError(null); } // Handling validation for Password field. if(Password.isEmpty()) { valid = false; textInputLayoutPassword.setError("Please enter valid Password!"); } else { textInputLayoutPassword.setError(null); } return valid; } }); } // This method is used to connect XML views to its objects private void initViews() { editTextName = (EditText) findViewById(R.id.editTextName); editTextPassword = (EditText) findViewById(R.id.editTextPassword); textInputLayoutName = (TextInputLayout) findViewById(R.id.textInputLayoutName); textInputLayoutPassword = (TextInputLayout) findViewById(R.id.textInputLayoutPassword); TextView textView = (TextView)findViewById(R.id.EmpID); TextView textView1 = (TextView)findViewById(R.id.EmpCode); TextView textView2 = (TextView)findViewById(R.id.EmpName); buttonLogin = (Button) findViewById(R.id.buttonLogin); } // This method is for handling fromHTML method depreciation. @SuppressWarnings("deprecation") public static Spanned fromHtml(String html) { Spanned result; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) { result = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY); } else { result = Html.fromHtml(html); } return result; } // This method used to set Create account TextView text and click event (multiple colors // for TextView yet not supported in XML so I have done it programmatically) private void initCreateAccountTextView() { TextView textViewCreateAccount = (TextView) findViewById(R.id.textViewCreateAccount); textViewCreateAccount.setText(fromHtml("<font color='#ffffff'>I don't have account yet. </font><font color='#0c0099'>create one</font>")); textViewCreateAccount.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(Login.this, Register.class); startActivity(intent); } }); } } 
  3. Content_Navigation.xml

      <LinearLayout android:id="@+id/linear" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/EmpID" android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/EmpId" android:textAlignment="center" android:textColor="@color/colorAccent" android:textSize="25dp" /> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/EmpCode" android:textAlignment="center" android:text="@string/EmpCode" android:textSize="25dp" android:textColor="@color/colorAccent" /> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/EmpName" android:textAlignment="center" android:text="@string/EmpCode" android:textSize="25dp" android:textColor="@color/colorAccent" /> </LinearLayout> 
  4. 導航活動

      //Declaration Textview; TextView EmpID, EmpCode, EmpName; // EmployeeHelper db; EmployeeHelper mydb; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_navigation); mydb = new EmployeeHelper(this); mydb.insertData("112", "002", "xxx"); mydb.getAllData(); TextView textView = (TextView)findViewById(R.id.EmpID); TextView textView1 = (TextView)findViewById(R.id.EmpCode); TextView textView2 = (TextView)findViewById(R.id.EmpName); String EmpID = getIntent().getStringExtra("EmpID"); String EmpCode = getIntent().getStringExtra("EmpCode"); String EmpName = getIntent().getStringExtra("EmpName"); textView.setText("EmpID - 112"); textView1.setText("EmpCode - 002"); textView2.setText("EmpName - xxx"); textView.setText("EmpID - 111"); textView1.setText("EmpCode - 001"); textView2.setText("EmpName - bbb"); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); FloatingActionButton fab = (FloatingActionButton) 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 = (DrawerLayout) findViewById(R.id.drawer_layout); ActionBarDrawerToggle toggle = new ActionBarDrawerToggle( this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); drawer.addDrawerListener(toggle); toggle.syncState(); NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); navigationView.setNavigationItemSelectedListener(this); } @Override public void onBackPressed() { DrawerLayout 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.navigation, 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_camera) { // Handle the intent code to navigate from one page to another. startActivity( new Intent(Navigation.this, LeaveTran.class)); } else if (id == R.id.nav_gallery) { startActivity( new Intent(Navigation.this, PersonalProfile.class)); } else if (id == R.id.nav_home) { // Handle the intent code to navigate from one page to another. startActivity( new Intent(Navigation.this, Home.class)); } DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); drawer.closeDrawer(GravityCompat.START); return true; } } 
  5. 數據庫助手

      public class EmployeeHelper extends SQLiteOpenHelper { public static final int DATABASE_VERSION = 3; public static final String DATABASE_NAME = "my_database.db2"; public static final String TABLE_NAME = "Employee"; public static final String KEY_EmpID = "EmpID"; public static final String KEY_EmpCode = "EmpCode"; public static final String KEY_EmpName = "EmpName"; //SQL for creating users table public static final String SQL_TABLE_NAME = " CREATE TABLE " + TABLE_NAME + " ( " + KEY_EmpID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_EmpCode + " TEXT, " + KEY_EmpName + " TEXT" + " ) "; public EmployeeHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_TABLE_NAME); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(" DROP TABLE IF EXISTS " + TABLE_NAME); } public boolean insertData(String EmpID, String EmpCode, String EmpName) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(KEY_EmpID, EmpID); contentValues.put(KEY_EmpCode, EmpCode); contentValues.put(KEY_EmpName, EmpName); long result = db.insert(TABLE_NAME, null, contentValues); // error here // If data is inserted incorrectly it will return -1 if (result == -1) { return false; } else { return true; } } public List<String> getAllCategory() { List<String> AllCategoryList = new ArrayList<String>(); String selectQuery = "SELECT * FROM " + TABLE_NAME; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); /*db = SQLiteDatabase.openDatabase(DATABASE_NAME, Context.MODE_PRIVATE, null); Cursor allrows = db.rawQuery("SELECT * FROM " + TABLE_Categ_NAME, null); System.out.println("COUNT : " + allrows.getCount());*/ if (cursor.moveToFirst()) { do { String EmpID = cursor.getString(0); String EmpCode = cursor.getString(1); String EmpName = cursor.getString(2); AllCategoryList.add(EmpID); AllCategoryList.add(EmpCode); AllCategoryList.add(EmpName); } while (cursor.moveToNext()); } cursor.close(); db.close(); return AllCategoryList; } public Cursor getAllData() { SQLiteDatabase db = this.getReadableDatabase(); String buildSQL = "SELECT * FROM " + TABLE_NAME; Log.d(TAG, "getAllData SQL: " + buildSQL); return db.rawQuery(buildSQL, null); } } 
  6. 員工類

      public class Employee { public static String EmpID; public static String EmpCode; public static String EmpName; public Employee (String EmpID, String EmpCode, String EmpName) { this.EmpID = EmpID; this.EmpCode = EmpCode; this.EmpName = EmpName; } public static String getEmpID() { return EmpID; } public static String getEmpCode() { return EmpCode; } public static String getEmpName() { return EmpName; } public static void setEmpID(String empID) { EmpID = empID; } public static void setEmpCode(String empCode) { EmpCode = empCode; } public static void setEmpName(String empName) { EmpName = empName; } 

    這是它顯示的方式:

    在此輸入圖像描述

像這樣創建一個Global PrefManager類並創建一個三個字段來設置數據

public class PrefManager {
    // Shared preferences file name
    public static final String PREF_NAME = "PACKAGE_NAME" + "_Preferences";




private static final String KEY_EMPID = "Emp_ID";
    private static final String KEY_EMPCODE = "Emp_Code";
    private static final String KEY_EMP_NAME = "Emp_Name";

  SharedPreferences pref;
    // Editor for Shared preferences
    Editor editor;
    // Context
    Context _context;
    // Shared pref mode
    int PRIVATE_MODE = 0;

    public PrefManager(Context context) {
        this._context = context;
        pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = pref.edit();
    }



public String getEmpID() {
        return pref.getString(KEY_EMPID, null);
    }

    public void setEmpID(String token) {
        editor.putString(KEY_EMPID, token);
        editor.commit();
    }

    public String getEmpCode() {
        return pref.getString(KEY_EMPCODE, null);
    }

    public void setEmpCode(String token) {
        editor.putString(KEY_EMPCODE, token);
        editor.commit();
    }

    public String getEmpName() {
        return pref.getString(KEY_EMP_NAME, null);
    }

    public void setEmpName(String token) {
        editor.putString(KEY_EMP_NAME, token);
        editor.commit();
    }
}

登錄活動調用意圖時間設置數據到共享首選項您還可以在注冊時間上保存數據

public class LoginActivity{

PrefManager pref;


  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);
// inilize pref manager class
 pref = new PrefManager(this);

}

 if (currentUser != null) {
                //Snackbar.make(buttonLogin, "Login Successful!", Snackbar.LENGTH_LONG).show();
                //User Logged in successfully Launch You home screen activity

                Intent intent = new Intent (Login.this,Navigation.class);


pref.setEmpID(//passyour employee id);
                startActivity(intent);
                finish();
            } 

在導航上,活動從共享首選項獲取數據並存儲到字符串並設置為抽屜textview

  public class navigationActivity()

***PrefManager pref;***
String EmpId;

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

    ***pref = new PrefManager(this);***
    EmpId = pref.getEmpID;
    }

    // OnnavigationDrawer header

     textView.setText("EmpID:"+EmpId);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM