新闻Webview

权限

<!--允许程序打开网络套接字-->
<uses-permission android:name="android.permission.INTERNET" />
<!--允许程序设置内置sd卡的写权限-->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--允许程序获取网络状态-->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!--允许程序访问WiFi网络信息-->
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
android:name=".MyApp"

依赖

compile 'com.android.support:recyclerview-v7:26.0.0'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'com.squareup.okhttp3:okhttp:3.9.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.9.0'
compile 'com.google.code.gson:gson:2.8.2'
compile 'org.greenrobot:eventbus:3.1.1'
compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

Api

public class Api {
    public static String Base_Url = "http://api.tianapi.com/startup/?key=71e58b5b2f930eaf1f937407acde08fe&num=10";
}

Baselview

public interface BaseIview {
    Context context();
}

BasePresenter

public class BasePresenter<V extends BaseIview> {
    //    声明V
    private V view;

    public BasePresenter(V view) {
        this.view = view;
    }

    public void onDestory(){
        view = null;
    }
    public Context getContext(){
//        如果有环境变量直接拿来用
        if(view != null & view.context()!=null){
            return view.context();
        }
        return MyApp.getContext();
    }

}

IView

public interface IView  extends BaseIview {
    public void onSuccessV(ShowBean jsonBean);
}

MyApp

public class MyApp extends Application {
    private  static MyApp myApp;


    @Override
    public void onCreate() {
        super.onCreate();
        myApp = this;
        File files = new File("/sdcard/Rimg");
        initImageLoader(getApplicationContext(),files);
    }
    public static void initImageLoader(Context context, File file) {
        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);


        config .diskCache(new UnlimitedDiskCache(file));//UnlimitedDiskCache 限制这个图片的缓存路径
        ImageLoader.getInstance().init(config.build());
    }


    public static Context getContext() {
        return myApp;
    }

}


MyShowBeanAdapter
public class MyShowBeanAdapter extends RecyclerView.Adapter<MyShowBeanAdapter.MyViewHolder>{

    private Context context;
    List<ShowBean.NewslistBean> newslist;
    public MyShowBeanAdapter(Context context, List<ShowBean.NewslistBean> newslist) {
        this.context = context;
        this.newslist = newslist;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.rv_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);
        return holder;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        ShowBean.NewslistBean newslistBean = newslist.get(position);
        String picUrl = newslistBean.getPicUrl();
        String title = newslistBean.getTitle();
        String description = newslistBean.getDescription();
        String ctime = newslistBean.getCtime();
//        holder.item_img
        holder.item_tv1.setText(title);
        holder.item_tv2.setText(description);
        holder.item_tv3.setText(ctime);
        ImageLoader.getInstance().displayImage(picUrl,holder.item_img);

//        点击后跳转到图四界面并使用WebView显示页面内容。
        if(onItemClickListener != null){
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onItemClickListener.onClick(position);
                }
            });
            holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    onItemClickListener.onClick(position);
                    return false;
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return newslist.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder{

        private final ImageView item_img;
        private final TextView item_tv1;
        private final TextView item_tv2;
        private final TextView item_tv3;

        public MyViewHolder(View itemView) {
            super(itemView);
            item_img = itemView.findViewById(R.id.item_img);
            item_tv1 = itemView.findViewById(R.id.item_tv1);
            item_tv2 = itemView.findViewById(R.id.item_tv2);
            item_tv3 = itemView.findViewById(R.id.item_tv3);
        }
    }
    //      定义点击事件的接口
    public interface onItemClickListener{
        void onClick( int position);
        void onLongClick( int position);
    }
    private onItemClickListener onItemClickListener;
    //      提供对外的回调方法
    public void setOnItemClickListener(onItemClickListener onItemClickListener ){
        this. onItemClickListener=onItemClickListener;
    }

}

OkHttpUtil
public class OkHttpUtil {
    private Handler handler = new Handler();
    private  static OkHttpUtil okHttpUtil;
    private setOkLoadListener okLoadListener;

