Android Activity中实现Fragment切换功能效果

      一个最简单的Activity中实现Fragment切换功能效果:

一.效果图:

二.快速实现:

一个Activity中添加多个Fragment进行切换实现相应的功能需求逻辑,比如在activity中有三个按钮切换fragment界面,按钮1和按钮二都是点击之后直接切换到对应的Fragment,按钮3则是弹出一个弹框出来,然后点击弹框中的按钮再进行切换到对应的Fragment。

1.主函数代码:

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.example.qd.douyinwu.R;
import com.example.qd.douyinwu.adapter.MyListAdapter;
import com.example.qd.douyinwu.fragment.FlyFragment;
import com.example.qd.douyinwu.fragment.HightFragment;
import com.example.qd.douyinwu.fragment.TestFragment;
import com.example.qd.douyinwu.view.activity.popupmenu.PopUpWindowActivity;

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

public class FragmentTestActivity extends AppCompatActivity implements View.OnClickListener{

    private FragmentManager fragmentManager;
    private FlyFragment flyFragment;
    private HightFragment hightFragment;
    private FragmentTransaction mTransaction;
    private String[] name;
    private List<String> list = new ArrayList<>();
    private PopupWindow popupWindow1;
    private Button btThree;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);

        initView();
    }

    private void initView(){
        FrameLayout fl = findViewById(R.id.fl);
        Button btOne = findViewById(R.id.bt_one);
        btThree = findViewById(R.id.bt_three);

        Button btTwo = findViewById(R.id.bt_two);
        btOne.setOnClickListener(this);
        btThree.setOnClickListener(this);
        btTwo.setOnClickListener(this);

        list.clear();
        list.add("KING");
        list.add("OLPL");
        list.add("CHAIN");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        list.add("CHINA");
        //获取到fragment的管理者

        fragmentManager = getSupportFragmentManager();
        //开启事务
        mTransaction = fragmentManager.beginTransaction();

        flyFragment = new FlyFragment();
        hightFragment = new HightFragment();
        /**
         * 替换界面
         * 1 需要替换的界面的id
         * 2具体指某一个fragment的对象
         */
        mTransaction.replace(R.id.fl, flyFragment).commit();

    }

    @Override
    public void onClick(View v) {
        FragmentTransaction mTransaction = fragmentManager.beginTransaction();
        switch (v.getId()){
            case R.id.bt_one:
                mTransaction.replace(R.id.fl, flyFragment).commit();
                break;
            case R.id.bt_two:
                mTransaction.replace(R.id.fl, hightFragment).commit();
                break;
            case R.id.bt_three:
                initPopWindow();
                break;
                default:
                    break;
        }
    }
    private void initPopWindow(){

        View contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.layout_pop_item_list, null);
//        contentView.setBackgroundColor(Color.BLUE);

        popupWindow1 = new PopupWindow(findViewById(R.id.mainLayout), 900, LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow1.setContentView(contentView);

        TextView tvMore = (TextView) contentView.findViewById(R.id.tv_more);
        TextView textView = (TextView) contentView.findViewById(R.id.text);
        tvMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow1.dismiss();
                //这里需要重新获取对象,不然会报错java.lang.IllegalStateException: commit already called
                fragmentManager = getSupportFragmentManager();
                FragmentTransaction mTransaction = fragmentManager.beginTransaction();
                mTransaction.replace(R.id.fl, new TestFragment()).commit();
                Toast.makeText(FragmentTestActivity.this, "更多", Toast.LENGTH_SHORT).show();
            }
        });
        textView.setText("测试");
        openDir();
        ListView listView = (ListView) contentView.findViewById(R.id.list);
        //原生自带布局
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, name);
        //自定义布局,只可以设置一个控件的布局
//        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item_popup,R.id.tv_content, name);
        //完全自定义布局
        MyListAdapter mAdapter = new MyListAdapter(this,list);//得到一个MyAdapter对象
        listView.setAdapter(mAdapter);//为ListView绑定Adapter /*为ListView添加点击事件*/
