android fragment动态加载,动态添加Fragment
8種機械鍵盤軸體對比
本人程序員,要買一個寫代碼的鍵盤,請問紅軸和茶軸怎么選?
動態添加Fragment
在程序運行時, 根據具體情況來動態地添加Fragment到Activity中.
1 新建 AnotherRightFragment 作為另一個右側Fragment . 并寫好布局文件 another_right_fragment.xml.(黃色背景)import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class extends Fragment{
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.another_right_fragment, container, false);
return view;
}
}
布局文件 another_right_fragment.xml.(黃色背景)
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
android:orientation="vertical" >
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="另一個Fragment"
android:textSize="20sp" />
2 修改 activity_main.xml. 將右側Fragment放在了一個 FrameLayout 中
android:layout_width="match_parent"
android:layout_height="match_parent" >
android:id="@+id/left_fragment"
android:name="com.yassblog.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" />
android:id="@+id/right_layout"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1" >
android:id="@+id/right_fragment"
android:name="com.yassblog.RightFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
3 修改MainActivity 中的代碼import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View v){
switch (v.getId()) {
case R.id.button:
AnotherRightFragment fragment = new AnotherRightFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout, fragment);
transaction.commit();
break;
default:
break;
}
}
}
可以看到,首先我們給左側Fragment中的按鈕注冊了一個點擊事件,然后將動態添加Fragment的邏輯都放在了點擊事件里進行。
4 動態添加Fragment的邏輯創建待添加的Fragment實例。
獲取到 FragmentManager,在Activity中可以直接調用 getFragmentManager()方法得到。
開啟一個事務,通過調用 beginTransaction()方法開啟。
向容器內加入Fragment,一般使用 replace()方法實現,需要傳入容器的 id 和待添加的Fragment實例。
提交事務,調用 commit()方法來完成。
5 這樣就完成了在Activity中動態添加Fragment的功能,重新運行程序,點擊左側按鈕,查看一下效果.
總結
以上是生活随笔為你收集整理的android fragment动态加载,动态添加Fragment的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 开机自动进安全模式怎么办 开机无法正常进
- 下一篇: 海尔灵越5000怎么改win7系统 如何