片段和getFragmentManager以及版本兼容性

时间:2017-03-16 16:40:33

标签: java android android-fragments

我对编码很新,并且到处寻找,但可能看起来不正确。我遇到了占位符问题。不确定是否支持片段管理器,因为它是v7支持

Error:(21, 32) error: no suitable method found for add(int,ListFragment)
method FragmentTransaction.add(Fragment,String) is not applicable
(argument mismatch; int cannot be converted to Fragment)
method FragmentTransaction.add(int,Fragment) is not applicable
(argument mismatch; ListFragment cannot be converted to Fragment)

这是我的代码

 package chris.smellslikebacon;




 import android.app.FragmentManager;
 import android.app.FragmentTransaction;
 import android.os.Bundle;
 import android.support.v7.app.AppCompatActivity;
 import android.widget.Toast;

 public class MainActivity extends AppCompatActivity implements            ListFragment.OnRecipeSelectedInterface {

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

    ListFragment savedFragment = (ListFragment) getSupportFragmentManager().findFragmentById(R.id.placeholders);
    if(savedFragment == null) {
        ListFragment fragment = new ListFragment();
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.add(R.id.placeholders, fragment);
        fragmentTransaction.commit();
    }
}
@Override
public void onListRecipeSelected(int index) {
Toast.makeText(MainActivity.this, Recipes.names[index],      Toast.LENGTH_SHORT).show();    }
}

1 个答案:

答案 0 :(得分:0)

我认为您应该使用getSupportFragmentManager代替支持:

FragmentManager fragmentManager = getSupportFragmentManager();

希望这有帮助。