如果您想要有关如何将活动切换为片段的示例参考。我正在添加我的示例活动和片段。
// Now this is the Activity class which I have to convert to fragments
TestActivity.java
public class TestActivity extends Activity implements OnClickListener {
private static EditText edittext;
private static Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
edittext = (EditText) findViewById(R.id.et_price);
button = (Button) findViewById(R.id.bt_bold);
button.setOnClickListener(this);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.equals(button)) {
edittext.setText("Arshad's Test App");
}
}
}
现在要将 TestActivity 转换为 Fragment,我们需要将其分为两个类。TestActivity.java 和 TestFragment.java
// Now the TestActivity will extend the FragmentActivity instead of Activity
public class TestActivity extends FragmentActivity {
private TestFragment testFragment_object;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
testFragment_object = new TestFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, testFragment_object).commit();
} else {
// Or set the fragment from restored state info
testFragment_object = (TestFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
}
现在,Fragment 类将包含要在之前包含在 Activity 类中的类中执行的布局和操作的所有代码。
TestFragment.java
public class TestFragment extends Fragment implements OnClickListener {
private static EditText edittext;
private static Button button;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_first, container, false);
edittext = (EditText) view.findViewById(R.id.et_price);
button = (Button) view.findViewById(R.id.bt_bold);
button.setOnClickListener(this);
return view;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.equals(button)) {
edittext.setText("Arshad's Test App");
}
}
}