    //  单例模式
    public static OkHttpUtil getInstance(){
        if(okHttpUtil == null){
            okHttpUtil = new OkHttpUtil();
        }
        return  okHttpUtil;
    }

    //      GET
    public void doGet(String url){
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(new MyInterceptor()).build();
        final Request request = new Request.Builder().url(url).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = handler.obtainMessage();
                message.what = 0;
                message.obj = e.getMessage();
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = handler.obtainMessage();
                message.what = 1;
                message.obj = response.body().string();
                handler.sendMessage(message);
            }
        });
    }
    //    POST
    public void okPost(String url, Map<String,String> map){
        OkHttpClient build = new OkHttpClient.Builder().addInterceptor(new MyInterceptor()).build();
//        创建FormBody
        FormBody.Builder builder = new FormBody.Builder();
//        遍历map
        Set<String> keySet = map.keySet();
        for (String key:keySet) {
            String value = map.get(key);
            builder.add(key,value+"");
        }
//         build
        FormBody body = builder.build();
        Request request = new Request.Builder().url(url).post(body).build();
        Call call = build.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Message message = handler.obtainMessage();
                message.what = 0;
                message.obj = e.getMessage();
                handler.sendMessage(message);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message message = handler.obtainMessage();
                message.what = 1;
                message.obj = response.body().string();
                handler.sendMessage(message);
            }
        });

    }




    private class MyInterceptor implements Interceptor {
        public static final String TAG = "MyInterceptor";

        @Override
        public Response intercept(Chain chain) throws IOException {
            //            获取原来的body
            Request request = chain.request();
            RequestBody body = request.body();
            if (body instanceof FormBody) {
//                便利原来的所有参数,加到新的body里面,最后将公告参数加到新的body
                FormBody.Builder builder = new FormBody.Builder();
                for (int i = 0; i < ((FormBody) body).size(); i++) {
                    String name = ((FormBody) body).name(i);
                    String value = ((FormBody) body).value(i);
//                    放入新的
                    builder.add(name, value);
                }
//                再将公共参数添加进去
                builder.add("source", "android");
                FormBody formBody = builder.build();
//                创建新的请求
                Request newRequest = request.newBuilder().post(formBody).build();
                Response response = chain.proceed(newRequest);
                return response;
            }
            return null;
        }
    }
    class MyHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
//                    失败
                    Exception e = (Exception) msg.obj;
                    okLoadListener.okLoadError(e);
                    break;
                case 1:
//                    成功
                    String json =  (String)msg.obj;
                    okLoadListener.okLoadDuccess(json);
                    break;

            }
        }
    }
    //    提供给外部调用的接口
    public abstract interface setOkLoadListener {
        public void okLoadDuccess(String json);
        public void okLoadError(Exception e);
    }
}
ShowBean
public class ShowBean {

