2017-03-07 69 views
-1

我嘗試添加listFragment with fragmentTransation.add(...),但我不能這樣做,這是一個錯誤。我想添加一個像正常片段一樣的listfragment,有可能嗎?Android:添加列表片段到交易

這裏是我的主要活動代碼:

public class MainActivity extends AppCompatActivity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    FragmentList fragmentList = FragmentList.createFragment(); 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
    fragmentTransaction.add(R.id.relativeLayout,fragmentList); //WRONG 
    fragmentTransaction.commit(); 
} 

這裏是我listfragment類代碼:

public class FragmentList extends ListFragment 
{ 
public static FragmentList createFragment() 
{ 
    FragmentList fragmentList = new FragmentList(); 
    return fragmentList; 
} 

@Override 
public void onCreate(Bundle bundle) 
{ 
    super.onCreate(bundle); 
    ListView listView = getListView(); 
    String[] stringa = {"A","B","C"}; 
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,stringa); 
    listView.setAdapter(arrayAdapter); 

} 

@Override 
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{ 
    super.onCreateView(inflater,container,savedInstanceState); 
    View rootView = inflater.inflate(R.layout.fragment, container, false); 
    return rootView; 
} 
} 
+0

發佈錯誤請! – ApolloSoftware

+0

@ApolloSoftware在fragmentTransaction.add(R.id.relativeLayout,fragmentList)下面有一條紅線; – Curio

+0

您可以擴展公共類MainActivity擴展AppCompatActivity,FragmentActivity? – ApolloSoftware

回答

4

1)不能使用android.app.ListFragmentSupportFragmentManger您可以使用getFragmentManager()了點。

基本上,檢查您的import陳述。

或者你可以擴展android.support.v4.app.Fragment代替,並用<ListView>定義自己的佈局(如你已經在做)

或者你可以使用android.support.v4.app.ListFragment


更重要的是,雖然

2 )getListView()不能從onCreate調用,因爲目前還沒有視圖。

你只需要onCreateView

public class FragmentList extends ListFragment { 

    @Override 
    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
    { 
     super.onCreateView(inflater,container,savedInstanceState); 
     View rootView = inflater.inflate(R.layout.fragment, container, false); 
     String[] stringa = {"A","B","C"}; 

     ListView listView = (ListView) rootView.findViewById(android.R.id.list); 
     ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,stringa); 
     listView.setAdapter(arrayAdapter); 

     return rootView; 
    } 
} 

另外,

getFragmentManager() // Change accordingly 
    .beginTransaction() 
    .add(R.id.relativeLayout,new FragmentList()) 
    .commit(); 
+0

getFragmentManager()應該工作我認爲。 – ApolloSoftware

+0

是的,它會與'ListFragment' –

+1

有支持['ListFragment'](https://developer.android.com/reference/android/support/v4/app/ListFragment.html),順便說一句。 –