我是android编程的初学者。我想用片段编写一个程序,我阅读了本教程(http://www.mysamplecode.com/2012/08/android-fragment-example.html)并编写了它,但是当我运行程序时,程序有编译器错误!错误与 add() 和 replace() 函数有关。
我在下面写了 AndroidFragmentActivity 类,请阅读并帮助我。
AndoridFragmentActivity.java:
package com.appfragmentarray;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.appfragmentarray.ListFragment.OnURLSelectedListener;
public class AndroidFragmentActivity extends Activity implements OnURLSelectedListener{
boolean detailPage = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v("AndroidFragmentActivity", "onCreate()");
Log.v("AndroidFragmentsavedInstanceState", savedInstanceState == null ? "true" : "false");
setContentView(R.layout.activity_main);
if(savedInstanceState == null) {
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ListFragment listFragment = new ListFragment();
ft.add(R.id.displayList, listFragment, "List_Fragment");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
if(findViewById(R.id.displayDetail) != null){
detailPage = true;
getFragmentManager().popBackStack();
DetailFragment detailFragment = (DetailFragment) getFragmentManager().findFragmentById(R.id.displayDetail);
if(detailFragment == null){
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
detailFragment = new DetailFragment();
ft.replace(R.id.displayDetail, detailFragment, "Detail_Fragment1");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
}
}
}
public void onURLSelected(String URL) {
Log.v("AndroidFragmentActivity",URL);
if(detailPage){
DetailFragment detailFragment = (DetailFragment)
getFragmentManager().findFragmentById(R.id.displayDetail);
detailFragment.updateURLContent(URL);
}
else{
DetailFragment detailFragment = new DetailFragment();
detailFragment.setURLContent(URL);
android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.displayList, detailFragment, "Detail_Fragment2");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
}
}
错误是:
无法从 Fragment 转换为 DetailFragment
FragmentTransaction 类型中的方法 add(int, Fragment, String) 不适用于参数 (int, ListFragment, String)
FragmentTransaction 类型中的方法 replace(int, Fragment, String) 不适用于参数 (int, DetailFragment, String)
我该如何解决这个问题?谢谢。