当我启动我的应用程序时,我得到以下异常:
java.lang.RuntimeException:com.demo.mtin.mtin.MainActivity必须实现OnFragmentInteractionListener
有人可以帮我吗? 我需要在MainActivity中添加哪些代码?
我有两个空白片段:PopularFragment和RatedFragment
MainActivity如下:
public class MainActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private MoviesAdapter mAdapter;
@Override
protected void onResume() {
SharedPreferences sharedPref = getBaseContext().getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);
String order = sharedPref.getString("order", "popular");
if (order.equals("popular")) {
getPopularMovies();
} else {
getTopRatedMovies();
}
super.onResume();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// uci i postaviti order -> popular
Log.d("NESTO", "NESTO-onCreate");
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
}
}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PageAdapter adapter = new PageAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
答案 0 :(得分:0)
这实际上是一个非常直接的错误消息,请执行此操作:
public class MainActivity extends AppCompatActivity implements PopularFragment.OnFragmentInteractionListener, RatedFragment.OnFragmentInteractionListener { ...
@Override
public void onFragmentInteraction(Uri uri) {
}}
您必须指明您的活动实现了片段的接口,然后实现它(尽管可能无效)。
在你的片段中有以下内容:
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}