利用 Fragment ,JSON,第三方开源框架实现 仿新闻界面

来源:互联网 发布:python新手入门 编辑:程序博客网 时间:2024/05/14 03:52

从网上加载 JSON 数据,解析并显示出来,本文是根据前文《JSON,ListView AsyncHttpClient 等第三方包的综合实应用》http://blog.csdn.net/antimage08/article/details/50471114 扩展应用而来;效果如下(只展示了部分效果,其余内容可在前文见到):




效果图中:左侧的按钮效果参见前文的《RippleDrawable 的简单使用》http://blog.csdn.net/antimage08/article/details/50390546

点击图片新闻后得到的效果参见前文的《简单的完全自定义视图(同心圆)》http://blog.csdn.net/antimage08/article/details/50103433

所用的开源包如下:


这次增加了新的开源库 slidingmenu_library-release.aar 其导入的方法如前文。(所用开源库均有修改,从 XML 文件中就可以看出,精简部分的开源包可以到我的百度云:http://pan.baidu.com/s/1gdLtZXL 下载(但不提供更新),文章中所用素材也在百度云盘中:http://pan.baidu.com/s/1gdYlpcf   文中和以前文章中都有注解)

其中开源包在 github 上的链接如下:

SlidingMenu :https://github.com/jfeinstein10/SlidingMenu

imageSlider :https://github.com/daimajia/AndroidImageSlider 

httpclient     :https://github.com/apache/httpclient  

AsyncHttpClient :https://github.com/scruffyfox/AsyncHttpClient   

XListView   : https://github.com/Maxwin-z/XListView-Android




先将《JSON,ListView AsyncHttpClient 等第三方包的综合实应用》中 MainActivity.java 中的代码转移到 MainFragment.java 中:

package com.scxh.listlayout;import android.app.Activity;import android.app.Fragment;import android.os.AsyncTask;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.ImageView;import android.widget.ProgressBar;import android.widget.Toast;import com.google.gson.Gson;import com.loopj.android.http.AsyncHttpClient;import com.loopj.android.http.TextHttpResponseHandler;import com.scxh.listlayout.parsejson.InfoT;import com.scxh.listlayout.parsejson.MerchantKeyT;import com.scxh.listlayout.parsejson.TotalT;import com.scxh.slider.library.SliderLayout;import com.scxh.slider.library.SliderTypes.TextSliderView;import com.warmtel.android.xlistview.XListView;import java.text.SimpleDateFormat;import java.util.HashMap;import java.util.List;import cz.msebera.android.httpclient.Header;public class MainFragment extends Fragment {    private String url = "http://192.168.1.160/json/around";    private XListView listView;    private MyAdapter adapter;    private AsyncHttpClient asyncHttpClient = new AsyncHttpClient();    private ProgressBar progressBar;    private SliderLayout sliderLayout;    private ImageView titleImageView;    private addOrBack listener;    // 定义接口,实现和 LeftActivity 的交互    public interface addOrBack{        public void toAddToBack();    }    public static MainFragment newInstance() {        MainFragment fragment = new MainFragment();        return fragment;    }    // 当该 MainFragment 被添加,显示到 LeftActivity 时,回调该方法    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        if (activity instanceof addOrBack) {            listener = (addOrBack) activity;        } else {            throw new RuntimeException(activity.toString()                    + " must implement OnMerchantFragmentInteractionListener");        }    }    // 当该 MainFragment 从它所属的 LeftActivity 中被删除时,回调该方法    @Override    public void onDetach() {        super.onDetach();        // 将 listener 复为 null        listener = null;    }    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        listView = (XListView)getView().findViewById(R.id.listView);        progressBar = (ProgressBar)getView().findViewById(R.id.progressbar);        titleImageView = (ImageView)getView().findViewById(R.id.title_imageview);        titleImageView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // 激发 listener 的 OnClickListener 方法                listener.toAddToBack();            }        });        initListHeader();        // 使用异步下载网络资源        // 使用第三方的开源框架下载资源        getAsyncDataList();        // XListView 的点击事件        clickForXListView();        adapter = new MyAdapter(getActivity());        listView.setAdapter(adapter);        listView.setEmptyView(progressBar);    }    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.for_mainfragment, container, false);    }    /**     *  ListView 分为 3 部分: 头部 ListHeader, 内容部分(我们常用的部分) ContentView,底部 FooterView     *  其中:头部,底部一般不可见     */    private void initListHeader() {        View sliderHeaderView = LayoutInflater.from(getActivity()).inflate(R.layout.silderl_layout,null);        sliderLayout = (SliderLayout) sliderHeaderView.findViewById(R.id.slider_imager);        listView.addHeaderView(sliderHeaderView);        HashMap<String,String> sliderList = getData();        for(String key : sliderList.keySet()){            String url = sliderList.get(key);            TextSliderView textSliderView = new TextSliderView(getActivity());            textSliderView.description(key);            textSliderView.image(url);            textSliderView.setScaleType(TextSliderView.ScaleType.CenterCrop);            sliderLayout.addSlider(textSliderView);        }        sliderLayout.setPresetIndicator(SliderLayout.PresetIndicators.Right_Bottom);    }    /**     *  XListView 的点击事件     */    private void clickForXListView(){        // 默认是 false,这里改为 true        listView.setPullLoadEnable(true);        listView.setXListViewListener(new XListView.IXListViewListener() {            @Override            public void onRefresh() {                // 此处模拟加载的状态                forLittleTime();            }            @Override            public void onLoadMore() {                // 此处模拟加载的状态                forLittleTime();            }        });    }    /**     *  模网络的加载工作,(睡眠)     */    private void forLittleTime(){        new AsyncTask<Void, Void, Void>() {            @Override            protected Void doInBackground(Void... params) {                try {                    Thread.sleep(3000);                } catch (InterruptedException e) {                    e.printStackTrace();                }                return null;            }            @Override            protected void onPostExecute(Void aVoid) {                super.onPostExecute(aVoid);                getAsyncDataList();            }        }.execute();    }    /**     *  利用第三方开源包下载     */    public void getAsyncDataList() {        asyncHttpClient.get(url, new TextHttpResponseHandler() {            @Override            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {                Toast.makeText(getActivity(), "加载失败", Toast.LENGTH_SHORT).show();            }            @Override            public void onSuccess(int i, Header[] headers, String s) {                forGson(s);                Toast.makeText(getActivity(), "加载成功", Toast.LENGTH_SHORT).show();                listView.setRefreshTime(                        new SimpleDateFormat("HH:mm:ss").format(System.currentTimeMillis()));                // 下载成功之后停止刷新(减少内存消耗)                listView.stopRefresh();                // 下载成功后停止下载(减少内存消耗)                listView.stopLoadMore();                //           swipeRefreshLayout..setRefreshing(false);   // 停止刷新            }        });    }    /* ListView 的头部加载数据来源 */    private HashMap<String,String> getData(){        HashMap<String,String> http_url_maps = new HashMap<String, String>();        http_url_maps.put("习近平接受八国新任驻华大使递交国书", "http://img.my.csdn.net/uploads/201407/26/1406383291_6518.jpg");        http_url_maps.put("天津港总裁出席发布会", "http://img.my.csdn.net/uploads/201407/26/1406383290_9329.jpg");        http_url_maps.put("瑞海公司从消防鉴定到安评一路畅通无阻", "http://img.my.csdn.net/uploads/201407/26/1406383290_1042.jpg");        http_url_maps.put("Airbnb高调入华 命运将如Uber一样吗?", "http://img.my.csdn.net/uploads/201407/26/1406383275_3977.jpg");        return http_url_maps;    }    /**     *  解析 JSON     */    private void forGson(String str){        Gson gson = new Gson();        TotalT totalT = gson.fromJson(str, TotalT.class);        String resultCode = totalT.getResultCode();        String resultInfo = totalT.getResultInfo();        //   Log.d("============", "结果码: "+resultCode+", 结果信息:"+resultInfo);        InfoT infoT = totalT.getInfo();        List<MerchantKeyT> merchantKeyTList = infoT.getMerchantKey();        adapter.setForMerchantKeyT(merchantKeyTList);    }    @Override    public void onPause() {        if(sliderLayout !=null) {            sliderLayout.stopAutoCycle();            sliderLayout = null;        }        super.onDestroy();    }}



其中 MyAdapter.java 类不同移动和修改(内容见前文),现在添加左侧的 LeftFragment.java :

package com.scxh.listlayout;import android.app.Activity;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;public class LeftFragment extends Fragment {    public Callbacks callbacks;    public interface Callbacks {        public void mediaClick();        public void musicClick();        public void pictureClick();    }    public static LeftFragment newInstance() {        LeftFragment fragment = new LeftFragment();        return fragment;    }    @Override    public void onAttach(Activity activity) {        super.onAttach(activity);        if (activity instanceof Callbacks ){            callbacks = (Callbacks)activity;        } else {            throw new RuntimeException(activity.toString()                    + " must implement OnMerchantFragmentInteractionListener");        }    }    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_left, container, false);    }    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);        Button mediaButton = (Button)getView().findViewById(R.id.media_button);        Button musicButton = (Button)getView().findViewById(R.id.music_button);        Button pictureButton = (Button)getView().findViewById(R.id.picture_button);        mediaClick(mediaButton);        musicClick(musicButton);        pictureClick(pictureButton);    }    @Override    public void onDetach() {        super.onDetach();        // 将 callbacks 复为 null        callbacks = null;    }        private void mediaClick(Button mediaButton){        mediaButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                callbacks.mediaClick();            }        });    }    private void musicClick(Button musicButton){        musicButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                callbacks.musicClick();            }        });    }    private void pictureClick(Button pictureButton){        pictureButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                callbacks.pictureClick();            }        });    }}



为了实现点击 title 位置的 箭头和左侧的按钮有所回应,所有在其中增加了接口,以此来实现交互;

现在添加 LefActivity.java :

package com.scxh.listlayout;import android.os.Bundle;import com.warmtel.slidingmenu.lib.SlidingMenu;import com.warmtel.slidingmenu.lib.app.SlidingActivity;public class LeftActivity extends SlidingActivity        implements MainFragment.addOrBack, LeftFragment.Callbacks{    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.left_framelayout_for_leftfragment);        // 显示 MainFragment 的内容        getFragmentManager().beginTransaction().                add(R.id.left_frame_fragment, MainFragment.newInstance()).commit();        // 显示 LeftFragment 的内容(侧面)        setBehindContentView(R.layout.sliding_leftfragment_layout);        getFragmentManager().beginTransaction()                .add(R.id.sliding_merchant_layout, LeftFragment.newInstance()).commit();        SlidingMenu slidingMenu = getSlidingMenu();        slidingMenu.setBehindOffsetRes(R.dimen.sliding_menu_offset);        // 侧滑的 Fragment 在左侧        slidingMenu.setMode(SlidingMenu.LEFT);        // 在全屏幕上都可以滑动        slidingMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);    }    @Override    public void toAddToBack() {        // 打开和关闭 (slidingmenu_library-release 第三方框架自带的)        toggle();    }    /**     *  当点击视频新闻按钮时,回到新闻的显示页面     */    @Override    public void mediaClick() {        getFragmentManager().beginTransaction()                .replace(R.id.left_frame_fragment, MainFragment.newInstance()).commit();        toggle();    }    /**     *  点击音乐新闻按钮时,跳转到 MusicFragment     */    @Override    public void musicClick() {        getFragmentManager().beginTransaction()                .replace(R.id.left_frame_fragment, MusicFragment.newInstance()).commit();        toggle();    }    /**     *  点击图片新闻按钮时,跳转到 PictureFragment     */    @Override    public void pictureClick() {        getFragmentManager().beginTransaction()                .replace(R.id.left_frame_fragment, PictureFragment.newInstance()).commit();        toggle();    }}



点击按钮后弹出的 fragment  如下:

MusicFragment:

package com.scxh.listlayout;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class MusicFragment extends Fragment {    public static MusicFragment newInstance() {        MusicFragment fragment = new MusicFragment();        return fragment;    }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_music, container, false);    }}



