Android studio Fragment用法

利用Fragment类将程序界面分成数个区域,这些不同区域的程序界面可以各自显示或隐藏,以适应不同屏幕尺寸的设备,这种Fragment类型的程序接口具有以下特性:

   
1. 程序运行界面可以由多个Fragment组成

 
2. 每一个Fragment都有各自独立的运行状态


3. 在程序运行的过程中,Fragment可以动态加入和移除

 
在程序中使用Fragment需要完成以下几个步骤:


1.在程序项目中新增一个继承自Fargmenr的新类

2.在步骤一的新类中加上需要处理的状态转换方法,例如:

(1)omCreat()

   当Fragment刚被建立时会运行这个方法,例如我们可以在这个方法中完成变量的初始设置。

(2)onCreatView()

        当Fragment将要显示在屏幕上时会运行这个方法,我们必须在这个方法中设置好Fragment所用的接口

(3)onPause()

        当Fragment要从屏幕上消失时会运行这个方法,我们可以在这个方法中存储用户的操作状态和资料,以便下次Fragment重新显示在屏幕上时,用户可以继续 之前的工作。

3.建立Fragment使用的界面布局文件,Fragment的操作接口同样是由程序项目中的res/layout文件夹下的接口布局文件来定义,只是我们必须在Fragment的onCreateView()方法中进行接口的设置,而不是在onCreate()中进行,例如:


Public class MyFragment extends Fragment{

@Override

Publish View onCreatView(LayoutInflater inflater,ViewGroup

Container,Bundle savedInstanceState){

Return inflater.inflate(R.layout.fragment_layout,container,false);

     }

}

我们利用inflater对象的inflate()方法取得res/layout/fragment_layout.xml接口布局文件,并将最后的结果传回给系统,这样就完成了Fragment的接口设置。

4.把前面建立好的Fragment类加入程序中,我们可以利用<Fragment>标签,在主程序的接口布局文件中完成加入Fragment的动作

使用<fragment>标签时要注意以下几点:

(1)fragment的开头字母必须小写。

(2)每一个<fragment>标签都要设置android:id属性

(3)<fragment>标签的android:name属性是指定所使用的Fragment类,且必须加上完整的组件路径名称

(4)在<fragment>标签中可以使用android:layout_weight属性,以设置比例的方式控制每一个Fragment所占的屏幕宽度,此时android:layout_width属性必须设置为“0dp".
 

发布了8 篇原创文章 · 获赞 2 · 访问量 3968
展开阅读全文

fragment向fragment传递数据问题

03-28

