我是新來的android和我正在達特茅斯的教程。 http://www.cs.dartmouth.edu/~campbell/cs65/lecture08/lecture08.htmlAndroid片段類型不匹配
我下面所有的代碼,並在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轉換成片段。所以我按照修正錯誤的建議,並更改代碼以
// 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,上下文)是不確定的。
萬一進口是至關重要的,在這裏,他們是:
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安裝或其他問題有關。提前致謝!
顯示你'MyTabsListener'類的代碼。確保你的類MyTabsListener包含你已經定義的兩個參數的構造函數。 – GrIsHu
你的活動擴展到什麼地方並且張貼了片段 – Raghunandan
的導入請顯示'MyTabsListener'和'FindFragment'類。您應該爲'FindFragment'類擴展Fragment'或將MyTabsListener的構造函數更改爲'MyTabsListener(FindFragment ff,Context c)' – Aprian