//        listView.setAdapter(adapter);
        mAdapter.setOnClickMyTextView(new MyListAdapter.OnClickMyTextView() {
            @Override
            public void myTextViewClick(int id) {
                Toast.makeText(FragmentTestActivity.this, "点击了"+id, Toast.LENGTH_SHORT).show();

            }
        });
        popupWindow1.setFocusable(true);
        popupWindow1.showAsDropDown(btThree);//显示位置

        popupWindow1.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                popupWindow1.dismiss();
            }
        });
        popupWindow1.setOutsideTouchable(true);
    }
    private void openDir()
    {
        name = new String[]{"12","22","22","22","22","22","22","22"};
    }
}

2.主函数布局:

<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:background="@color/colorPrimary"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="50dp">
        <Button
            android:id="@+id/bt_one"
            android:text="一"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/bt_two"
            android:text="二"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <Button
            android:id="@+id/bt_three"
            android:text="三"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

    <FrameLayout
        android:id="@+id/fl"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></FrameLayout>
</LinearLayout>

3.FlyFragment.class:

package com.example.qd.douyinwu.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.qd.douyinwu.R;

public class FlyFragment extends Fragment{

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_fly,container,false);
//        TextView mTextView = (TextView) view.findViewById(R.id.tv_fragment_content);
//        mTextView.setText("Fragment2");
//        mTextView.setOnClickListener(this);
//        Button mButton = (Button) view.findViewById(R.id.btn_toggle_fragment);
//        mButton.setOnClickListener(this);
        return view;
    }
}

4.fragment_fly.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">

    <TextView
        android:id="@+id/tv_content"
        android:text="我是一"
        android:layout_gravity="center"
        android:gravity="center"
        android:textSize="25sp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

 

5.Fragment都是类似的就不全部贴出了,直接复制改下名字就可以:

TestFragment.class

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.example.qd.douyinwu.R;

public class TestFragment extends Fragment{

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_hight,container,false);
        TextView mTextView = (TextView) view.findViewById(R.id.tv_content);
        mTextView.setText("我是三");
//        mTextView.setOnClickListener(this);
//        Button mButton = (Button) view.findViewById(R.id.btn_toggle_fragment);
//        mButton.setOnClickListener(this);
        return view;
    }
}

 

 

以下是测试demo:(布局颜色需要改变)Fragment之间的滑动 网路请求解析(仅仅是笔记)

       bean 1

<span style="font-size:18px;">import java.util.List;

public class Data1 {

	public List<MyData1> data;
	
	public class MyData1{
		
		public String FROMNAME;
		public String ID;
		public String IMAGEURL;
		public String RN;
		public String SHOWTIME;
		public String SUBTITLE;
		public String TITLE;
	}
}
</span>

 

 

 

bean 2

 

<span style="font-size:18px;">import java.util.List;

public class Data2 {

	public List<MyData2> data;
	
	public class MyData2{
		
		public String ID;
		public String RN;
		public String SHOWTIME;
		public String SUBTITLE;
		public String TITLE;
	}
}</span>

 

 

 

  MainActivity.class

 

 

<span style="font-size:18px;">import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.TextView;
import fragment.Fragment1;
import fragment.Fragment2;
import fragment.Fragment3;

public class MainActivity extends FragmentActivity implements OnClickListener {

