2017-09-04 96 views
-1

這是我學習android studio的第二天。 我不知道爲什麼這裏有錯誤。 幫我請!Android Studio中的片段混亂

//MainActivity.java 
    public void ChangeFragment(View view) { 
     FragmentManager fragmentManager = getFragmentManager(); 
     FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
     Fragment2 fragment2 = new Fragment2(); 
     fragmentTransaction.add(R.id.FragmentView, fragment2); 
//error is there: "Wrong 2nd argument type. Found: 'com.example.myfirstapp.Fragment2', required: 'android.app.Fragment'" 

     fragmentTransaction.commit(); 
    } 

@

//Fragment2.java 
import android.support.v4.app.Fragment; 
public class Fragment2 extends Fragment { 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 
     final View view = inflater.inflate(R.layout.activity_fragment2, container, false); 

     Button button1 = (Button) view.findViewById(R.id.button2); 
     button1.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       TextView text = (TextView) view.findViewById(R.id.textView1); 
       text.setText("I am a Fragment"); 
      } 
     }); 
     return view; 
    } 

@

//activity_fragment2.xml 
    <LinearLayout 
     android:id="@+id/FragmentView" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     tools:layout_editor_absoluteX="16dp" 
     tools:layout_editor_absoluteY="16dp"> 
    </LinearLayout> 

https://developer.android.com/guide/components/fragments.html#Transactions

回答

1

如果您正在使用android.support.v4.app.Fragment(你應該),那麼你需要使用getSupportFragmentManager(),而不是getFragmentManager()

+0

?android.support.v4.app.Fragment的是Android工作室自動生成(Alt + Enter鍵) – rozaimech

+0

有很多種,支持片段中的許多錯誤修復將不會出現在框架片段中。爲什麼不能使用'getSupportFragmentManager()'? – ianhanniballake

+0

好的,謝謝,我只是按照正式的步驟去學習。現在我正在尋找關於getSupportFragmentManager()的教程。你明白,一開始一切都很困難,但現在我什麼都不懂,所以我可以去看看另一個。畢竟,所有的道路都通向羅馬......但是我真的想知道,我需要用什麼?如果我使用getFragmentManger()? – rozaimech

0
import android.app.FragmentManager; 
import android.app.FragmentTransaction; 
FragmentManager fragmentManager = **getFragmentManager()**; 
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 

import android.app.Fragment; 
public class Fragment2 extends Fragment {..} 

@

如果我使用getFragmentManager(),我需要用什麼
import android.support.v4.app.FragmentManager; 
import android.support.v4.app.FragmentTransaction; 
FragmentManager fragmentManager = **getSupportFragmentManager()**; 
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 

import android.support.v4.app.Fragment; 
public class Fragment2 extends Fragment {..}