fragment向fragment传递数据问题,我想从MsgFragment这里 点击之后获取城市名传到下一个跳转的AttractionsFragment并获取String city,我试过用javabean的SET GET方法没用。IndexFragment这个方法是写fragment跳转代码的。 有没有人帮下额。难住我很久了。 项目地址链接:https://pan.baidu.com/s/1VbWzHWg26cJ8iKNcIFlSeQ 提取码:vu86 ``` public class IndexFragment extends Fragment implements ChangeFragment { private Fragment fragmentMsg; private Fragment fragmentColl; private Fragment fragmentAction; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view1 = LayoutInflater.from(getContext()).inflate(R.layout.fragment_index, container, false); return view1; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); fragmentMsg = MsgFragment.newInstance(this); fragmentColl = AttractionsFragment.newInstance(this); fragmentAction=AttractionsContentFragment.newInstance(this); changeResult(); } @Override public void changeFragment() { getChildFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.fl_content,fragmentColl).commit(); } @Override public void changeResult() { getChildFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.fl_content,fragmentMsg).commit(); } @Override public void changeAttractionsContent() { getChildFragmentManager() .beginTransaction() .addToBackStack(null) .replace(R.id.fl_content,fragmentAction).commit(); } } ``` ``` public class MsgFragment extends Fragment { View view; private int i; private String str; private String[] mVals = new String[]{ "南宁市","柳州市","桂林市" ,"梧州市" ,"北海市","防城港市","钦州市","贵港市","玉林市","百色市","贺州市","河池市","来宾市","崇左市"}; private LayoutInflater mInflater; private FlowLayout mFlowLayout; private CityEntity cityEntity ; private static ChangeFragment mChange; public static MsgFragment newInstance(ChangeFragment changeFragment) { mChange = changeFragment; Bundle args = new Bundle(); MsgFragment fragment = new MsgFragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mInflater = LayoutInflater.from(getContext()); } public MsgFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_msg, container, false); mFlowLayout = view.findViewById(R.id.id_flowlayout); initData(); return view; } public void initData() { /** * 找到搜索标签的控件 */ for (i = 0; i < mVals.length; i++) { final TextView tv = (TextView) mInflater.inflate( R.layout.search_label_tv, mFlowLayout, false); tv.setText(mVals[i]); str = tv.getText().toString(); //点击事件 tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { try { switch (((TextView) v).getText().toString()) { case "南宁市": String a="南宁市"; changeToAnotherFragment(); break; case "柳州市": cityEntity.setCity("柳州市"); changeToAnotherFragment(); break; case "桂林市": cityEntity.setCity("桂林市"); changeToAnotherFragment(); break; case "梧州市": cityEntity.setCity("梧州市"); changeToAnotherFragment(); break; case "北海市": cityEntity.setCity("北海市"); changeToAnotherFragment(); break; case "防城港市": cityEntity.setCity("防城港市"); changeToAnotherFragment(); break; case "钦州市": cityEntity.setCity("钦州市"); changeToAnotherFragment(); break; case "贵港市": cityEntity.setCity("贵港市"); changeToAnotherFragment(); break; case "玉林市": cityEntity.setCity("玉林市"); changeToAnotherFragment(); break; case "百色市": cityEntity.setCity("百色市"); changeToAnotherFragment(); break; case "贺州市": cityEntity.setCity("贺州市"); changeToAnotherFragment(); break; case "河池市": cityEntity.setCity("河池市"); changeToAnotherFragment(); break; case "来宾市": cityEntity.setCity("来宾市"); changeToAnotherFragment(); break; case "崇左市": cityEntity.setCity("崇左市"); changeToAnotherFragment(); break; default: break; } } catch (Exception e) { e.printStackTrace(); } } }); mFlowLayout.addView(tv);//添加到父View } } @SuppressLint("ResourceType") private void changeToAnotherFragment() { mChange.changeFragment(); } } ``` ``` public class AttractionsFragment extends Fragment { private MyListView attr_lv; private JSONArray attr_array; private ImageLoaderConfiguration configuration; public DisplayImageOptions imageOptions; private Handler handler; private int msggg=0; public String city; private static ChangeFragment mChange; public static AttractionsFragment newInstance(ChangeFragment changeFragment) { mChange = changeFragment; Bundle args = new Bundle(); AttractionsFragment fragment = new AttractionsFragment(); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { //获取fragment的layout View view = inflater.inflate(R.layout.fragment_attractions, container, false); //对recycleview进行配置 return view; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); attr_lv=view.findViewById(R.id.frag_attractions); configuration = ImageLoaderConfiguration.createDefault(getActivity()); ImageLoader.getInstance().init(configuration); imageOptions = DisplayImageOptions.createSimple(); initData(); handler=new Handler(){ @Override public void handleMessage(Message msg) { if(msg.what ==msggg){ attr_lv.setAdapter(new AttracListAdapter(getActivity())); attr_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getActivity(),String.valueOf(position),Toast.LENGTH_SHORT).show(); try { JSONObject object1=attr_array.getJSONObject(position); String a= object1.getString("foodtitle"); String b=object1.getString("foodcontentimg"); System.out.println(a); System.out.println(b); } catch (JSONException e) { e.printStackTrace(); } } }); } } }; } private void initData() { new Thread(){ public void run() { String url = DocUtil.attractions_list; System.out.println(city); OkHttpClient okHttpClient = new OkHttpClient(); String token= CacheUtils.getString(getActivity(), "token", ""); RequestBody body = new FormBody.Builder() .add("token",token) .add("city",city) .build(); Request request = new Request.Builder() .url(url) .post(body) .build(); Call call = okHttpClient.newCall(request); try { Response response = call.execute(); //System.out.println(response.body().string()); try { final String string=response.body().string(); final JSONObject object=new JSONObject(string); attr_array=object.getJSONArray("attractionsList"); System.out.println(attr_array); if(attr_array.length()>0) { try { Message msg = new Message(); msg.what = msggg; handler.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } }else { Toast.makeText(getActivity(), "无数据", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } catch (IOException e) { e.printStackTrace(); } } }.start(); } class AttracListAdapter extends BaseAdapter { private Context mContext; public AttracListAdapter(Context mContext) { super(); this.mContext = mContext; } @Override public int getCount() { // TODO Auto-generated method stub return attr_array.length(); } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate( R.layout.attractions_item, parent, false); try { JSONObject object=attr_array.getJSONObject(position); TextView tvss1=convertView.findViewById(R.id.attrac_title); TextView tvss2=convertView.findViewById(R.id.attrac_content); tvss1.setText(object.getString("attractionstitle")); tvss2.setText("地址:"+object.getString("attractionscontent")); ImageView img=convertView.findViewById(R.id.attrac_img); ImageLoader.getInstance().displayImage(DocUtil.base_url+ object.getString("attrac_img"), img, imageOptions); } catch (Exception e) { e.printStackTrace(); } } return convertView; } } } ``` ``` public interface ChangeFragment { void changeFragment(); void changeResult(); void changeAttractionsContent(); } ``` 问答

