主类:
package com.wondersoft.criminalintent;
import android.os.Bundle;
import android.support.v4.app.*;
import android.view.Menu;
public class CrimeActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime);
FragmentManager fm = getSupportFragmentManager();//生成fragmentManager 管理器
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if(fragment == null) {
fragment = new Fragment();
System.out.println("nihao");
fm.beginTransaction().add(R.id.fragmentContainer, fragment).commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.crime, menu);
return true;
}
}
Fragment类
package com.wondersoft.criminalintent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCrime = new Crime();
}
//生成fragment师徒的布局
/*在 onCreateView(...) 方 法 中 , fragment 的 视 图 是 直 接 通 过 调 用 LayoutInflater.
inflate(...)方法并传入布局的资源ID生成的。第二个参数是视图的父视图,通常我们需要父
视图来正确配置组件。第三个参数告知布局生成器是否将生成的视图添加给父视图
*/
public View onCreateView(LayoutInflater inflater,ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime,parent,false);
mTitleField = (EditText)v.findViewById(R.id.crime_title);
//为编辑框没TitleField添加监听器
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c,int start,int before,int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c,int start,int before,int count) {
//空
}
public void afterTextChanged(Editable c) {
}
});
return v;
}
}
frament.xml
<?xml version="1.0" encoding="utf-8"?>
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:hint="@string/crime_title_hint">
主.xml
<?xml version="1.0" encoding="utf-8"?>
android:name="com.wondersoft.criminalintent.CrimeFragment"
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@string/crime_title_hint">
fragment显示不出来是什么原因啊