使用Android模板建立的tabbed activity項目之問題(can’t convert taba to fragment)

來源:互聯網
上載者:User

使用Android模板建立的tabbed activity項目之問題(can’t convert taba to fragment)

 

建立新的android項目時,使用tabbed activity模板,自動設定好viewpager等。

在
@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).


return PlaceholderFragment.newInstance(position + 1);
}
改為:


@Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class
// below).


switch (position) {
case 0:
return new taba();



case 1:
return new tabb();

case 2:
return new tabc();

default:
// this page does not exists
return null;
}
// return PlaceholderFragment.newInstance(position + 1);
}


並去建立3個taba.java tabb.java tabc.java,像這樣

public class taba extends Fragment{



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {




View rootView = inflater.inflate(R.layout.fragment_a, container,
false);
return rootView;
}


}


以及對應的layout xml,像這樣
xmlns:tools=http://schemas.android.com/tools
android:layout_width=match_parent
android:layout_height=match_parent
android:paddingBottom=@dimen/activity_vertical_margin
android:paddingLeft=@dimen/activity_horizontal_margin
android:paddingRight=@dimen/activity_horizontal_margin
android:paddingTop=@dimen/activity_vertical_margin
tools:context=com.example.samepledemo.taba >



android:id=@+id/section_label
android:layout_width=wrap_content
android:layout_height=wrap_content
android:text=taba />






以上,其實在網上有很多,特別是stackoverflow上。
其實我寫這個,主要是因為在接下來遇到怪問題了,正準備開啟android studio來對比一下。
結果找到原因。
在getitem方法這個java檔案中,使用的是import android.support.v4.app.Fragment;
而在taba.java中使用的是
import android.app.Fragment;
所以,最後全改為
import android.support.v4.app.Fragment;
就行了。


import android.support.v4.app.Fragment;和import android.app.Fragment;主要區別就是:

android.support.v4.app.Fragment支援最低到1.6的andorid版本,android.app.Fragment支援最低到3.0

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.