单纯的Fragment传递数据,两个按钮实现切换

很简单的两个按钮实现加在数据,其实两个都是一样的 只不过换了个网址...

做的比较low..请谅解  //废话不说 上图~

单纯的Fragment传递数据,两个按钮实现切换_第1张图片

第二个按钮我就不上图了 和这个一样.

可以看到两个按钮实现切换,按钮我没有设置背景和选中颜色,就是普通白色  然后点击切换Fragment.

我这个切换没有使用ViewPage,就是点击按钮切换Fragment和里面内容


先附上xml文件

主布局:

就是一个 RadioGroup里面套了两个按钮,RadioGrouo里面横向一定要写 不写会造成Button按钮没有东西

    android:id="@+id/rg"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:orientation="horizontal"
    >
            android:id="@+id/btn_liuxing"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="流行"
        android:button="@null"
        android:gravity="center"
        android:textSize="20sp"
        />
            android:id="@+id/bent_remen"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="match_parent"
        android:text="热门"
        android:textSize="20sp"
        android:button="@null"
        android:gravity="center"
        />


    android:id="@+id/fl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_below="@+id/rg"
    >
主布局代码:里面就是声明Fragment RadioGroup的点击切换

全程使用V4包

 
  
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioGroup;

import yztc.com.day1008_fragment.fragment_liuxing.fragment_liuxing;
import yztc.com.day1008_fragment.fragment_remen.fragment_remen;

public class MainActivity extends AppCompatActivity {
    //碎片布局填充 准备
    //碎片管理者对象
    private FragmentManager manager;
    //碎片执行者对象
    private FragmentTransaction ft;
    //两个Button点击事件初始化
    private RadioGroup rg;
    private fragment_liuxing liuxing;
    private fragment_remen remen;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //初始化控件
        rg = (RadioGroup) findViewById(R.id.rg);
        //碎片管理者对象
        manager = getSupportFragmentManager();
        //碎片执行者对象
        ft = manager.beginTransaction();
        liuxing = new fragment_liuxing();
        remen = new fragment_remen();
        //第一页显示
        ft.add(R.id.fl, liuxing);
        //提交事件
        ft.commit();

        //RadioGroup点击事件
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {

                ft = manager.beginTransaction();
                switch (i) {
                    //第一个按钮 切换
                    case R.id.btn_liuxing:
                        //这里要写成替换
                        ft.replace(R.id.fl, liuxing);
                        break;
                    //第二个按钮 切换
                    case R.id.bent_remen:
                        ft.replace(R.id.fl, remen);
                        break;
                }
                //必须要写 不写会造成 白板 没有东西
                ft.commit();
            }
        });
    }
}
碎片 流行 主布局代码:

网络访问是用了第三方框架OkHttp 复制粘贴到APP下就可以使用

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.util.List;

import yztc.com.day1008_fragment.Contanst;
import yztc.com.day1008_fragment.R;

/**
 * Created by Administrator on 2016/10/8.
 */
public class fragment_liuxing extends Fragment {
    //获取listview
    private ListView lv;
    private List list;
    //构建适配器
    private BaseAdapter_liuxing adapter;
    //handler异步 
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String str = (String) msg.obj;
                    list = ParserJson.getParserJson(str);
                    adapter = new BaseAdapter_liuxing(list,getActivity());
                    //适配
                    lv.setAdapter(adapter);
                    break;
            }
        }
    };
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_liuxing,null);
        //初始化控件
        lv = (ListView) view.findViewById(R.id.lv_liuxing);
        
        return view;
    }
    
    //这个方法和上一个没什么区别,
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        getOkttp();
        
    }
    
    //网络访问 第三方框架(OkHttp):compile 'com.squareup.okhttp:okhttp:2.7.5'
    public void getOkttp() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(Contanst.URL).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            //下载失败
            @Override
            public void onFailure(Request request, IOException e) {
                Log.i("tag","下载失败");
            }
            //下载成功
            @Override
            public void onResponse(Response response) throws IOException {
                String json = response.body().string();
                Message message = new Message();
                //传递
                message.what = 1;
                message.obj = json;
                handler.sendMessage(message);
            }
        });

    }
}
碎片 适配器代码:

import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

import yztc.com.day1008_fragment.R;

/**
 * Created by Administrator on 2016/10/8.
 */
public class BaseAdapter_liuxing extends BaseAdapter {
    private List list;
    private Context context;

    public BaseAdapter_liuxing(List list, Context context) {
        this.context = context;
        this.list = list;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }


    ViewHolder holder = null;
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (convertView == null){
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.liuxing_item,null);
            holder = new ViewHolder();
            holder.iv = (ImageView) convertView.findViewById(R.id.iv_liuxing);
            holder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            holder.tv_author = (TextView) convertView.findViewById(R.id.tv_author);
            holder.tv_time = (TextView) convertView.findViewById(R.id.publishtime);
            convertView.setTag(holder);
        }else {
            holder = (ViewHolder) convertView.getTag();
        }
        //获取图片
        String imageUrl = list.get(position).getPic_big();
        Log.i("tag","-------imageUrl-------"+imageUrl);
        //下载图片 第三方框架Glide compile 'com.github.bumptech.glide:glide:3.7.0'
        Glide.with(context).load(imageUrl).into(holder.iv);

        holder.tv_title.setText(list.get(position).getTitle());
        holder.tv_author.setText(list.get(position).getAuthor());
        holder.tv_time.setText(list.get(position).getPublishtime());

        return convertView;
    }
    //定义类
    public class ViewHolder{
        ImageView iv;
        TextView tv_title,tv_author,tv_time;
    }

}
实体类:

/**
 * "artist_id": "15",
 "language": "国语",
 "pic_big": "http://musicdata.baidu.com/data2/pic/4367a6de6f7dc000c50962ca55c964a2/271831974/271831974.jpg",
 "pic_small": "http://musicdata.baidu.com/data2/pic/5b13c6847088bda14e02a681f962061e/271831977/271831977.jpg",
 "country": "内地",
 "area": "0",
 "publishtime": "2016-09-24",
 "album_no": "1",
 "lrclink": "http://musicdata.baidu.com/data2/lrc/49a5a8b8e3ee44190967da0152d79ad3/271833151/271833151.lrc",
 "copy_type": "3",
 "hot": "492611",
 "all_artist_ting_uid": "45561",
 "resource_type": "0",
 "is_new": "1",
 "rank_change": "0",
 "rank": "1",
 "all_artist_id": "15",
 "style": "影视原声",
 "del_status": "0",
 "relate_status": "0",
 "toneid": "0",
 "all_rate": "64,128,256,320,flac",
 "sound_effect": "0",
 "file_duration": 286,
 "has_mv_mobile": 0,
 "versions": "",
 "bitrate_fee": "{\"0\":\"0|0\",\"1\":\"0|0\"}",
 "song_id": "271832017",
 "title": "你在终点等我",
 "ting_uid": "45561",
 "author": "王菲",
 "album_id": "271832019",
 "album_title": "你在终点等我",
 "is_first_publish": 0,
 "havehigh": 2,
 "charge": 0,
 "has_mv": 0,
 "learn": 0,
 "song_source": "web",
 "piao_id": "0",
 "korean_bb_song": "0",
 "resource_type_ext": "0",
 "mv_provider": "0000000000",
 "artist_name": "王菲"
 */
public class MusicInfo {
    private String title;
    private String author;
    private String publishtime;
    private String pic_big;

    public MusicInfo(String title, String author, String pic_big, String publishtime) {
        this.title = title;
        this.author = author;
        this.pic_big = pic_big;
        this.publishtime = publishtime;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPic_big() {
        return pic_big;
    }

    public void setPic_big(String pic_big) {
        this.pic_big = pic_big;
    }

    public String getPublishtime() {
        return publishtime;
    }

    public void setPublishtime(String publishtime) {
        this.publishtime = publishtime;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }
}
Json串解析 原生解析:

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/10/8.
 */
public class ParserJson {
    public static List getParserJson(String jsonString){
        List list = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONArray jsonArray = jsonObject.getJSONArray("song_list");
            for (int i = 0;i;i++){
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                String title = jsonObject1.getString("title");
                String author = jsonObject1.getString("author");
                String pic_bg = jsonObject1.getString("pic_big");

//                String fileName = pic_bg.substring(2,pic_bg.length()-2);
//                String str = fileName.replace("\\","");
//                Log.i("tag", "----str----" + str);
                String publishtime = jsonObject1.getString("publishtime");
		//装入list
                MusicInfo musicInfo = new MusicInfo(title,author,pic_bg,publishtime);
                list.add(musicInfo);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

        return list;
    }
}

网址: Url

public class Contanst {
    public static final String URL = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=qianqian&version=2.1.0&method=baidu.ting.billboard.billList&format=json&type=1&offset=0&size=50";
    public static final String URL1 = "http://tingapi.ting.baidu.com/v1/restserver/ting?from=qianqian&version=2.1.0&method=baidu.ting.billboard.billList&format=json&type=2&offset=0&size=50";
}
碎片主布局:就是一个LIstView

xml version="1.0" encoding="utf-8"?>
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/lv_liuxing"
        android:layout_width="match_parent"
        android:layout_height="match_parent">


碎片的item:用来给listview赋值用的布局

xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
            android:layout_width="match_parent"
        android:layout_height="100dp">
            android:id="@+id/iv_liuxing"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@mipmap/ic_launcher"
        android:layout_margin="15dp"
        />
                    android:id="@+id/tv_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="title"
            android:layout_toRightOf="@+id/iv_liuxing"
            android:layout_marginTop="15dp"
            android:textSize="20sp"
            />
                    android:id="@+id/tv_author"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="author"
            android:layout_below="@+id/tv_title"
            android:layout_toRightOf="@id/iv_liuxing"
            />
                    android:id="@+id/publishtime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="publishtime"
            android:layout_toRightOf="@id/iv_liuxing"
            android:layout_below="@id/tv_author"
            />
    

代码可以粘贴使用.博客写的很烂请多谅解,新人一枚,以后慢慢写出好文章..

第二个布局我就不写了 都是一样的 改个网址数据就不同了.

现在可以运行下程序了...是不是成功了呢?



哈哈.是不是报这个错误了?java.lang.SecurityException: Permission denied (missing INTERNET permission?)

加上网络权限就可以咯

在mainfests里



android:name="android.permission.INTERNET">


你可能感兴趣的:(Fragment,切换)