	private TextView t1;
	private TextView t2;
	private TextView t3;
	private ViewPager viewPager;
	private TextView t11;
	private TextView t22;
	private TextView t33;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 去掉头部
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		//初始化组件
		initView();

	}

	/**
	 * 初始化组件
	 */

	@SuppressWarnings("deprecation")
	public void initView() {
		t1 = (TextView) findViewById(R.id.t1);
		t2 = (TextView) findViewById(R.id.t2);
		t3 = (TextView) findViewById(R.id.t3);
		t11 = (TextView) findViewById(R.id.t11);
		t22 = (TextView) findViewById(R.id.t22);
		t33 = (TextView) findViewById(R.id.t33);
		viewPager = (ViewPager) findViewById(R.id.viewPager);

		// 设置监听
		t1.setOnClickListener(this);
		t2.setOnClickListener(this);
		t3.setOnClickListener(this);

		t11.setOnClickListener(this);
		t22.setOnClickListener(this);
		t33.setOnClickListener(this);
		
		//给ViewPager设置适配器
		viewPager.setAdapter(new FragmentPagerAdapter(
				getSupportFragmentManager()) {

			@Override
			public int getCount() {
				// TODO Auto-generated method stub
				return 3;
			}

			@Override
			public Fragment getItem(int arg0) {
				//根据ViewPager 索引 返回相应Fragment
				Fragment fragment = null;
				switch (arg0) {
				case 0:
					fragment = new Fragment1();

					break;
				case 1:
					fragment = new Fragment2();
					break;
				case 2:
					fragment = new Fragment3();
					break;

				default:
					break;
				}
				return fragment;
			}
		});
		
		//给ViewPager设置滑动监听
		viewPager.setOnPageChangeListener(new OnPageChangeListener() {

			@Override
			public void onPageSelected(int position) {
				//根据position改变游标状态
				switch (position) {
				case 0:
					t11.setBackgroundColor(Color.RED);
					t22.setBackgroundColor(Color.parseColor("#00000000"));
					t33.setBackgroundColor(Color.parseColor("#00000000"));
					break;
				case 1:
					t22.setBackgroundColor(Color.RED);
					t11.setBackgroundColor(Color.parseColor("#00000000"));
					t33.setBackgroundColor(Color.parseColor("#00000000"));
					break;
				case 2:
					t33.setBackgroundColor(Color.RED);
					t22.setBackgroundColor(Color.parseColor("#00000000"));
					t11.setBackgroundColor(Color.parseColor("#00000000"));
					break;
				default:
					break;
				}

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub

			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub

			}
		});
	}

	/**
	 * 点击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		//点击选项卡 跳转到对应的Fragment页
		case R.id.t1:
			viewPager.setCurrentItem(0);
			break;
		case R.id.t2:
			viewPager.setCurrentItem(1);
			break;
		case R.id.t3:
			viewPager.setCurrentItem(2);
			break;
		default:
			break;
		}
	}

}
</span>

 

 

 

 

 

 Fragment1

 

<span style="font-size:18px;">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
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.ListView;
import android.widget.TextView;
import bean.Data1;
import bean.Data1.MyData1;

import com.bwie.test.R;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;

public class Fragment1 extends Fragment {

	private View view;
	private ListView listView1;
	private final String path = "http://www.93.gov.cn/93app/data.do";// 接口
	private String resultJson;
	private Context context;
	private List<MyData1> datas = new ArrayList<MyData1>();
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				//给listView 设置数据  更新UI
				resultJson = (String) msg.obj;
				Gson gson = new Gson();
				Data1 fromJson = gson.fromJson(resultJson, Data1.class);
				datas.addAll(fromJson.data);
				listView1.setAdapter(new MyBaseAdapter1());
				break;

			default:
				break;
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment1, container, false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

		context = getActivity();
		listView1 = (ListView) view.findViewById(R.id.listView1);

		new Thread() {
			public void run() {
				requestDataByData(0, 0);

			}
		}.start();
	}

	/**
	 * 请求网络数据
	 */

	public void requestDataByData(final int channelId, final int startNum) {

		try {
			URL url = new URL(path);
			String entity = "channelId=" + channelId + "&startNum=" + startNum;
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			OutputStream outputStream = conn.getOutputStream();
			outputStream.write(entity.getBytes());
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
				InputStream is = conn.getInputStream();
				//将流转化为字符换
				int len = 0;
				byte[] buffer = new byte[1024];
				while ((len = is.read(buffer)) != -1) {
					arrayOutputStream.write(buffer, 0, len);
				}
				//将结果发送的Handler
				handler.obtainMessage(0, arrayOutputStream.toString("utf-8"))
						.sendToTarget();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class MyBaseAdapter1 extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return datas.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View arg1, ViewGroup arg2) {
			View view2 = View.inflate(context, R.layout.list_item1, null);
			TextView title1 = (TextView) view2.findViewById(R.id.title1);
			TextView subTitle1 = (TextView) view2.findViewById(R.id.subTitle);
			TextView time1 = (TextView) view2.findViewById(R.id.time1);
			TextView author1 = (TextView) view2.findViewById(R.id.author1);
			ImageView img = (ImageView) view2.findViewById(R.id.img);
			title1.setText(datas.get(position).TITLE);
			subTitle1.setText(datas.get(position).SUBTITLE);
			time1.setText(datas.get(position).SHOWTIME);
			author1.setText(datas.get(position).FROMNAME);
			if(TextUtils.isEmpty(datas.get(position).IMAGEURL)){
				img.setVisibility(View.GONE);
			}else{
				BitmapUtils bitmapUtils = new BitmapUtils(context);
				bitmapUtils.display(img, datas.get(position).IMAGEURL);
			}
			
			return view2;
		}

	}

}
</span>

 

 

 

 

 

   Fragment2

 