    /**
     * code : 200
     * msg : success
     * newslist : [{"ctime":"2017-06-06 16:00","title":"模式思考:为什么星巴克成了印钞机?","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0606/2017060614515724.jpg","url":"http://www.chinaz.com/start/2017/0606/720004.shtml"},{"ctime":"2017-06-06 16:00","title":"佛学文化社群平台,\u201c般若\u201d要连接寺庙、僧人、善信","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0606/6363235766401474079822974.jpeg","url":"http://www.chinaz.com/start/2017/0606/720017.shtml"},{"ctime":"2017-06-06 16:00","title":"短视频不再是东北人的天下 \u201c川军\u201d已崛起","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0606/6363235842103727035736068.png","url":"http://www.chinaz.com/start/2017/0606/720028.shtml"},{"ctime":"2017-06-06 11:00","title":"中国文青创业者的最大金主:远离风口,专注慢公司","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0606/2017060610250221.jpg","url":"http://www.chinaz.com/start/2017/0606/719534.shtml"},{"ctime":"2017-06-06 10:00","title":"给程序员当经纪人,程序员客栈完成300万元天使轮融资","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0606/201706060900398654.jpg","url":"http://www.chinaz.com/start/2017/0606/719406.shtml"},{"ctime":"2017-06-06 10:00","title":"经历多次押宝失败的TOM网,可能要因政策原因而彻底断了挣扎","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0606/6363233672258475907689785.jpeg","url":"http://www.chinaz.com/start/2017/0606/719411.shtml"},{"ctime":"2017-06-05 17:00","title":"网易蜗牛读书:突破付费模式 敲碎纸电隔阂","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0605/201706051550205463.jpg","url":"http://www.chinaz.com/start/2017/0605/718537.shtml"},{"ctime":"2017-06-05 17:00","title":"五年之后,网易新闻为什么彻底放弃了\u201c有态度\u201d?","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0605/201706051600289006.jpg","url":"http://www.chinaz.com/start/2017/0605/718557.shtml"},{"ctime":"2017-06-05 17:00","title":"一年赚了知性女青年7000万元,它却是行业不擅长挣钱的公司","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0605/201706051619455958.jpg","url":"http://www.chinaz.com/start/2017/0605/718595.shtml"},{"ctime":"2017-06-05 15:00","title":"从兴起到洗牌仅用一年!谁让这场全民狂欢戛然而止?","description":"创业新闻","picUrl":"http://pic.chinaz.com/thumb/2017/0605/6363226806028247287344888.jpg","url":"http://www.chinaz.com/start/2017/0605/718364.shtml"}]
     */

    private int code;
    private String msg;
    private List<NewslistBean> newslist;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public List<NewslistBean> getNewslist() {
        return newslist;
    }

    public void setNewslist(List<NewslistBean> newslist) {
        this.newslist = newslist;
    }

    public static class NewslistBean {
        /**
         * ctime : 2017-06-06 16:00
         * title : 模式思考:为什么星巴克成了印钞机?
         * description : 创业新闻
         * picUrl : http://pic.chinaz.com/thumb/2017/0606/2017060614515724.jpg
         * url : http://www.chinaz.com/start/2017/0606/720004.shtml
         */

        private String ctime;
        private String title;
        private String description;
        private String picUrl;
        private String url;

        public String getCtime() {
            return ctime;
        }

        public void setCtime(String ctime) {
            this.ctime = ctime;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getDescription() {
            return description;
        }

        public void setDescription(String description) {
            this.description = description;
        }

        public String getPicUrl() {
            return picUrl;
        }

        public void setPicUrl(String picUrl) {
            this.picUrl = picUrl;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }
    }
}
ShowModel
public class ShowModel {
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                ShowBean showBean = (ShowBean) msg.obj;
                callBack.onSuccessM(showBean);
            }

        }
    };


//    定义一个接口回调

    public interface CallBack{
        public void onSuccessM(ShowBean showBean );
    }

    //  声明接口
    private  CallBack callBack;

    //    提供一个对外响应数据的方法
    public void setCallBack(CallBack callBack){
        this.callBack = callBack;
    }

    //  提供一个获取数据的方法
    public void getShowModel(String url){
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(okhttp3.Call call, IOException e) {

            }

            @Override
            public void onResponse(okhttp3.Call call, Response response) throws IOException {
                if(response.isSuccessful()){
                    String jsonStr = response.body().string();
                    Gson gson = new Gson();
                    ShowBean showBean = gson.fromJson(jsonStr, ShowBean.class);
                    Message message = new Message();
                    message.obj = showBean;
                    message.what = 0;
                    handler .sendMessage(message);
                }
            }


        });


    }

}
ShowPresenter
public class ShowPresenter {
    private ShowModel showModel ;
    private IView iView;

    public ShowPresenter(IView iView) {
        this.iView = iView;
        showModel = new ShowModel();
    }
    public void getShowPresenter(String url) {
        showModel.getShowModel(url);
        showModel.setCallBack(new ShowModel.CallBack() {
            @Override
            public void onSuccessM(ShowBean showBean) {
                if (iView != null) {
                    iView.onSuccessV(showBean);
                }
            }
        });
    }
    public void detachView() {
        if (iView != null) {
            iView = null;
        }
    }

}
MainActivty
public class MainActivity extends AppCompatActivity implements IView {

