我有一个带有FrameLayout的基本片段,我想在派生的片段中使用这个布局,并为它添加一个onTouchListener。
BaseFragment.java
public class BaseFragment extends Fragment {
protected FrameLayout baseFrameLayout;
protected View baseView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
baseView = inflater.inflate(R.layout.fragment_base, container, false);
baseFrameLayout = (FrameLayout) baseView.findViewById(R.id.frameLayout);
return baseView;
}
}
fragment_base.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frameLayout"
android:clickable="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
DerivedFragment.java
public class DerivedFragment extends BaseFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
baseFrameLayout.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// do something
return true;
}
});
return baseView;
}
}
不幸的是,当我触摸FrameLayout
时,没有执行onTouchListener修改
最后,我以这种方式将DerivedFragment添加到另一个Fragment:
OverViewFragment.java
public class OverViewFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.fragment_overView, container, false);
Fragment derivedFragment = new DerivedFragment();
FragmentTransaction devTrans = getChildFragmentManager().beginTransaction();
devTrans.add(R.id.derivedFragmentId, derivedFragment).commit();
Fragment footerFragment = new FooterFragment();
FragmentTransaction statTrans = getChildFragmentManager().beginTransaction();
statTrans.add(R.id.footerFragmentId, footerFragment).commit();
return view;
}
}
fragment_overView.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/derivedFragmentId"
android:layout_above="@+id/footerFragmentId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:gravity="center"
/>
<FrameLayout
android:id="@+id/footerFragmentId"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
答案 0 :(得分:1)
我之前从未使用过空的布局。所以我只是测试了它。
使用以下行,布局不可见且不会获得点击次数:
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
以下几行有效:
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
因此,要么制作布局match_parent
,要么在里面添加视图。