gpt4 book ai didi

java - 无法在同一 Activity 中用 fragment B 替换 fragment A

转载 作者:行者123 更新时间:2023-11-30 01:54:49 25 4
gpt4 key购买 nike

我的应用程序有一个主 Activity ,它有一个线性布局,线性布局显示一个 fragment A,其中包含包含按钮和 TextView 的列表。我想单击 fragment A 的 ListView 按钮,然后它应该用 fragment B 替换 fragment A。

现在我可以点击 Fragment A ListView 的按钮,但是(它没有显示 Fragment B)它显示 Android 没有响应。我已完成调试,但在提交 fragment B 的事务时出现错误。其他代码工作正常。

请帮我看看为什么会出现这个错误完整代码如下

主要 Activity 代码

public class MainActivity extends Activity {

FrameLayout frameLayout = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Async","On Create");

frameLayout = (FrameLayout) findViewById(R.id.fragment_Container);
InstallFragmetA();
}

protected void InstallFragmetA()
{
FragmentA fragmentA = new FragmentA();
FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_Container,fragmentA,"A");
transaction.commit();
}

protected void InstallFragmetB()
{
FragmentB fragmentB = new FragmentB();
FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.add(R.id.fragment_Container,fragmentB,"B");
transaction.commit();
}
protected void RemoveFragmetA()
{

Log.d("Async","In Remove Fragment A");
FragmentB fragmentB = new FragmentB();
Log.d("Async","Fragment b initializeed");
// FragmentManager manager= getFragmentManager();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
Log.d("Async","Begin fragment transaction");
FragmentA fragmentA = (FragmentA) getFragmentManager().findFragmentByTag("A");
// fragmentA.onDestroy();
// fragmentA.onDestroyView();
transaction.replace(R.id.fragment_Container, fragmentB, "B");
Log.d("Async", "Fragment A replaced");
// transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
Log.d("Async","Fragment Failed");
// transaction.addToBackStack(null);
transaction.commit();
Log.d("Async","Transaction Commit");

}

A代码 fragment

public class FragmentA extends Fragment  {
MainActivity mainActivity= null;
TextView textView=null;
String[] friendList= null;
public FragmentA()
{
mainActivity = new MainActivity();
}
//Activity activity= null;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// this.activity = activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Async","On Create");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("Async","On Create view");
return inflater.inflate(R.layout.fragmenta,container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

textView = (TextView) getActivity().findViewById(R.id.textView);
ListView list = (ListView) getActivity().findViewById(R.id.listView);
Log.d("Async","Array is "+getResources().getStringArray(R.array.FriendsList));
friendList = getResources().getStringArray(R.array.FriendsList);
Log.d("Async","Array is "+friendList[0]);
textView.setText(friendList[0]);
// ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),R.array.FriendsList,R.layout.text);

AdapterClass adapterClass = new AdapterClass(getActivity(),friendList,mainActivity);
list.setAdapter(adapterClass);
list.setItemsCanFocus(true);
list.setFocusable(true);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override


public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Async","A");
Toast.makeText(getActivity(),"Hello "+position,Toast.LENGTH_LONG).show();

}
});
Log.d("Async","On Activity Created");
}

我正在为 fragment A 使用的适配器类

public class AdapterClass extends ArrayAdapter {
Button btn;
int counter=0;
Context c=null;
String[] friendList= null;
LayoutInflater l;
MainActivity mainActivity = null;
public AdapterClass(Context c, String[] friendList, MainActivity mainActivity) {
super(c,R.layout.a,R.id.textView3,friendList);
l = (LayoutInflater) c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
Log.d("Async","counter is ");
this.c=c;
this.friendList = friendList;
this.mainActivity = mainActivity;

}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
Log.d("Async","getView is "+position);
Log.d("Async","counter is "+counter);
View row = convertView;
Myholder holder = null;
if(row == null)
{
Log.d("Async","Row is Null");
row = l.inflate(R.layout.a, parent,false);
holder = new Myholder(row);
row.setTag(holder);
Log.d("Async","Row Set tag");
}
else
{
Log.d("Async","Row is not null");
holder = (Myholder) row.getTag();
Log.d("Async","Holder not tag");
}
holder.btn.setText(friendList[position]);
holder.text.setText(friendList[position]);
holder.btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("Async","Button Clicked "+friendList[position]);
Toast.makeText(c,"Button clicked "+friendList[position],Toast.LENGTH_LONG).show();

mainActivity.RemoveFragmetA();
}
});
return row;
}

fragment B代码