<span style="font-size:18px;">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
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.ListView;
import android.widget.TextView;
import bean.Data1;
import bean.Data1.MyData1;
import bean.Data2;
import bean.Data2.MyData2;

import com.bwie.test.R;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;

public class Fragment2 extends Fragment {

	private View view;
	private ListView listView2;
	private final String path = "http://www.93.gov.cn/93app/data.do";// 接口
	private String resultJson;
	private Context context;
	private List<MyData2> datas = new ArrayList<MyData2>();
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				//给listView 设置数据  更新UI
				resultJson = (String) msg.obj;
				Log.i("result", resultJson);
				Gson gson = new Gson();
				Data2 fromJson = gson.fromJson(resultJson, Data2.class);
				datas.addAll(fromJson.data);
				listView2.setAdapter(new MyBaseAdapter1());
				break;

			default:
				break;
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment2, container, false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		//获得上下文对象
		context = getActivity();
		listView2 = (ListView) view.findViewById(R.id.listView2);

		//开启子线程  进行请求网络 操作
		new Thread() {
			public void run() {
				requestDataByData(1, 21);

			}
		}.start();
	}

	/**
	 * 请求网络数据   POST
	 */

	public void requestDataByData(final int channelId, final int startNum) {

		try {
			URL url = new URL(path);
			String entity = "channelId=" + channelId + "&startNum=" + startNum;
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			OutputStream outputStream = conn.getOutputStream();
			outputStream.write(entity.getBytes());
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
				InputStream is = conn.getInputStream();
				
				//将流转化为字符串
				int len = 0;
				byte[] buffer = new byte[1024];
				while ((len = is.read(buffer)) != -1) {
					arrayOutputStream.write(buffer, 0, len);
				}

				handler.obtainMessage(0, arrayOutputStream.toString("utf-8"))
						.sendToTarget();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	//自定义适配器
	class MyBaseAdapter1 extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return datas.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View arg1, ViewGroup arg2) {
			View view2 = View.inflate(context, R.layout.list_item2, null);
			TextView title2 = (TextView) view2.findViewById(R.id.title2);
			TextView subTitle2 = (TextView) view2.findViewById(R.id.subTitle2);
			TextView time2 = (TextView) view2.findViewById(R.id.time2);
			title2.setText(datas.get(position).TITLE);
			subTitle2.setText(datas.get(position).SUBTITLE);
			time2.setText(datas.get(position).SHOWTIME);

			return view2;
		}

	}

}</span>

 

 

 

    Fragment3

 

 

<span style="font-size:18px;">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
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.ListView;
import android.widget.TextView;
import bean.Data1;
import bean.Data1.MyData1;
import bean.Data2;
import bean.Data2.MyData2;

import com.bwie.test.R;
import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;

public class Fragment3 extends Fragment {

	private View view;
	private ListView listView2;
	private final String path = "http://www.93.gov.cn/93app/data.do";// 接口
	private String resultJson;
	private Context context;
	private List<MyData2> datas = new ArrayList<MyData2>();
	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				//给listView 设置数据  更新UI
				resultJson = (String) msg.obj;
				Log.i("result", resultJson);
				Gson gson = new Gson();
				Data2 fromJson = gson.fromJson(resultJson, Data2.class);
				datas.addAll(fromJson.data);
				listView2.setAdapter(new MyBaseAdapter1());
				break;

