為LinearLayout添加Fragment效果
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIwczX0xiRGZkRGZ0Xy9GbvNGL2EzXlpXazxSPRdVY2pESaVnRygFcohVYsFjMMBjVtJWd0ckW65UbM5WOHJWa5kHT20ESjBjUIF2X0hXZ0xCMx81dvRWYoNHLrdEZwZ1Rh5WNXp1bwNjW1ZUba9VZwlHdssmch1mclRXY39CXldWYtlWPzNXZj9mcw1ycz9WL49zZuBnLxcTO5ADO1ATM4IjNwkTMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)
1、建立Fragment
public class Fragment1 extends Fragment {
public static Fragment1 getInstance(Bundle bundle) {
Fragment1 fg = new Fragment1();
fg.setArguments(bundle);
return fg;
}
protected View contentView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
contentView = inflater.inflate(R.layout.fragment1, container, false);
initViews();
return contentView;
}
public void initViews(){
TextView textView =(TextView)contentView.findViewById(R.id.f1te);
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getContext(),"ssssf1",Toast.LENGTH_SHORT).show();
}
});
}
}
附activity_main.xml
<LinearLayout
android:id="@+id/music_control"
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_alignParentBottom="true"
android:padding="5dp"
android:orientation="horizontal"
android:background="@color/grey">
</LinearLayout>
2、添加方法
/**
* 用于設定底部的控制音樂播放的fragment
*/
private void setBottomController() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.music_control,new Fragment1());
transaction.commit();
}