首先我是新的机器人和英语:)抱歉。我有片段管理器的问题。我读了一些在主要活动中使用片段的代码。但它无法在模拟器中运行,您也可以在下面看到代码。我认为关于“import android.support.v4.app.FragmentManager;”的问题线。我不知道也许我必须使用它像“import android.app.FragmenManager” 我希望你能理解我的判决并帮助我。 谢谢。
package com.example.ilk.fragmenttransactions;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends FragmentActivity {
FragmentManager fm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addA(View v){
FragmentA f1 = new FragmentA();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.fragment_container, f1, "A");
transaction.commit();
}
public void removeA(View v){
FragmentA f1 = (FragmentA)fm.findFragmentByTag("A");
FragmentTransaction transaction = fm.beginTransaction();
if(f1 != null){
transaction.remove(f1);
transaction.commit();
}
else{
Toast.makeText(this, "There is no A! you cannot delete it", Toast.LENGTH_LONG).show();
}
}
public void addB(View v){
FragmentB f2 = new FragmentB();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.fragment_container, f2, "B");
transaction.commit();
}
public void removeB(View v){
FragmentB f2 = (FragmentB)fm.findFragmentByTag("B");
FragmentTransaction transaction = fm.beginTransaction();
if(f2 != null){
transaction.remove(f2);
transaction.commit();
}
else{
Toast.makeText(this, " There is no B! you cannot delete it ",Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
答案 0 :(得分:1)
使用import android.support.v4.app.FragmentManager
。
未加载片段,因为您的应用初始化时没有进行任何交易:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
我认为您正在尝试通过单击布局元素
来加载片段 android:onClick
属性
例如:
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="addA" />
执行此方法:
public void addA(View v){
FragmentA f1 = new FragmentA();
FragmentTransaction transaction = fm.beginTransaction();
transaction.add(R.id.fragment_container, f1, "A");
transaction.commit();
}