效果图:
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/fragmentTitle"
android:name="com.example.beck.test.FragmentDemo.TitleFragment"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<fragment
android:id="@+id/fragmentContent"
android:name="com.example.beck.test.FragmentDemo.ContentFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="@id/fragmentTitle" />
</RelativeLayout>
MainActivity.java:
public class FragmentAty extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_fragment);
}
}
ContentFragment.java:
public class ContentFragment extends Fragment {
private ImageButton imgbtn;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.contentfragment,container,false);
imgbtn= (ImageButton) view.findViewById(R.id.imgbtnWeichat);
imgbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"I am ImageButton in TitleFragment !",Toast.LENGTH_SHORT
).show();
}
});
return view;
}
}
fragment_content.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageButton
android:id="@+id/imgbtnWeichat"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@mipmap/weichat"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="使用Fragment做主面板WeiChat"
style="@style/TextViewStyle" />
</LinearLayout>
TitleFragment和其布局省略