这是我学习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
答案 0 :(得分:1)
如果您使用android.support.v4.app.Fragment
(您应该使用),那么您需要使用getSupportFragmentManager()
,而不是getFragmentManager()
。
答案 1 :(得分: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 {..}
@
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 {..}