Android — — —动态添加碎片

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android — — —动态添加碎片相关的知识,希望对你有一定的参考价值。



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00">

<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is another fragment"
android:textSize="30sp"
android:layout_gravity="center"/>



</LinearLayout>

技术分享

 

package com.example.fragmenttest;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
* Created by Administrator on 2016/3/2.
*/
public class AnotherRightFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.another_right_fragment,container,false);
return view;
}
}



<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<fragment
android:id="@+id/left_fragment"
android:name="com.example.fragmenttest.LeftFragment"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"/>

<FrameLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:id="@+id/right_layout">

<fragment
android:id="@+id/right_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.fragmenttest.RightFragment"/>

</FrameLayout>

</LinearLayout>

技术分享

 

package com.example.fragmenttest;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity implements View.OnClickListener{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button btn = (Button)findViewById(R.id.button1);
btn.setOnClickListener(this);
}


@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
AnotherRightFragment fragment = new AnotherRightFragment();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.right_layout,fragment);
         //模拟返回栈
         //transaction.addToBackStack(null);
transaction.commit();
break;
default:
break;
}

}
}

技术分享



以上是关于Android — — —动态添加碎片的主要内容,如果未能解决你的问题,请参考以下文章

安卓动态添加碎片

碎片的静态与动态添加(区分手机与平板)

Android中碎片的添加问题

Android第一行代码-Fragment

Android第一行代码-Fragment

在片段中动态添加文本视图