public class FragmentB extends Fragment {
public void onAttach(Activity activity) {
super.onAttach(activity);
// this.activity = activity;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("Async", " Fragment B On Create");
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
Log.d("Async"," Fragment B On Create view");
return inflater.inflate(R.layout.fragmentb,container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/mainActivity"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<FrameLayout
android:layout_width="fill_parent"
android:id="@+id/fragment_Container"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"></FrameLayout>

fragment .xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:id="@+id/linearLayouts"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Small Text"
android:id="@+id/textView" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView" />

fragment b.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Small Text"
android:id="@+id/textView" />

<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/listView1" />

我遇到以下错误。

E/AndroidRuntime(1021):     java.lang.IllegalStateException: Activity has been destroyed
E/AndroidRuntime(1021): at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1333)
E/AndroidRuntime(1021): at android.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
E/AndroidRuntime(1021): at android.app.BackStackRecord.commit(BackStackRecord.java:574)
E/AndroidRuntime(1021): at com.example.bathla.lab5_asynctasklabtest.MainActivity.InstallFragmetB(MainActivity.java:38)
E/AndroidRuntime(1021): at com.example.bathla.lab5_asynctasklabtest.AdapterClass$1.onClick(AdapterClass.java:64)
E/AndroidRuntime(1021): at android.view.View.performClick(View.java:4240)
E/AndroidRuntime(1021): at android.view.View$PerformClick.run(View.java:17721)
E/AndroidRuntime(1021): at android.os.Handler.handleCallback(Handler.java:730)
E/AndroidRuntime(1021): at android.os.Handler.dispatchMessage(Handler.java:92)
E/AndroidRuntime(1021): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime(1021): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime(1021): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime(1021): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime(1021): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime(1021): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime(1021): at dalvik.system.NativeStart.main(Native Method)

最佳答案

主 Activity

public class MainActivity extends Activity implements FragmentAListener
{
private FragmentA fragmentA;
private FragmentB fragmentB;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragmentA = (FragmentA) getFragmentManager().findFragmentByTag(FragmentA.class.getSimpleName());
if (savedInstanceState == null) {
fragmentA = new FragmentA();
replaceToFragment(fragmentA, false);
}
}

@Override
public void onListItemButtonClicked(String itemName) {
fragmentB = new FragmentB();
Bundle bundle = new Bundle();
bundle.putString(FragmentB.ITEM_NAME_KEY, itemName);
fragmentB.setArguments(bundle);
replaceToFragment(fragmentB, true);
}

public void replaceToFragment(Fragment fragment, boolean addToBackStack) {
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.container, fragment, fragment.getClass().getSimpleName());
if (addToBackStack) {
transaction.addToBackStack(fragment.getClass().getSimpleName());
}
transaction.commit();
}
}

fragment A

public class FragmentA extends Fragment
{
private String[] friendList;
private FragmentAListener listener;

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!(activity instanceof FragmentAListener)) {
throw new RuntimeException("Activity must implements FragmentAListener");
}
listener = (FragmentAListener) activity;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmenta, container, false);
TextView textView = (TextView) view.findViewById(R.id.textView);
ListView listView = (ListView) view.findViewById(R.id.listView);
friendList = getResources().getStringArray(R.array.FriendsList);
textView.setText(friendList[0]);
AdapterClass adapterClass = new AdapterClass(inflater.getContext(), friendList, listener);
listView.setAdapter(adapterClass);
listView.setOnItemClickListener(itemClickListener);
return view;
}

private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener()
{
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO your code
}
};


public interface FragmentAListener
{
void onListItemButtonClicked(String itemName);
}
}

fragment B

public class FragmentB extends Fragment
{
public static final String ITEM_NAME_KEY = "item_name";

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragmentb, container, false);
//TODO find your views here
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText("Its FragmentB. Selected item: " + getArguments().getString(ITEM_NAME_KEY));
return view;
}
}

适配器

 public class AdapterClass extends ArrayAdapter<String>
{
private LayoutInflater inflater;
private FragmentAListener listener;

public AdapterClass(Context context, String[] friendList, FragmentAListener listener) {
super(context, 0, friendList);
inflater = LayoutInflater.from(context);
this.listener = listener;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
Holder holder;
if (view == null) {
view = inflater.inflate(R.layout.list_item, parent, false);
holder = new Holder(view);
view.setTag(holder);
} else {
holder = (Holder) view.getTag();
}
String itemName = getItem(position);
holder.textView.setText(itemName);
holder.button.setText(itemName);
holder.button.setTag(itemName);
return view;
}

private class Holder
{
private TextView textView;
private Button button;

public Holder(View row) {
textView = (TextView) row.findViewById(R.id.textView);
button = (Button) row.findViewById(R.id.button);
button.setOnClickListener(onClickListener);
}
}

private OnClickListener onClickListener = new OnClickListener()
{
@Override
public void onClick(View v) {
listener.onListItemButtonClicked(v.getTag().toString());
}
};
}

Activity 布局

<LinearLayout
android:id="@+id/mainActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
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=".MainActivity">

<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">

</FrameLayout>
</LinearLayout>

FragmentA布局

<LinearLayout android:id="@+id/linearLayouts"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:text="This is Fragment A"
android:textAppearance="?android:attr/textAppearanceLarge"/>

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

fragment B布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#2233"
android:text="This is Fragment B"
android:textAppearance="?android:attr/textAppearanceLarge"/>

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>

列表项布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/fancy_item_fragment"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="blocksDescendants"
android:orientation="horizontal"
android:padding="15dp">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Text"/>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"/>
</LinearLayout>

关于java - 无法在同一 Activity 中用 fragment B 替换 fragment A,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32416887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com