這是做出來後的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進行高斯模糊處理,防止背景圖擋着文字。