Android Studio 升级到3.5的错误

09-10

Android Studio 弹出升级的消息框,手贱点了一下 ,然后升级到了Android Studio3.5,升级完成后打开Android Studio ,提示升级失败,查看错误为: java.lang.UnsatisfiedLinkError: org.sqlite.core.NativeDB._open_utf8([BI)V at org.sqlite.core.NativeDB._open_utf8(Native Method) at org.sqlite.core.NativeDB._open(NativeDB.java:71) at org.sqlite.core.DB.open(DB.java:174) at org.sqlite.core.CoreConnection.open(CoreConnection.java:220) at org.sqlite.core.CoreConnection.<init>(CoreConnection.java:76) at org.sqlite.jdbc3.JDBC3Connection.<init>(JDBC3Connection.java:25) at org.sqlite.jdbc4.JDBC4Connection.<init>(JDBC4Connection.java:24) at org.sqlite.SQLiteConnection.<init>(SQLiteConnection.java:45) at org.sqlite.JDBC.createConnection(JDBC.java:114) at org.sqlite.JDBC.connect(JDBC.java:88) at java.sql.DriverManager.getConnection(DriverManager.java:664) at java.sql.DriverManager.getConnection(DriverManager.java:270) at com.android.tools.deployer.SqlApkFileDatabase.<init>(SqlApkFileDatabase.java:62) at com.android.tools.deployer.SqlApkFileDatabase.<init>(SqlApkFileDatabase.java:50) at com.android.tools.idea.run.DeploymentService.<init>(DeploymentService.java:56) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:423) at org.picocontainer.defaults.InstantiatingComponentAdapter.newInstance(InstantiatingComponentAdapter.java:193) at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.doGetComponentInstance(CachingConstructorInjectionComponentAdapter.java:92) at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.instantiateGuarded(CachingConstructorInjectionComponentAdapter.java:66) at com.intellij.util.pico.CachingConstructorInjectionComponentAdapter.getComponentInstance(CachingConstructorInjectionComponentAdapter.java:48) at com.intellij.openapi.components.impl.ServiceManagerImpl$MyComponentAdapter.createAndInitialize(ServiceManagerImpl.java:222) at com.intellij.openapi.components.impl.ServiceManagerImpl$MyComponentAdapter.lambda$getComponentInstance$0(ServiceManagerImpl.java:209) at com.intellij.openapi.components.impl.ServiceManagerImpl$MyComponentAdapter.getComponentInstance(ServiceManagerImpl.java:213) at com.intellij.util.pico.DefaultPicoContainer.getLocalInstance(DefaultPicoContainer.java:246) at com.intellij.util.pico.DefaultPicoContainer.getComponentInstance(DefaultPicoContainer.java:213) at com.intellij.openapi.components.ServiceManager.doGetService(ServiceManager.java:52) at com.intellij.openapi.components.ServiceManager.getService(ServiceManager.java:30) at com.android.tools.idea.run.DeploymentService.getInstance(DeploymentService.java:48) at com.android.tools.idea.deploy.DeployActionsInitializer.updateDeployableProvider(DeployActionsInitializer.java:184) at com.android.tools.idea.deploy.DeployActionsInitializer.access$000(DeployActionsInitializer.java:56) at com.android.tools.idea.deploy.DeployActionsInitializer$1.projectOpened(DeployActionsInitializer.java:123) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.util.messages.impl.MessageBusConnectionImpl.deliverMessage(MessageBusConnectionImpl.java:114) at com.intellij.util.messages.impl.MessageBusImpl.doPumpMessages(MessageBusImpl.java:393) at com.intellij.util.messages.impl.MessageBusImpl.pumpWaitingBuses(MessageBusImpl.java:354) at com.intellij.util.messages.impl.MessageBusImpl.pumpMessages(MessageBusImpl.java:343) at com.intellij.util.messages.impl.MessageBusImpl.sendMessage(MessageBusImpl.java:320) at com.intellij.util.messages.impl.MessageBusImpl.access$100(MessageBusImpl.java:29) at com.intellij.util.messages.impl.MessageBusImpl$1.invoke(MessageBusImpl.java:192) at com.sun.proxy.$Proxy17.projectOpened(Unknown Source) at com.intellij.openapi.project.impl.ProjectManagerImpl.fireProjectOpened(ProjectManagerImpl.java:780) at com.intellij.openapi.project.impl.ProjectManagerImpl.lambda$null$6(ProjectManagerImpl.java:401) at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransactionAndWait$2(TransactionGuardImpl.java:165) at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88) at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransaction$1(TransactionGuardImpl.java:111) at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.doRun(LaterInvocator.java:435) at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.runNextEvent(LaterInvocator.java:419) at com.intellij.openapi.application.impl.LaterInvocator$FlushQueue.run(LaterInvocator.java:403) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764) at java.awt.EventQueue.access$500(EventQueue.java:98) at java.awt.EventQueue$3.run(EventQueue.java:715) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74) at java.awt.EventQueue.dispatchEvent(EventQueue.java:734) at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:757) at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:706) at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:375) at com.intellij.ide.IdeEventQueue.pumpEventsForHierarchy(IdeEventQueue.java:814) at com.intellij.openapi.progress.util.ProgressWindow.startBlocking(ProgressWindow.java:210) at com.intellij.openapi.progress.util.ProgressWindow.startBlocking(ProgressWindow.java:196) at com.intellij.openapi.application.impl.ApplicationImpl.runProcessWithProgressSynchronously(ApplicationImpl.java:609) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcessWithProgressSynchronously(CoreProgressManager.java:454) at com.intellij.openapi.progress.impl.ProgressManagerImpl.runProcessWithProgressSynchronously(ProgressManagerImpl.java:109) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcessWithProgressSynchronously(CoreProgressManager.java:251) at com.intellij.openapi.progress.impl.CoreProgressManager.runProcessWithProgressSynchronously(CoreProgressManager.java:205) at com.intellij.openapi.project.impl.ProjectManagerImpl.loadProjectUnderProgress(ProjectManagerImpl.java:450) at com.intellij.openapi.project.impl.ProjectManagerImpl.openProject(ProjectManagerImpl.java:425) at com.intellij.platform.PlatformProjectOpenProcessor.doOpenProject(PlatformProjectOpenProcessor.java:260) at com.intellij.ide.RecentProjectsManagerBase.doOpenProject(RecentProjectsManagerBase.java:512) at com.intellij.ide.RecentProjectsManagerBase.doReopenLastProject(RecentProjectsManagerBase.java:634) at com.intellij.ide.RecentProjectsManagerBase$MyAppLifecycleListener.appStarting(RecentProjectsManagerBase.java:692) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at com.intellij.util.messages.impl.MessageBusConnectionImpl.deliverMessage(MessageBusConnectionImpl.java:114) at com.intellij.util.messages.impl.MessageBusImpl.doPumpMessages(MessageBusImpl.java:393) at com.intellij.util.messages.impl.MessageBusImpl.pumpWaitingBuses(MessageBusImpl.java:354) at com.intellij.util.messages.impl.MessageBusImpl.pumpMessages(MessageBusImpl.java:343) at com.intellij.util.messages.impl.MessageBusImpl.sendMessage(MessageBusImpl.java:320) at com.intellij.util.messages.impl.MessageBusImpl.access$100(MessageBusImpl.java:29) at com.intellij.util.messages.impl.MessageBusImpl$1.invoke(MessageBusImpl.java:192) at com.sun.proxy.$Proxy63.appStarting(Unknown Source) at com.intellij.idea.IdeaApplication$IdeStarter.lambda$main$1(IdeaApplication.java:388) at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88) at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransaction$1(TransactionGuardImpl.java:111) at com.intellij.openapi.application.TransactionGuardImpl.submitTransaction(TransactionGuardImpl.java:120) at com.intellij.openapi.application.TransactionGuard.submitTransaction(TransactionGuard.java:121) at com.intellij.idea.IdeaApplication$IdeStarter.main(IdeaApplication.java:386) at com.intellij.idea.IdeaApplication.lambda$run$1(IdeaApplication.java:220) at com.intellij.openapi.application.TransactionGuardImpl.performUserActivity(TransactionGuardImpl.java:195) at com.intellij.idea.IdeaApplication.run(IdeaApplication.java:220) at com.intellij.idea.IdeaApplication.lambda$initApplication$0(IdeaApplication.java:77) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764) at java.awt.EventQueue.access$500(EventQueue.java:98) at java.awt.EventQueue$3.run(EventQueue.java:715) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:74) at java.awt.EventQueue.dispatchEvent(EventQueue.java:734) at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:349) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:205) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) 操作系统是Win10 专业版 64位。 以为是我的老版本导致的程序不对,然后把和Android Studio有关的文件都删了,重新安装,安装好了以后可以用了,但是关了AS,再重新打开AS,又开始报上面的错误,有没有遇到这个问题的?如何来解决这个问题? ------------------------------------------------------------》》》》》 很白痴的问题,以及个人的习惯导致的,使用管理员权限打开就好了,AS会在AppData/Local 中创建一个临时的sqlite 数据访问的dll,不是管理员权限访问不了,就导致了这个错误。 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览