Evi*_*n1_ 0 android android-layout android-fragments android-activity
我构建会提到,支持多种设备尺寸的应用在这里.
为了处理意见里面的Fragment一个可能要么做查找与findViewById在活动的onCreate()或片段的onViewCreated().
他们都会工作,因为:如果你从Activity你那里做到这一点,你将处理Fragment父母的,你的View意志仍然在其中,如果你从中做到Fragment这将有正常的findViewById行为.
所以...
他们都有自己的优势:
如果你这样做Activity:
如果你这样做Fragment:
有这个问题的方式.在他们讨论有关使用getView或getActivity调用findViewById的Fragment.
接受的答案是:
而不是使用getActivity().findViewById(),你需要getView().findViewById().这样做的原因是,如果您使用活动进行视图查找,那么当具有相同视图ID的多个片段附加到该视图时,您将遇到麻烦
但是,如果你永远不会Fragment在相同的布局中重复使用,那么在查找中这是一个很好的情况Activity吗?
示例布局:
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<fragment
android:id="@+id/f_main"
class=".fragments.MainFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="@layout/fragment_main" />
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
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=".fragments.MainFragment">
<android.support.v7.widget.RecyclerView
android:id="@+id/a_main_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)
您可以RecyclerView从Activity或访问具有id a_main_recycler的ID Fragment.
支持多种设备大小与片段无关.出于其他原因,它们可能是一个好主意,但除此之外.但是一个Activity应该永远不知道片段内部的内容.如果确实如此,那么你完全错过了Fragments的观点,要么根本不应该使用它们,要么重构你的代码.
| 归档时间: |
|
| 查看次数: |
685 次 |
| 最近记录: |