所需的 PictureFragment.java :

package com.scxh.listlayout;import android.app.Fragment;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;public class PictureFragment extends Fragment {    public static PictureFragment newInstance() {        PictureFragment fragment = new PictureFragment();        return fragment;    }    @Override    public void onActivityCreated(Bundle savedInstanceState) {        super.onActivityCreated(savedInstanceState);            }    @Override    public View onCreateView(LayoutInflater inflater, ViewGroup container,                             Bundle savedInstanceState) {        // Inflate the layout for this fragment        return inflater.inflate(R.layout.fragment_picture, container, false);    }}



同心圆的效果:

BullsView.java :

package com.scxh.listlayout;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.graphics.Point;import android.util.AttributeSet;import android.view.View;public class BullsView extends View {    private Paint mPaint;    private Point mCenter;    private float mRadius;    public BullsView(Context context) {        this(context, null);    }    public BullsView(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public BullsView(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        // 创建画笔(支持锯齿)        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);        mPaint.setStyle(Paint.Style.FILL);        // 创建圆心        mCenter = new Point();    }    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        int width, height;        // 确定内容的理想大小,无约束        int cWidth = 100;        int mHeight = 100;        width = getHowToGetWH(widthMeasureSpec, cWidth);        height = getHowToGetWH(heightMeasureSpec, mHeight);        // 使用测量必须调用该方法        setMeasuredDimension(width, height);    }    /**     * 测量宽度和高度的方法     */    private int getHowToGetWH(int measureSpec, int mSize) {        int specSize = MeasureSpec.getSize(measureSpec);        switch (MeasureSpec.getMode(measureSpec)) {            case MeasureSpec.AT_MOST:                return Math.min(specSize, mSize);            case MeasureSpec.UNSPECIFIED:                return mSize;            case MeasureSpec.EXACTLY:                return specSize;            default:                return 0;        }    }    @Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        // 如果有变化,则复位参数        if (w != oldw || h != oldh) {            mCenter.x = w / 2;            mCenter.y = h / 2;            mRadius = Math.min(mCenter.x, mCenter.y);        }    }    @Override    protected void onDraw(Canvas canvas) {        // 绘制同心圆        mPaint.setColor(Color.RED);        canvas.drawCircle(mCenter.x, mCenter.y, mRadius, mPaint);        mPaint.setColor(Color.WHITE);        canvas.drawCircle(mCenter.x, mCenter.y, mRadius * 0.8f, mPaint);        mPaint.setColor(Color.BLACK);        canvas.drawCircle(mCenter.x, mCenter.y, mRadius * 0.6f, mPaint);        mPaint.setColor(Color.CYAN);        canvas.drawCircle(mCenter.x, mCenter.y, mRadius * 0.4f, mPaint);        mPaint.setColor(Color.BLUE);        canvas.drawCircle(mCenter.x, mCenter.y, mRadius * 0.1f, mPaint);    }}




布局文件 for_mainfragment.xml :

<?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="match_parent"    android:orientation="vertical"    android:background="@android:color/white"    android:paddingBottom="5dp"    android:paddingLeft="5dp"    android:paddingRight="5dp"    android:paddingTop="5dp">    <include layout="@layout/activity_title" />    <FrameLayout        android:layout_width="match_parent"        android:layout_height="match_parent">        <com.warmtel.android.xlistview.XListView            android:id="@+id/listView"            android:layout_width="match_parent"            android:layout_height="match_parent"            android:divider="@android:color/white"            android:dividerHeight="5dp" />        <ProgressBar            android:id="@+id/progressbar"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:layout_gravity="center" />    </FrameLayout></LinearLayout>



其中所包含的 activity_title.xml :

<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="30dp"    android:background="@drawable/common_bg_title">    <ImageView        android:id="@+id/title_imageview"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerVertical="true"        android:layout_marginLeft="10dp"        android:src="@drawable/btn_back"/>    <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="我的关注"        android:layout_toRightOf="@id/title_imageview"        android:textSize="22sp"        android:layout_centerVertical="true"        android:layout_marginLeft="10dp"/></RelativeLayout>



fragment_left.xml (左侧的按钮部分):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".LeftFragment">    <!-- TODO: Update blank fragment layout -->    <TextView        android:id="@+id/textView_fragment_left"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:textSize="30sp"        android:text="新闻的内容形式" />    <Button        android:id="@+id/media_button"        android:background="@drawable/background_button"        android:stateListAnimator="@animator/button_press"        android:textSize="22sp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="视频新闻" />    <Button        android:id="@+id/music_button"        android:background="@drawable/background_button"        android:stateListAnimator="@animator/button_press"        android:textSize="22sp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="音乐新闻" />    <Button        android:id="@+id/picture_button"        android:background="@drawable/background_button"        android:stateListAnimator="@animator/button_press"        android:textSize="22sp"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="图片新闻" /></LinearLayout>




fragment_main.xml :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.scxh.listlayout.MainFragment">    <!-- TODO: Update blank fragment layout -->    <TextView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:text="@string/hello_blank_fragment" /></FrameLayout>




fragment_music.xml :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@android:color/holo_blue_light"    tools:context="com.scxh.listlayout.MusicFragment">    <!-- TODO: Update blank fragment layout -->    <TextView        android:id="@+id/music_fragment_content"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:textSize="30sp"        android:gravity="center"        android:text="Music 来起 !" /></FrameLayout>




fragment_picture.xml :

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.scxh.listlayout.PictureFragment">    <!-- TODO: Update blank fragment layout -->    <com.scxh.listlayout.BullsView        android:id="@+id/picture_fragment_content"        android:layout_width="match_parent"        android:layout_height="match_parent" /></FrameLayout>




left_framelayout_for_leftfragment.xml :

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/left_frame_fragment"></FrameLayout>




sliding_leftfragment_layout.xml :

<?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:id="@+id/sliding_merchant_layout"></FrameLayout>




左侧按钮效果的资源:

button_default.xml :

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item        android:state_enabled="false"        android:drawable="@drawable/disabled" />    <item        android:state_pressed="true"        android:drawable="@drawable/selected" />    <item        android:state_focused="true"        android:drawable="@drawable/selected" />    <item android:drawable="@drawable/fdefault" /></selector>




drawable-v21 目录中的 background_button.xml :

<?xml version="1.0" encoding="utf-8"?><ripple xmlns:android="http://schemas.android.com/apk/res/android"    android:color="#0CC">    <!--显示默认的 drawable-->    <item android:drawable="@drawable/button_default" />    <!--匹配默认值的波纹效果剪切遮罩-->    <item        android:id="@android:id/mask"        android:drawable="@drawable/button_default" /></ripple>



animator 目录下的 button_press.xml :

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android">    <item        android:state_enabled="true"        android:state_pressed="true">        <set android:ordering="together">            <objectAnimator                android:duration="@android:integer/config_shortAnimTime"                android:propertyName="scaleX"                android:valueTo="0.8"                android:valueType="floatType" />            <objectAnimator                android:duration="@android:integer/config_shortAnimTime"                android:propertyName="scaleY"                android:valueTo="0.8"                android:valueType="floatType" />        </set>    </item>    <item>        <set android:ordering="together">            <objectAnimator                android:duration="@android:integer/config_shortAnimTime"                android:propertyName="scaleX"                android:valueTo="1.0"                android:valueType="floatType" />            <objectAnimator                android:duration="@android:integer/config_shortAnimTime"                android:propertyName="scaleY"                android:valueTo="1.0"                android:valueType="floatType" />        </set>    </item></selector>





0 0
原创粉丝点击