			default:
				break;
			}
		};
	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		view = inflater.inflate(R.layout.fragment2, container, false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		// 获得上下文对象
		context = getActivity();
		listView2 = (ListView) view.findViewById(R.id.listView2);
		// 开启一个子线程 进行请求网络操作
		new Thread() {
			public void run() {
				requestDataByData(3, 21);

			}
		}.start();
	}

	/**
	 * 请求网络数据
	 */

	public void requestDataByData(final int channelId, final int startNum) {

		try {
			URL url = new URL(path);
			String entity = "channelId=" + channelId + "&startNum=" + startNum;
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoOutput(true);
			OutputStream outputStream = conn.getOutputStream();
			outputStream.write(entity.getBytes());
			int responseCode = conn.getResponseCode();
			if (responseCode == 200) {
				ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
				InputStream is = conn.getInputStream();
				//将流转化为字符串
				int len = 0;
				byte[] buffer = new byte[1024];
				while ((len = is.read(buffer)) != -1) {
					arrayOutputStream.write(buffer, 0, len);
				}

				handler.obtainMessage(0, arrayOutputStream.toString("utf-8"))
						.sendToTarget();
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	class MyBaseAdapter1 extends BaseAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return datas.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View arg1, ViewGroup arg2) {
			View view2 = View.inflate(context, R.layout.list_item2, null);
			TextView title2 = (TextView) view2.findViewById(R.id.title2);
			TextView subTitle2 = (TextView) view2.findViewById(R.id.subTitle2);
			TextView time2 = (TextView) view2.findViewById(R.id.time2);
			title2.setText(datas.get(position).TITLE);
			subTitle2.setText(datas.get(position).SUBTITLE);
			time2.setText(datas.get(position).SHOWTIME);

			return view2;
		}

	}

}
</span>


        activity_main

 

 

 

<span style="font-size:18px;"><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="com.bwie.test.MainActivity" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" >

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="center"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/t1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#ccc"
                android:gravity="center"
                android:padding="10dp"
                android:text="本社介绍" />

            <TextView
                android:id="@+id/t11"
                android:layout_width="match_parent"
                android:layout_height="2dp"
                android:background="#ff0000" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/t2"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#ccc"
                android:gravity="center"
                android:padding="10dp"
                android:text="履行职责" />

            <TextView
                android:id="@+id/t22"
                android:layout_width="match_parent"
                android:layout_height="2dp"
                 
                android:gravity="center" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:orientation="vertical" >

            <TextView
                android:id="@+id/t3"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="#ccc"
                android:gravity="center"
                android:padding="10dp"
                android:text="自我建设" />

            <TextView
                android:id="@+id/t33"
                android:layout_width="match_parent"
                android:layout_height="2dp"
                
                android:gravity="center" />
        </LinearLayout>
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </android.support.v4.view.ViewPager>

</LinearLayout></span>

 

 

 

 

 

          fragment1布局

 

<span style="font-size:18px;"><?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" >
    

    <ListView 
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView1"
        ></ListView>
</LinearLayout>
</span>


              fragment2布局

 

 

 

  

<span style="font-size:18px;"><?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" >

    <ListView
        android:id="@+id/listView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</LinearLayout></span>

 

 

 

                    fragment3布局

 

 

<span style="font-size:18px;"><?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" >
    

</LinearLayout></span>


                      list_item1适配器布局

 

    

<span style="font-size:18px;"><?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="horizontal" >

    <ImageView
        android:id="@+id/img"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="100dp"
        android:src="@drawable/ic_launcher" />

    <LinearLayout 
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="100dp"
        android:orientation="vertical"
        >
        <TextView
        android:id="@+id/title1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="标题"
        android:textColor="#000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/subTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="内容" />
        <LinearLayout 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            
            <TextView 
                android:id="@+id/author1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="作者"
                />
            <TextView 
                android:id="@+id/time1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="时间"
                />
        </LinearLayout>
    </LinearLayout>

</LinearLayout></span>

 

 

 

 

      list_item2适配器布局

 

 

<span style="font-size:18px;"><?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="horizontal" >

     

    <LinearLayout 
        android:layout_width="0dp"
        android:layout_weight="2"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <TextView
        android:id="@+id/title2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="标题"
        android:textColor="#000"
        android:textSize="18sp" />

    <TextView
        android:id="@+id/subTitle2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="内容" />
        <LinearLayout 
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            >
            
             
            <TextView 
                android:id="@+id/time2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="时间"
                />
        </LinearLayout>
    </LinearLayout>

</LinearLayout></span>

   

 

                            ****************************************记得加上网络权限************************
 

          

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值