片段可以扩展抽象类吗?

时间:2016-02-26 02:41:59

标签: android android-fragments

抽象类扩展了android.support.v4.app.Fragment,因此MyFragment可以作为片段执行某些操作。但是在扩展抽象类时,MyFragment无法转换为Fragment。 片段如何扩展抽象类?

MainActivity.java

public class MainActivity extends AppCompatActivity{
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        FragmentManager fm = getSupportFragmentManager();
        int id = item.getItemId();
        switch (id){
        case (R.id.nav_bin):
            fm.beginTransaction().replace(R.id.fragment_content, new MyFragment()).commit();
            break;
         ...
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

MyFragment.java

public class MyFragment extends BaseActivity implements ...{
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View baseView = inflater.inflate(R.layout.fragment_content, container, false);
        return baseView;
    }

}

BaseActivity.java

public abstract class BaseActivity extends Fragment implements ...{
}

1 个答案:

答案 0 :(得分:2)

...BaseActivity extends Fragment...

首先,请不要使用这个命名惯例 - 这非常令人困惑。请尝试使用BaseFragmentBaseActivity表示它从Activity类延伸。

其次,您的问题可能源于混合android.app.Fragment导入和android.support.v4.app.Fragment导入。确保您的BaseFragment班级正在导入android.support.v4.app.Fragment而不是android.app.Fragment