15 ActionBar.Tab 以及保存fragment对象 代码案例
API 21弃用
values 中 string文件源码:
<?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">Day15_Actionbar_demo4</string> <string name="action_settings">Settings</string> <string name="hello_world">Hello world!</string> <!-- nums 对应网址 --> <string-array name="paths"> <item>http://c.m.163.com/nc/article/headline/T1348647853363/0-20.html</item> <item>http://c.m.163.com/nc/article/list/T1348648517839/0-20.html</item> <item>http://c.m.163.com/nc/article/list/T1348649079062/0-20.html</item> <item>http://c.m.163.com/nc/article/list/T1348648756099/0-20.html</item> </string-array> <!--由于地址返回json的根目录中只有这个名字 所以写死每个地址的根目录名 就可以只用一个解析了 --> <string-array name="nums"> <item>T1348647853363</item> <item>T1348648517839</item> <item>T1348649079062</item> <item>T1348648756099</item> </string-array> </resources>
activity_main.xml源码:
<!-- 直接作为fragment的容器 --> <RelativeLayout 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:id="@+id/rl_fragment_id" tools:context=".MainActivity" > </RelativeLayout>
fragment填充对象源码:
<?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/lv" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
MainActivity.java:
package com.qf.day15_actionbar_demo4; import java.util.HashMap; import java.util.Map; import com.qf.day15_actionbar_demo4.fragment.MyFragment; import android.os.Bundle; import android.app.ActionBar; import android.app.ActionBar.Tab; import android.app.ActionBar.TabListener; import android.app.Activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.util.Log; import android.view.Menu; import android.widget.Toast; public class MainActivity extends Activity implements TabListener{ private Map<Integer, Fragment> fragmentMap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //将集合实例化 fragmentMap = new HashMap<Integer, Fragment>(); //获取ActionBar ActionBar actionBar = getActionBar(); //设置导航模式 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); ActionBar.Tab tab = actionBar.newTab(); tab.setIcon(android.R.drawable.ic_menu_add); tab.setText("头条"); tab.setTabListener(this); actionBar.addTab(tab, true); tab = actionBar.newTab(); tab.setIcon(android.R.drawable.ic_menu_call); tab.setText("娱乐"); tab.setTabListener(this); actionBar.addTab(tab); tab = actionBar.newTab(); tab.setIcon(android.R.drawable.ic_menu_camera); tab.setText("财经"); tab.setTabListener(this); actionBar.addTab(tab); tab = actionBar.newTab(); tab.setIcon(android.R.drawable.ic_menu_crop); tab.setText("体育"); tab.setTabListener(this); actionBar.addTab(tab); } /** * 选择Tab 事件监听 */ @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub //你点击的是那个Tab 位置获取出来 // int pos = tab.getPosition(); // // MyFragment myFragment = new MyFragment(); // // Bundle bundle = new Bundle(); // bundle.putInt("pos", pos); // myFragment.setArguments(bundle); // // // ft.replace(R.id.rl_fragment_id, myFragment); // //.commit(); 不需要加提交 不需要 添加回退 Log.e("AAA", tab.getPosition()+""); Fragment fragment = fragmentMap.get(tab.getPosition()); if(fragment==null){ fragment = new MyFragment(); Bundle bundle = new Bundle(); bundle.putInt("pos", tab.getPosition()); fragment.setArguments(bundle); fragmentMap.put(tab.getPosition(), fragment); ft.add(R.id.rl_fragment_id, fragment); }else{ ft.show(fragment); } } /** * 重选Tab 双击 */ @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub } /** * 用户选择另一个tab标签的时候触发 */ @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { // TODO Auto-generated method stub //没有被选择的Tab Fragment fragment = fragmentMap.get(tab.getPosition()); Toast.makeText(this, tab.getPosition()+"", 0).show(); if(fragment!=null){ ft.hide(fragment); } } }
MyTask.java 一个异步任务 用于加载网络数据:
package com.qf.day15_actionbar_demo4.asynctask; import java.util.List; import com.qf.day15_actionbar_demo4.interface0.CallBackData; import com.qf.day15_actionbar_demo4.utils.HttpUtils; import com.qf.day15_actionbar_demo4.utils.ParseJson; import android.os.AsyncTask; public class MyTask extends AsyncTask<String, Void, List<String>>{ private String num; private CallBackData callBackData; public MyTask(String num,CallBackData callBackData){ this.num = num; this.callBackData = callBackData; } @Override protected List<String> doInBackground(String... params) { // TODO Auto-generated method stub String jsonStr = HttpUtils.getStr(params[0]); //解析数据 return ParseJson.getData(num, jsonStr); } @Override protected void onPostExecute(List<String> result) { // TODO Auto-generated method stub super.onPostExecute(result); if(result!=null&&result.size()>0){ callBackData.sendData(result); } } }
Fragment.java :
package com.qf.day15_actionbar_demo4.fragment; import java.util.List; import com.qf.day15_actionbar_demo4.R; import com.qf.day15_actionbar_demo4.asynctask.MyTask; import com.qf.day15_actionbar_demo4.interface0.CallBackData; import android.app.Activity; import android.app.Fragment; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; public class MyFragment extends Fragment{ private ListView lv; int pos ; private String path,num;//请求地址 和请求数据的解析需要的对象 @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); pos = getArguments().getInt("pos"); String[] paths = getResources().getStringArray(R.array.paths); String[] nums = getResources().getStringArray(R.array.nums); path = paths[pos]; num = nums[pos]; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub View view = inflater.inflate(R.layout.layout, container, false); lv = (ListView) view.findViewById(R.id.lv); return view; } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); //开启异步任务 请求数据 展示数据 new MyTask(num, new CallBackData() { @Override public void sendData(List<String> list) { // TODO Auto-generated method stub Log.e("AAA", "===path=="+path); Log.e("AAA", "===list=="+list.size()); ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, list); lv.setAdapter(adapter); } }).execute(path); } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); Log.e("AAA", "==onHiddenChanged=="); } }
一个回调接口:
package com.qf.day15_actionbar_demo4.interface0; import java.util.List; public interface CallBackData { public void sendData(List<String> list); }
- 一个网络下载代码:
package com.qf.day15_actionbar_demo4.utils;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtils {
public static String getStr(String path) {
// TODO Auto-generated method stub
HttpURLConnection connection = null;
InputStream is = null;
try {
URL url = new URL(path);
connection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.connect();
if(connection.getResponseCode()==200)
{
is = connection.getInputStream();
StringBuilder sBuilder = new StringBuilder();
byte[] buffer = new byte[1024];
int len = 0;
while ((len=is.read(buffer))!=-1) {
sBuilder.append(new String(buffer,0,len));
}
return sBuilder.toString();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally
{
if(connection!=null)
{
connection.disconnect();
}
if (is!=null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
}
解析json数据工具类:
package com.qf.day15_actionbar_demo4.utils; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpUtils { public static String getStr(String path) { // TODO Auto-generated method stub HttpURLConnection connection = null; InputStream is = null; try { URL url = new URL(path); connection= (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); connection.connect(); if(connection.getResponseCode()==200) { is = connection.getInputStream(); StringBuilder sBuilder = new StringBuilder(); byte[] buffer = new byte[1024]; int len = 0; while ((len=is.read(buffer))!=-1) { sBuilder.append(new String(buffer,0,len)); } return sBuilder.toString(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(connection!=null) { connection.disconnect(); } if (is!=null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } return null; } }