    private RecyclerView mRv;
    private MyShowBeanAdapter adapter;
    private ShowPresenter presenter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
//      抽取个获取数据的方法
        initData();
//      给rv设置manager
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRv.setLayoutManager(manager);



    }
    //      获取数据并适配器展示
    private void initData() {
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder().url(Api.Base_Url).build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String json = response.body().string();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        ShowBean jsonBean = gson.fromJson(json, ShowBean.class);
                        final List<ShowBean.NewslistBean> newslist = jsonBean.getNewslist();
                        adapter = new MyShowBeanAdapter(MainActivity.this, newslist);
                        mRv.setAdapter(adapter);

//      点击后跳转到图四界面并使用WebView显示页面内容

                        adapter.setOnItemClickListener(new MyShowBeanAdapter.onItemClickListener() {
                            @Override
                            public void onClick(int position) {
                                Intent intent = new Intent(MainActivity.this, WebViewActivity.class);
//                                Bundle bundle = new Bundle();
//                                bundle.putString("url",newslist.get(position).getUrl());
                                String url = newslist.get(position).getUrl();
                                Log.i("tag",url);
                                intent.putExtra("url",url);
                                startActivity(intent);
//                                setResult(RESULT_OK,intent);
//                                finish();
                            }

                            @Override
                            public void onLongClick(int position) {
                                Toast.makeText(MainActivity.this, "您长按了第"+position+"行", Toast.LENGTH_SHORT).show();
                            }
                        });

                    }
                });
            }
        });
    }


    private void initView() {
        mRv = (RecyclerView) findViewById(R.id.rv);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if (presenter != null) {
            presenter.detachView();
        }
    }

    @Override
    public Context context() {
        return this;
    }

    @Override
    public void onSuccessV(ShowBean jsonBean) {

    }
}
mainxml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bwie.myapplication.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </android.support.v7.widget.RecyclerView>


</LinearLayout>

WebViewActivity
public class WebViewActivity extends AppCompatActivity {

    private WebView mWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);
        initView();
        WebSettings settings = mWeb.getSettings();
        settings.setDefaultTextEncodingName("utf-8");
//        允许JS的代码操作
        settings.setJavaScriptEnabled(true);
//        不是用系统浏览器打开网页
        mWeb.setWebViewClient(new WebViewClient(){

        });
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");
        Log.i("tag_web",url);
        mWeb.loadUrl(url+"");


//          允许JS弹框在安卓APP中
      /*  mWeb.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Log.i("tag","onProgressChanged"+newProgress);
                super.onProgressChanged(view, newProgress);
                Intent intent = getIntent();
                String url = intent.getStringExtra("url");
                Log.i("tagaaa",url);
                mWeb.loadUrl(url+"");

            }
        });*/

    }

    private void initView() {
        mWeb = (WebView) findViewById(R.id.web);
    }
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.bwie.myapplication.WebViewActivity">

    <WebView
        android:id="@+id/web"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </WebView>
</LinearLayout>
rv_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/item_img"
        android:layout_width="150dp"
        android:layout_height="120dp" />
    <LinearLayout
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="120dp"
        android:orientation="vertical">
        <TextView
            android:id="@+id/item_tv1"
            android:textSize="24dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="111111"/>
        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginLeft="10dp">
            <TextView
                android:id="@+id/item_tv2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:textColor="@color/colorPrimaryDark"
                android:text="111111"
                android:layout_marginTop="10dp"/>
            <TextView
                android:id="@+id/item_tv3"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="20dp"
                android:text="111111"
                android:layout_marginTop="10dp"
                android:layout_marginLeft="15dp"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>





猜你喜欢

转载自blog.csdn.net/ai123456852/article/details/80170512
今日推荐