这是做出来后的demo,放在了GitHub上:https://github.com/DateBro/FeiHuaLing.git
其实作为一个大一的菜鸡,我写这个博客和把demo放到GitHub上都是是为了尝试一下写博客记录自己的思路,和练习使用git。。。
对了,这个GitHub上的demo,因为练习使用git,多了两个branch,不要见怪
【1】问题背景和需求
问题是这样的:老师想让我们模仿因为中国诗词大会火起来的飞花令,做一个可以搜索包含某个字的诗句,也就是飞花令App。
因此希望我们做的App可以输入一个字,然后给出包含这个字的诗句的相关信息。
【2】我的设计
就仿照老师给的上届学长的apk,写一个简单的小程序,能输入一个字后显示出对应的诗句。
第一步先实现可以搜出相关诗句,第二步再实现界面的优化。
拓展功能:在搜出的诗句上点击可以出现全诗。
【1】开发环境
Win10,androidstudio,我自己的android手机,usb线缆。
【1.0】 实现基本的界面布局和文本读取搜索功能,布局使用LinearLayout,在一个基础的背景下加上一个输入查询文字的EditText,点击查询的按钮Button,以及一个显示查询到的诗句的RecyclerView;
完成后的效果图:
【1.1】 将recyclerView中展示诗句的itemView修改成CardView,使搜索出的诗句显示更加直观;
相关代码:
<android.support.v7.widget.CardView android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" android:paddingLeft="8dp" android:paddingRight="8dp" android:paddingTop="8dp" app:cardCornerRadius="10dp" app:cardElevation="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <TextView android:id="@+id/poem_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp" android:textSize="18sp"/> <TextView android:id="@+id/poem_content" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="10dp"/> </LinearLayout> </android.support.v7.widget.CardView>
完成后的效果图:
【1.2】 为每个诗句设置点击监听器,在点击后显示全诗。
相关代码:
@Override public void onClick(View v) { //出现全诗 Intent intent = WholePoemActivity.newIntent(getActivity()); intent.putExtra(WHOLE_POEM_ID, mPoem.getPoemId()); startActivity(intent); }
完成后的效果图:
【1.3】 解决旋转后查询数据消失的bug
代码:
//接下来解决旋转屏幕数据被销毁的bug @Override public void onSaveInstanceState(Bundle savedInstanceState){ super.onSaveInstanceState(savedInstanceState); savedInstanceState.putString(KEY_FINAL_INFO,mFinalInfo); savedInstanceState.putString(KEY_KEYWORD,mSearchWord); }
【1.4】对于文字搜索的处理
这个一开始也不知道怎么弄,借鉴了上届学长的Scanner方法
代码:
private List<Poem> searchPoem(){ List<Poem> poemList = new ArrayList<>(); String keyword = mSearchInput.getText().toString(); String poemId = ""; Poem poem; InputStream is = getResources().openRawResource(R.raw.shi) ; String title = ""; try { int k = 0; Scanner scan = new Scanner(is); while (scan.hasNext()) { String info = scan.nextLine(); //用正则表达式找到诗的题目 if(info.matches("^[0-9].*$")){ title = info.substring(3,info.length()); poemId = info.substring(0,3); } else if (info.contains(keyword)) { k++; poem = new Poem(title, info, poemId); poemList.add(poem); } } Toast.makeText(getActivity(), "一共有" + k + "句!", Toast.LENGTH_SHORT).show(); scan.close(); } catch (Exception e) { e.printStackTrace(); } return poemList; }
【3】总结和下一步的改进计划
这是第一次做Android,总体来说无论是使用的技术方法,还是搭建的UI界面,与同学们都有很大差距。
下一步的改进:
1, 界面的美化处理,无论是按钮,搜索框都有待美化;
2, 在工具栏中使用搜索,通过SQLite数据库添加搜索记录功能;
3, 代码风格不好,下次写好注释;
【4】其他说明
本来是用老婆新垣结衣做背景图的,结果被老师批评“辣手摧花”。。。,所以换了个比较适合的背景图并用ps进行高斯模糊处理,防止背景图挡着文字。