android:layout_height="wrap_content"
android:id="@+id/hsv">
android:layout_height="40dp"
android:orientation="horizontal"
android:id="@+id/lin_menu">
android:layout_height="match_parent"
android:id="@+id/vp"
android:layout_below="@id/hsv">
private HorizontalScrollView hsv;
private LinearLayout linMenu;
private ViewPager viewPager;
//存放菜单TextView组件
private List
private List
private List
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hsv = findViewById(R.id.hsv);
linMenu = findViewById(R.id.lin_menu);
viewPager = findViewById(R.id.vp);
//初使化数据
initData();
//初使化横向滑动菜单
initMenu();
//设置viewpager的适配器
MyPagerAdapter adapter=new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
viewPager.setOffscreenPageLimit(menuText.size());
}
/**
* 设置横向滑动菜单 滚动到 指定的菜单 项
* @param index
*/
private void setScrollMenu(int index){
//得到组件
TextView tvMenu=menuLists.get(index);
float tx = tvMenu.getX();//得到x坐标
//scrollTo(x,y):滚动 y-代表垂直方向的滚动 x-代表水平方向的滚动
hsv.scrollTo((int)tx,0);
}
private void initData() {
menuText.add("头条");
menuText.add("社会");
menuText.add("国内");
menuText.add("国际");
menuText.add("娱乐");
menuText.add("体育");
menuText.add("军事");
menuText.add("科技");
menuText.add("财经");
menuText.add("时尚");
tabsType.add("top");
tabsType.add("shehui");
tabsType.add("guonei");
tabsType.add("guoji");
tabsType.add("yule");
tabsType.add("tiyu");
tabsType.add("junshi");
tabsType.add("keji");
tabsType.add("caijing");
tabsType.add("shishang");
}
private void initMenu() {
//将TextView组件 添加到 linMenu 组件中
for (int i = 0; i < menuText.size(); i++) {
//创建菜单 TextView
TextView textView = new TextView(this);
textView.setText(menuText.get(i));
if (i == 0) {
textView.setTextColor(Color.RED);//设置字体颜色是红色
} else {
textView.setTextColor(Color.BLACK);//设置字体颜色是黑色
}
//设置标签,用来记录它是第几个菜单
textView.setTag(i);
//添加点击事件
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//viewpager切换到不同的页面
viewPager.setCurrentItem(Integer.parseInt(view.getTag() + ""));
//设置颜色
setSelectedMenu(Integer.parseInt(view.getTag() + ""));
}
});
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 5, 8, 0);//设置菜单之间的间隔
//进行添加 addView
linMenu.addView(textView, params);
//添加到集合中
menuLists.add(textView);
}
}
/**
* 将所有的菜单遍历一遍,设置选中的菜单字体颜色为红色,其余是黑色
* @param menuIndex
*/
private void setSelectedMenu(int menuIndex){//menuIndex:当前选中菜单的下标
for(int i=0;i
menuLists.get(i).setTextColor(Color.RED);//选中的颜色
}else {
menuLists.get(i).setTextColor(Color.BLACK);
}
}
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
//用来返回每个页面
@Override
public Fragment getItem(int position) {//position:页面的下标
RecommendFr fr=new RecommendFr();
Bundle bundle=new Bundle();
bundle.putString("tt",tabsType.get(position));
fr.setArguments(bundle);
Toast.makeText(MainActivity.this,tabsType.get(position)+"--"+position,Toast.LENGTH_SHORT).show();
return fr;
}
//返回页面的数量
@Override
public int getCount() {
return menuText.size();
}
}
}
MyTask
public class MyTask extends AsyncTask
//2.声明接口变量
private ICallBacks iCallBacks;
//3.定义带参构造方法
public MyTask(ICallBacks iCallBacks) {
this.iCallBacks = iCallBacks;
}
@Override
protected String doInBackground(String... strings) {
String str="";
try {
URL url = new URL(strings[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
int responseCode = urlConnection.getResponseCode();
if (responseCode==200){
InputStream inputStream = urlConnection.getInputStream();
str=toJson(inputStream);
}
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//4.调用接口的方法
iCallBacks.getJsonData(s);
}
//1.定义一个内部接口
public interface ICallBacks{
//得到json串
void getJsonData(String jsonstr);
}
private String toJson(InputStream inputStream) {
StringBuilder builder = new StringBuilder();
String string;
InputStreamReader in = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(in);
try {
while ((string=reader.readLine())!=null){
builder.append(string);
}
} catch (Exception e) {
e.printStackTrace();
}
return builder.toString();
}
}
public class RecommendFr extends Fragment {
private String url="";
private ListView listView;
private MyLvAdapter adapter;
private Handler myHandler=new Handler(){
@Override
public void handleMessage(Message msg) {
//设置适配器,进行显示
List
//设置适配器
MyLvAdapter adapter=new MyLvAdapter(getActivity(),data);
listView.setAdapter(adapter);
}
};
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.recomend,container,false);
listView = v.findViewById(R.id.lv);
//接收参数并拼接字符串
Bundle arguments = getArguments();
String str=arguments.getString("tt");
// Toast.makeText(getActivity(),str,Toast.LENGTH_SHORT).show();
url="http://v.juhe.cn/toutiao/index?type="+str+"&key=dbedecbcd1899c9785b95cc2d17131c5";
return v;
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//请求数据
requestNetData();
}
private void requestNetData() {
if(NetStateUtil.isConn(getActivity())){
//进行网络请求
new Thread(){
@Override
public void run() {
getData();
}
}.start();
}else {
NetStateUtil.showNoNetWorkDlg(getActivity());
}
}
private void getData() {
try {
URL url=new URL("http://api.iclient.ifeng.com/ClientNews?id=YL53,FOCUSYL53&action=default&pullNum=1&uid=864678036850608&devid=864678036850608&proid=ifengnews&vt=5&publishid=6103&screen=1080x1920&df=androidphone&os=android_22&nw=wifi");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
int code=urlConnection.getResponseCode();
if(code==200){
//获取数据
InputStream inputStream = urlConnection.getInputStream();
String jsonData=inputstreamToString(inputStream);
//进行解析
Gson gson=new Gson();
ResultData rdata=gson.fromJson(jsonData, ResultData.class);
//给主线程发送消息
Message msg=Message.obtain();
msg.obj=rdata.getResult().getData();
myHandler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public String inputstreamToString(InputStream stream){
StringBuilder builder=new StringBuilder();
try {
BufferedReader reader=new BufferedReader(new InputStreamReader(stream));
String str;
while ((str=reader.readLine())!=null){
builder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
}
}
判断网络
/*
* 判断网络连接是否已开
* true 已打开 false 未打开
* */
public static boolean isConn(Context context){
boolean bisConnFlag=false;
ConnectivityManager conManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = conManager.getActiveNetworkInfo();
if(network!=null){
bisConnFlag=conManager.getActiveNetworkInfo().isAvailable();
}
return bisConnFlag;
}
/**
* 当判断当前手机没有网络时选择是否打开网络设置
* @param context
*/
public static void showNoNetWorkDlg(final Context context) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setIcon(R.mipmap.ic_launcher) //
.setTitle(R.string.app_name) //
.setMessage("当前无网络").setPositiveButton("设置", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 跳转到系统的网络设置界面
Intent intent = null;
// 先判断当前系统版本
if(android.os.Build.VERSION.SDK_INT > 10){ // 3.0以上
intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
}else{
intent = new Intent();
intent.setClassName("com.android.settings", "com.android.settings.WirelessSettings");
}
context.startActivity(intent);
}
}).setNegativeButton("知道了", null).show();
}
}