我正在創建Material Design選項卡視圖。我在主活動的addFragment方法後出現錯誤。這是我得到的錯誤。Android - 錯誤的第一個參數類型和'android.supportv4.app.Fragment'
Wrong 1st argument type. Found: 'com.example.sa.tabproject.LatestPromoFragment, ' android.supportv4.app.Fragment'
我MainActivity.java
import android.app.Activity;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.support.v7.widget.Toolbar;
import android.app.Fragment;
public class MainActivity extends AppCompatActivity {
Toolbar toolbar;
TabLayout tabLayout;
ViewPager viewPager;
ViewPagerAdapter viewPagerAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar=(Toolbar)findViewById(R.id.toolBar);
setSupportActionBar(toolbar);
tabLayout=(TabLayout)findViewById(R.id.tab_layout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
viewPagerAdapter= new ViewPagerAdapter(getSupportFragmentManager());
viewPagerAdapter.addFragment(new LatestPromoFragment(),"Latest Promos");
viewPagerAdapter.addFragment(new MapViewFragment(),"Map View");
viewPager.setAdapter(viewPagerAdapter);
tabLayout.setupWithViewPager(viewPager);
}}
ViewPagerAdapter.java
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.util.ArrayList;
import java.util.List;
public class ViewPagerAdapter extends FragmentPagerAdapter {
ArrayList<Fragment> fragment = new ArrayList<>();
ArrayList<String> tabTitles= new ArrayList<>();
public void addFragment(Fragment fragment,String titles){
this.fragment.add(fragment);
this.tabTitles.add(titles);
}
public ViewPagerAdapter(FragmentManager fm){
super(fm);
}
@Override
public Fragment getItem(int position) {
return fragment.get(position);
}
@Override
public int getCount() {
return fragment.size();
}
@Override
public CharSequence getPageTitle(int position) {
return tabTitles.get(position);
}}
我進口幾個片段類的MainActivity.java。但它不能解決這個錯誤。
@DanielNugent感謝您指出我將編輯答案:) – dex