Fragment的创建方式,怎么设置用Activity去控制呢?难道把Fragment当做Activity来用吗?
我自己创建了一个Fragment的小Demo,现在项目做重构用fragment替换已有的Activity.主归正传:
两个问题:1. 在<fragment>标签下定义了class或name属性后是不是就相当于new 了一个自定义的Fragment?因为下面代码中在Activity里add时Fragment中的onCreateView调用了两遍,也就是new了两个同样的碎片. 如何不让它在启动时不去创建(或者说class=‘com.*’时不去new). 想达到Activity自己去控制Fragment的效果。
2.Fragment替换Activity时,是在Activity中一个个的Fragment的replace吗?或者是其它的怎么实现跳转的?
代码:
Activity:
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
// FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
// Fragment headerFragment = HeaderFragment.newInstance("标题");
// Fragment contentFragment = ContentFragment.newInstance("内容");
// Fragment footFragment = FootFragment.newInstance("签名");
// ft.add(R.id.titles, headerFragment);
// ft.add(R.id.content, contentFragment);
// ft.add(R.id.footer, footFragment);
// ft.commit();这段内容在这里多余,不加时正常,加了反而加了两层在上面了。
}
}
}
Fragment:
public class ContentFragment extends Fragment {
public static ContentFragment newInstance(String src) {
ContentFragment f = new ContentFragment();
// Supply index input as an argument.
Bundle args = new Bundle();
args.putString("index", src);
f.setArguments(args);
return f;
}
public String getShownContent() {
return getArguments().getString("index");
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.i("sys", "Content----CreateView");
TextView text1 = new TextView(getActivity());
LinearLayout layout1 = new LinearLayout(getActivity());
layout1.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
int padding = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 4, getActivity().getResources().getDisplayMetrics());
text1.setPadding(padding, padding, padding, padding);
layout1.addView(text1);
// text.setText(getShownContent());第一次(也就是自动new时)调getShownContent()时空指针
text1.setText("bbbbbbbbbbb");
return layout1;
}
}
其它两个略,与这个差不多.
Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<fragment
android:id="@+id/titles"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
class="com.example.fragmentproject.fragment.HeaderFragment" />
<fragment
android:id="@+id/content"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="2"
class="com.example.fragmentproject.fragment.ContentFragment" />
<fragment
android:id="@+id/footer"
android:layout_width="fill_parent"
android:layout_height="0dip"
android:layout_weight="1"
class="com.example.fragmentproject.fragment.FootFragment" />
</LinearLayout>
------解决方案--------------------