我是Android的新手,我正在遵循达特茅斯的教程。 http://www.cs.dartmouth.edu/~campbell/cs65/lecture08/lecture08.html
我正在关注所有代码和MainActivity.java,
// create the fragments
Fragment mFindFragment = new FindFragment();
Fragment mChatFragment = new ChatFragment();
// bind the fragments to the tabs - set up tabListeners for each tab
mFindTab.setTabListener(new MyTabsListener(mFindFragment,
getApplicationContext()));
mChatTab.setTabListener(new MyTabsListener(mChatFragment,
getApplicationContext()));
我遇到了这个错误:类型不匹配:无法从FindFragment转换为Fragment。所以我按照修复错误建议并将代码更改为
// create the fragments
FindFragment mFindFragment = new FindFragment();
// bind the fragments to the tabs - set up tabListeners for each tab
mFindTab.setTabListener(new MyTabsListener(mFindFragment,
getApplicationContext()));
现在,出现了一个新错误:构造函数MyTabsListener(FindFragment,Context)未定义。
如果导入很重要,那么它们就是:
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
对于myTabsListener:
class MyTabsListener implements ActionBar.TabListener {
public Fragment fragment;
public Context context;
public MyTabsListener(Fragment fragment, Context context) {
this.fragment = fragment;
this.context = context;
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Reselected!", Toast.LENGTH_SHORT).show();
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Selected!", Toast.LENGTH_SHORT).show();
ft.replace(R.id.container, fragment);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(context, "Unselected!", Toast.LENGTH_SHORT).show();
ft.remove(fragment);
}
}
对于我的FindFragment类:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FindFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.findfragment, container, false);
}
}
我在这里很困惑。我不确定这是否与我的导入,lib设置或其他问题有关。提前致谢!
答案 0 :(得分:3)
您需要更改此
import android.support.v4.app.Fragment;
// you will use this import when you want fragment from support library
// in that case you will extend FragmentActivity which is the base class for support based fragments
到
import android.app.Fragment;
FindFragment.java
中的。
同样在ChatFragment.java