这两天按照学习视频的进度对前面的学习做了一个总结主要是进行了一个小的开发:对于小学生的口算测试的开发;
主要由四个界面运用fragment,运用到的主要是Viewmodel shareprerence 还有Navicontrol等
Main activity代码主要为
在MAIN activity中主要是对跳转界面做了一些限定
package com.eb.calculation; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.NavigationUI; import android.app.DatePickerDialog; import android.content.DialogInterface; import android.os.Bundle; public class MainActivity extends AppCompatActivity { NavController controller; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); controller= Navigation.findNavController(this,R.id.fragment); NavigationUI.setupActionBarWithNavController(this,controller); } @Override public boolean onSupportNavigateUp() { if(controller.getCurrentDestination().getId()==R.id.question) { AlertDialog.Builder builder=new AlertDialog.Builder(this); builder.setTitle(R.string.quit_dialog_title); builder.setPositiveButton(R.string.postive, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { controller.navigateUp(); } }); builder.setNegativeButton(R.string.nav, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog alertDialog=builder.create(); alertDialog.show(); } else { controller.navigate(R.id.title2); } return super.onSupportNavigateUp(); } @Override public void onBackPressed() { onSupportNavigateUp(); } }
本次的 主要功能都在MyView Model中其种
package com.eb.calculation; import android.app.Application; import android.content.Context; import android.content.SharedPreferences; import androidx.annotation.NonNull; import androidx.lifecycle.AndroidViewModel; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.SavedStateHandle; import java.util.Random; @SuppressWarnings("ConstantConditions") public class MyViewModel extends AndroidViewModel { private SavedStateHandle handle; private static String KEY_HIGH_SCORE="key_high_score"; private static String KEY_LEFT_NUMBER="key_left_number"; private static String KEY_RIGHT_NUMBER="key_right_number"; private static String KEY_OPERATOR="key_operator"; private static String KEY_ANSWER="key_answer"; private static String SAVE_SHP_DATA_NAME="save_shp_data_name"; private static String KEY_CURRENT_SCORE="key_current_score"; boolean win_flag =false; public MyViewModel(@NonNull Application application, SavedStateHandle handle) { super(application); if(!handle.contains(KEY_HIGH_SCORE)) { SharedPreferences shp=getApplication().getSharedPreferences(SAVE_SHP_DATA_NAME, Context.MODE_PRIVATE); handle.set(KEY_HIGH_SCORE,shp.getInt(KEY_HIGH_SCORE,0)); handle.set(KEY_LEFT_NUMBER,0); handle.set(KEY_RIGHT_NUMBER,0); handle.set(KEY_OPERATOR,"+"); handle.set(KEY_ANSWER,0); handle.set(KEY_CURRENT_SCORE,0); } this.handle=handle; } public MutableLiveData<Integer>getLeftNumber(){ return handle.getLiveData(KEY_LEFT_NUMBER); } public MutableLiveData<Integer>getRightNumber(){ return handle.getLiveData(KEY_RIGHT_NUMBER); } public MutableLiveData<String>getOperator(){ return handle.getLiveData(KEY_OPERATOR); } public MutableLiveData<Integer>getHightScore() { return handle.getLiveData(KEY_HIGH_SCORE); } public MutableLiveData<Integer>getCurrentScore(){ return handle.getLiveData(KEY_CURRENT_SCORE); } public MutableLiveData<Integer>getAnswer() { return handle.getLiveData(KEY_ANSWER); } public void generator(){ int Level =1000; Random random=new Random(); int x=random.nextInt(Level)+1; int y=random.nextInt(Level)+1; int z=random.nextInt(4)+1; switch(z) { case 1:getOperator().setValue("+"); if(x>y){ getAnswer().setValue(x); getLeftNumber().setValue(y); getRightNumber().setValue(x-y); } else { getAnswer().setValue(y); getLeftNumber().setValue(x); getRightNumber().setValue(y-x); } break; case 2:getOperator().setValue("-"); if(x>y) { getAnswer().setValue(x-y); getLeftNumber().setValue(x); getRightNumber().setValue(y); } else { getAnswer().setValue(y-x); getLeftNumber().setValue(y); getRightNumber().setValue(x); } break; case 3:getOperator().setValue("*"); if(x>y) { while(x%y!=0) { x=random.nextInt(Level)+1; y=random.nextInt(Level)+1; } getAnswer().setValue(x); getLeftNumber().setValue(y); getRightNumber().setValue(x/y); } else{ while(y%x!=0) { x=random.nextInt(Level)+1; y=random.nextInt(Level)+1; } getAnswer().setValue(y); getLeftNumber().setValue(x); getRightNumber().setValue(y/x); } break; case 4:getOperator().setValue("/"); if(x>y) { while(x%y!=0) { x=random.nextInt(Level)+1; y=random.nextInt(Level)+1; } getAnswer().setValue(x/y); getLeftNumber().setValue(x); getRightNumber().setValue(y); } else { while(y%x!=0) { x=random.nextInt(Level)+1; y=random.nextInt(Level)+1; } getAnswer().setValue(y/x); getLeftNumber().setValue(y); getRightNumber().setValue(x); } break; } } public void save(){ SharedPreferences shp=getApplication().getSharedPreferences(SAVE_SHP_DATA_NAME,Context.MODE_PRIVATE); SharedPreferences.Editor editor=shp.edit(); editor.putInt(KEY_HIGH_SCORE,getHightScore().getValue()); editor.apply(); } void answerCorrect(){ getCurrentScore().setValue(getCurrentScore().getValue()+1); if(getCurrentScore().getValue()>getHightScore().getValue()) { getHightScore().setValue(getCurrentScore().getValue()); win_flag=true; } generator(); } }
在title页面中主要是用BUtton进行跳转
public View onCreateView(@NonNull LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) { MyViewModel myViewModel; myViewModel = ViewModelProviders.of(requireActivity(), new SavedStateViewModelFactory(requireActivity().getApplication(),this)).get(MyViewModel.class); FragmentTitleBinding binding; binding= DataBindingUtil.inflate(inflater,R.layout.fragment_title,container,false); binding.setData(myViewModel); binding.setLifecycleOwner(requireActivity()); binding.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { NavController controller= Navigation.findNavController(v); controller.navigate(R.id.action_title2_to_question); } }); return binding.getRoot(); // Inflate the layout for this fragment }
主要的答题界面为question界面对12个界面分为两组一组数字一组为确认键
package com.eb.calculation; import android.net.sip.SipSession; import android.os.Bundle; import androidx.databinding.DataBindingUtil; import androidx.fragment.app.Fragment; import androidx.lifecycle.SavedStateViewModelFactory; import androidx.lifecycle.ViewModelProvider; import androidx.lifecycle.ViewModelProviders; import androidx.navigation.NavController; import androidx.navigation.Navigation; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import com.eb.calculation.databinding.FragmentQuestionBinding; import com.eb.calculation.databinding.FragmentTitleBinding; /** * A simple {@link Fragment} subclass. */ public class question extends Fragment { public question() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final MyViewModel myViewModel; myViewModel = new ViewModelProvider(requireActivity()).get(MyViewModel.class); // final FragmentTitleBinding binding1; //原来 final FragmentQuestionBinding binding1; myViewModel.generator(); binding1= DataBindingUtil.inflate(inflater,R.layout.fragment_question,container,false); binding1.setData(myViewModel); binding1.setLifecycleOwner(requireActivity()); final StringBuilder builder=new StringBuilder(); View.OnClickListener listener=new View.OnClickListener() { @Override public void onClick(View v) { switch (v.getId()) { case R.id.button0:builder.append("0");break; case R.id.button1:builder.append("1");break; case R.id.button2:builder.append("2");break; case R.id.button3:builder.append("3");break; case R.id.button4:builder.append("4");break; case R.id.button5:builder.append("5");break; case R.id.button6:builder.append("6");break; case R.id.button7:builder.append("7");break; case R.id.button8:builder.append("8");break; case R.id.button9:builder.append("9");break; case R.id.buttonclear:builder.setLength(0);break; } if(builder.length()==0) { binding1.textView9.setText(getString(R.string.input_indicator)); } else { binding1.textView9.setText(builder.toString()); } } }; binding1.button0.setOnClickListener(listener); binding1.button1.setOnClickListener(listener); binding1.button2.setOnClickListener(listener); binding1.button3.setOnClickListener(listener); binding1.button4.setOnClickListener(listener); binding1.button5.setOnClickListener(listener); binding1.button6.setOnClickListener(listener); binding1.button7.setOnClickListener(listener); binding1.button8.setOnClickListener(listener); binding1.button9.setOnClickListener(listener); binding1.buttonclear.setOnClickListener(listener); binding1.buttonsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(Integer.valueOf(builder.toString()).equals(myViewModel.getAnswer().getValue())) { myViewModel.answerCorrect(); builder.setLength(0); binding1.textView9.setText(R.string.answer_correct_message); }else { NavController controller= Navigation.findNavController(v); if(myViewModel.win_flag) { controller.navigate(R.id.action_question_to_win); myViewModel.win_flag=false; myViewModel.save(); } else { controller.navigate(R.id.action_question_to_lose); } } } }); return binding1.getRoot() ; } }
所有变量的名称
<resources> <string name="app_name">Calculation</string> <!-- TODO: Remove or change this placeholder text --> <string name="hello_blank_fragment" translatable="false">Hello blank fragment</string> <string name="title_messsage">Calculation Test</string> <string name="title_image_info" translatable="false">title image</string> <string name="title_button_message">Enter</string> <string name="high_score">High Score:%d</string> <string name="equal_symbol" translatable="false">=</string> <string name="question_mark" translatable="false">?</string> <string name="current_score">Score:%d</string> <string name="input_indicator">Your Answer:</string> <string name="lose_image_message" translatable="false">lose_image</string> <string name="win_image_message" translatable="false">win_image</string> <string name="lose_message">You lose!</string> <string name="win_message">You win!</string> <string name="lose_score_message">Your Score:%d</string> <string name="win_score_message">New Record:%d</string> <string name="button_back_to_title">Back</string> <string name="answer_correct_message">Correct!Go On!</string> <string name="quit_dialog_title">Are you sure to quit</string> <string name="postive">OK</string> <string name="nav">Cancel</string> <string name="title_nav_message">Welcome</string> <string name="question_nav_message">Testing</string> <string name="win_nav_message">Win</string> <string name="lose_nav_message">Lose</string> </resources>
运行结果
当成功答题数大于最高得分时则会跳转到
所答题数没有超过时则跳跃到