最后完成了一这个小程序
还有主程序的代码
package com.eb.writeaccount; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.NavigationUI; import android.content.Context; import android.os.Bundle; import android.view.inputmethod.InputMethodManager; public class MainActivity extends AppCompatActivity { private NavController navController; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); navController = Navigation.findNavController(findViewById(R.id.fragment)); NavigationUI.setupActionBarWithNavController(this,navController); } @Override public boolean onSupportNavigateUp() { InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(findViewById(R.id.fragment).getWindowToken(),0); navController.navigateUp(); return super.onSupportNavigateUp(); } }
和MyViewModel的代码
package com.eb.writeaccount; import android.app.Application; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.LiveData; import java.util.List; public class MyViewModel extends AndroidViewModel { private writeRepostry writeRepostry; public MyViewModel(@NonNull Application application) { super(application); writeRepostry = new writeRepostry(application); } LiveData<List<Word>> getAllWordsLive() { return writeRepostry.getAllWordsLive(); } LiveData<List<Word>> findWordsWithPattern(String patten) { return writeRepostry.findWordsWithPattern(patten); } void insertWords(Word... words) { writeRepostry.insertWords(words); } void updateWords(Word... words) { writeRepostry.updateWords(words); } void deleteWords(Word... words) { writeRepostry.deleteWords(words); } void deleteAllWords() { writeRepostry.deleteAllWords(); } }