前几天QQ出了个成语接龙红包,基本上搜索成语都是件难事,我最近刚好开发了一款影视app,发现这个成语接龙,并不是特别难,就花半天顺便写了一下,
先看一下图片
大概的思路,就是一个php搜索接口,调用mysql数据而已
安卓端就是,简单的搜索功能加listview,由于发现QQ红包不能通过转发,好像必须经过qq的输入框发送,我就吧点击改为复制成语到剪贴版了
数据库的话:这个可以拿去测试
http://www.booku.cc/APIIDIOM/Search.php?tosearch=yin
demov1.0地址:http://www.shuchuwenku.com/index.php/2019/08/16/qqhongbaochengyujielongfuzhu/
下面是主要代码,不算多,
首先是buil.gradle app引入的
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
compile 'com.getbase:floatingactionbutton:1.10.1'
compile 'com.carson_ho:SearchLayout:1.0.1'
implementation 'com.alibaba:fastjson:1.1.54.android'
compile 'com.android.support:cardview-v7:25.0.1'
implementation files('libs/pinyin4j-2.5.0.jar')
}
需要的jar包看一下目录结构
另外是成语的类
package com.shuchuwenku.idiom;
public class IdiomClass {
private String derivation;
private String example;
private String explanation;
private String pinyin;
private String word;
public String getDerivation() {
return derivation;
}
public void setDerivation(String derivation) {
this.derivation = derivation;
}
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getExplanation() {
return explanation;
}
public void setExplanation(String explanation) {
this.explanation = explanation;
}
public String getPinyin() {
return pinyin;
}
public void setPinyin(String pinyin) {
this.pinyin = pinyin;
}
public void setWord(String word) {
this.word = word;
}
public String getWord() {
return word;
}
public IdiomClass() {
super();
}
public IdiomClass(String word, String pinyin) {
super();
this.word = word;
this.pinyin = pinyin;
}
@Override
public String toString() {
return "Person [pid=" + word + ", pname=" + pinyin + ", page=" + explanation + "]";
}
}
mainActivity
package com.shuchuwenku.idiom;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.Snackbar;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import scut.carson_ho.searchview.bCallBack;
import scut.carson_ho.searchview.ICallBack;
import scut.carson_ho.searchview.SearchView;
public class MainActivity extends AppCompatActivity {
private List Idiomclasslist = new ArrayList();
private SearchView searchView;
public String SEARCH_DATA = null;
private GridView lv_main_list2;//,lv_carrouse;
private idiomAdapter idiomAdapterSHOW;
private Button button_qq;
private ClipboardManager cm;
private ClipData mClipData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
//actionBar.setTitle("CloudPlayer");
//actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.hide();
}
lv_main_list2 = (GridView) findViewById(R.id.lv_main_list2);
// 2. 绑定视图
// setContentView(R.layout.activity_search);
// 3. 绑定组件
searchView = (SearchView) findViewById(R.id.search_view);
// 4. 设置点击键盘上的搜索按键后的操作(通过回调接口)
// 参数 = 搜索框输入的内容
searchView.setOnClickSearch(new ICallBack() {
@Override
public void SearchAciton(String string) {
System.out.println("我收到了" + string);
PinYinUtil upinyin = new PinYinUtil();
if (string.matches("[\u4E00-\u9FA5]+")) {
SEARCH_DATA = upinyin.getPingYin(string);
Message msg = new Message();
msg.what = 7;
Bundle bundle = new Bundle();
bundle.putString("searchstring", SEARCH_DATA); //往Bundle中存放数据
msg.setData(bundle);//mes利用Bundle传递数据
handler.sendMessage(msg);//用activity中的handler发送消息
} else {
SEARCH_DATA = string;
//从服务器获得最新版本 load_version
Message msg = new Message();
msg.what = 7;
Bundle bundle = new Bundle();
bundle.putString("searchstring", string); //往Bundle中存放数据
msg.setData(bundle);//mes利用Bundle传递数据
handler.sendMessage(msg);//用activity中的handler发送消息
}
//Log.d("11111", "onResponse:cityBean " + upinyin.getPingYin(string));
}
});
button_qq = (Button)findViewById(R.id.button_qq);
button_qq.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
joinQQGroup("F_UyUGCZt8cqeXEPIg8UBlS9zszHvRkg");
}
});
}
public boolean joinQQGroup(String key) {
Intent intent = new Intent();
intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D" + key));
// 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 //intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
try {
startActivity(intent);
return true;
} catch (Exception e) {
// 未安装手Q或安装的版本不支持
return false;
}
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case 7:
//获取最新app信息
String searchstring = msg.getData().getString("searchstring");//接受msg传递过来的参数
Idiomclasslist.clear();
searchstring = "http://www.booku.cc/APIIDIOM/Search.php?tosearch=" + searchstring;
Log.d("str9", "str9======" + searchstring);
tosearchdata_json(searchstring);
break;
case 8:
RecommendListData((ArrayList) Idiomclasslist);
break;
}
}
};
private IdiomClass idiomClasslist;
public String tosearchdata_json(String Surl_file) {
OkHttpClient mOkHttpClient = new OkHttpClient();
Request.Builder requestBuilder = new Request.Builder().url(Surl_file);
//可以省略,默认是GET请求
requestBuilder.method("GET", null);
Request request = requestBuilder.build();
Call mcall = mOkHttpClient.newCall(request);
mcall.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.d("1111", "onFailure: ");
}
@Override
public void onResponse(Call call, Response response) throws IOException {
String jsoninfo = response.body().string();
// CityBean cityBean = JSON.parseObject(json, TestBean.class);
// Log.d(TAG, "onResponse:cityBean " + cityBean);
//通过句柄发送json
//[[{"vod_id":"13442","vod_name":"奴隷倶楽部へ売られた女 神宮寺ナオ","vod_class":"有码视频","vod_pic":"https:\/\/img.dadiziyuan.net\/upload\/vod\/2018-12-29\/201812291546066673.jpg","vod_play_url":"在线播放$https:\/\/dadi-bo.com\/share\/d6UbsOhDdXesoJN0$$$在线播放$https:\/\/dadi-bo.com\/20181227\/VAYN7v2L\/index.m3u8"}]]
// String jsonstr1 = jsoninfo.replace("[{", "{");
// String jsonstr2 = jsonstr1.replace("}]", "}");
//String jsonstr3 = jsoninfo.replace("$$$在线播放$", "|");
ByteArrayInputStream stream = new ByteArrayInputStream(jsoninfo.getBytes());
StringBuffer stringBuffer = new StringBuffer();
String str = null;
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
while ((str = br.readLine()) != null) {
stringBuffer.append(str);
}
//03.使用fastJson解析Json、
List pidiomClass = JSON.parseArray(stringBuffer.toString(), IdiomClass.class);
for (IdiomClass pp : pidiomClass) {
idiomClasslist = new IdiomClass();
String word = pp.getWord();
String pinyin = pp.getPinyin();
String explanation = pp.getExplanation();
String example = pp.getExample();
String derivation = pp.getDerivation();
PinYinUtil upinyin = new PinYinUtil();
String jsonstr3[] = upinyin.getPingYin(word).split(" ");
Log.i("test======", "jsonstr3jsonstr3jsonstr3====" + jsonstr3[0]);
idiomClasslist.setPinyin(pinyin);
idiomClasslist.setWord(word);
idiomClasslist.setExplanation(explanation);
idiomClasslist.setExample(example);
idiomClasslist.setDerivation(derivation);
//pfilmclass.setParea(carea);
//将结果添加到对象集合中
// if (SEARCH_DATA.equals(jsonstr3[0])) {
//
// } else {
//
// }
if (SEARCH_DATA.indexOf(jsonstr3[0]) != -1) {
Idiomclasslist.add(idiomClasslist);
} else {
Log.i("test======", "jsonstr3jsonstr3jsonstr3====" + jsonstr3[0]);
Log.i("test======", "SEARCH_DATASEARCH_DATASEARCH_DATA====" + SEARCH_DATA);
}
}
Message msg = new Message();
msg.what = 8;
handler.sendMessage(msg);//用activity中的handler发送消息
}
});
return null;
}
public void RecommendListData(ArrayList filmclassList) {
idiomAdapterSHOW = new idiomAdapter(R.layout.searchvideo_item, this, filmclassList);
lv_main_list2.setAdapter(idiomAdapterSHOW);
lv_main_list2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView> adapterView, View view, int i, long l) {
//跳转提示
// Toast.makeText(MainActivity.this, "Click item" + i, Toast.LENGTH_SHORT).show();
final TextView word = (TextView) view.findViewById(R.id.word);
final TextView pinyin = (TextView) view.findViewById(R.id.pinyin);
final TextView explanation = (TextView) view.findViewById(R.id.explanation);
final TextView example = (TextView) view.findViewById(R.id.example);
final TextView derivation = (TextView) view.findViewById(R.id.derivation);
String word1 = word.getText().toString();
//shareText("成语红包", "答案", word1);
// TODO Auto-generated method stub
//获取剪贴板管理器:
cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
// 创建普通字符型ClipData
mClipData = ClipData.newPlainText("Label", word1);
// 将ClipData内容放到系统剪贴板里。
cm.setPrimaryClip(mClipData);
Toast.makeText(MainActivity.this,"“"+word1+"”"+"复制成功", Toast.LENGTH_SHORT).show();
}
});
}
/**
* 分享文字内容
*
* @param dlgTitle 分享对话框标题
* @param subject 主题
* @param content 分享内容(文字)
*/
private void shareText(String dlgTitle, String subject, String content) {
if (content == null || "".equals(content)) {
return;
}
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
if (subject != null && !"".equals(subject)) {
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
}
intent.putExtra(Intent.EXTRA_TEXT, content);
// 设置弹出框标题
if (dlgTitle != null && !"".equals(dlgTitle)) { // 自定义标题
startActivity(Intent.createChooser(intent, dlgTitle));
} else { // 系统默认标题
startActivity(intent);
}
}
//自己写个适配器类
class idiomAdapter extends BaseAdapter implements ListAdapter {
private LayoutInflater mInflater;
private ArrayList mData = new ArrayList();
private ArrayList Idiomclasslist;
private int id;
private Context context;
private LayoutInflater inflater;
public idiomAdapter(int searchvideo_item, MainActivity videoListActivity, ArrayList Idiomclasslist) {
this.Idiomclasslist = Idiomclasslist;
this.context = videoListActivity;
this.id = searchvideo_item;
inflater = LayoutInflater.from(context);
}
//private ImageView image_url;
@Override
public int getCount() {
return Idiomclasslist.size();
}
@Override
public Object getItem(int i) {
return Idiomclasslist.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@SuppressLint("WrongConstant")
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
TextView word = null;
TextView pinyin = null;
TextView explanation = null;
TextView example = null;
TextView derivation = null;
idiomAdapter.ViewHolder viewHolder;
if (view == null) {
//view = LayoutInflater.from(getContext()).inflate(R.layout.searchvideo_item, viewGroup, false);
view = inflater.inflate(id, null);
//viewHolder = new ViewHolder();
word = (TextView) view.findViewById(R.id.word);
pinyin = (TextView) view.findViewById(R.id.pinyin);
explanation = (TextView) view.findViewById(R.id.explanation);
example = (TextView) view.findViewById(R.id.example);
derivation = (TextView) view.findViewById(R.id.derivation);
// view.setTag(viewHolder); // 将ViewHolder存储在View中
view.setTag(new idiomAdapter.ViewHolder(word, pinyin, explanation, example, derivation));
} else {
// view = view;
idiomAdapter.ViewHolder viewHolder1 = (idiomAdapter.ViewHolder) view.getTag(); // 重新获取ViewHolder
word = viewHolder1.word;
pinyin = viewHolder1.pinyin;
explanation = viewHolder1.explanation;
example = viewHolder1.example;
derivation = viewHolder1.derivation;
}
IdiomClass idiomclass = (IdiomClass) Idiomclasslist.get(i); // 获取当前项的实例
word.setText(idiomclass.getWord().toString());
pinyin.setText(idiomclass.getPinyin().toString());
explanation.setText(idiomclass.getExplanation().toString());
example.setText(idiomclass.getExample().toString());
derivation.setText(idiomclass.getDerivation().toString());
// Imageload.showimagebyasynctask(image_url, filmclass.getPimg());
return view;
}
private final class ViewHolder {
TextView word = null;
TextView pinyin = null;
TextView explanation = null;
TextView example = null;
TextView derivation = null;
public ViewHolder(TextView word, TextView pinyin, TextView explanation, TextView example, TextView derivation) {
this.word = word;
this.pinyin = pinyin;
this.explanation = explanation;
this.example = example;
this.derivation = derivation;
}
}
}
}
拼音的工具类,主要工作是获取输入的第一个文字,转换为拼音,再调用搜索接口
pinyinuitl
package com.shuchuwenku.idiom;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
/**
* 拼音工具类
*
* @author lsf
*/
public class PinYinUtil {
/**
* 将字符串中的中文转化为拼音,其他字符不变
*
* @param inputString
* @return
*/
public static String getPingYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
format.setVCharType(HanyuPinyinVCharType.WITH_V);
char[] input = inputString.trim().toCharArray();
String output = "";
try {
for (int i = 0; i < input.length; i++) {
if (java.lang.Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
output += temp[0]+" ";
} else
output += java.lang.Character.toString(input[i]);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return output;
}
/**
* 获取汉字串拼音首字母,英文字符不变
* @param chinese 汉字串
* @return 汉语拼音首字母
*/
public static String getFirstSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat);
if (temp != null) {
pybf.append(temp[0].charAt(0));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
return pybf.toString().replaceAll("\\W", "").trim();
}
/**
* 获取汉字串拼音,英文字符不变
* @param chinese 汉字串
* @return 汉语拼音
*/
public static String getFullSpell(String chinese) {
StringBuffer pybf = new StringBuffer();
char[] arr = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for (int i = 0; i < arr.length; i++) {
if (arr[i] > 128) {
try {
pybf.append(PinyinHelper.toHanyuPinyinStringArray(arr[i], defaultFormat)[0]);
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
} else {
pybf.append(arr[i]);
}
}
return pybf.toString();
}
}
主页面布局activity_mail.xml
searchvideo_item
最重要的是申请权限