gpt4 book ai didi

java - Android, fragment : Problems with Replace and remove methods

转载 作者:行者123 更新时间:2023-12-01 08:54:50 25 4
gpt4 key购买 nike

我正在学习使用 fragment ,并且遇到了一些有关替换和删除方法的问题。这是我的 Activity 类(class):

public class MainActivity extends AppCompatActivity implements BlankFragment.OnFragmentInteractionListener {
private BlankFragment fragment1;
private BlankFragment fragment2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragment1 = BlankFragment.newInstance("Fragment 1","");
fragmentTransaction.add(R.id.linearLayout,fragment1);
fragmentTransaction.commit();

}
public void onClick(View arg0)
{
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

switch (arg0.getId())
{

case R.id.button:
fragment2 = BlankFragment.newInstance("Fragment 2", "");
fragmentTransaction.add(R.id.linearLayout, fragment2);
fragmentTransaction.commit();
break;

case R.id.button2:
Toast.makeText(this,"REMOVE",Toast.LENGTH_SHORT).show();
if(fragment2!=null)
{
fragmentTransaction.remove(fragment2);
fragmentTransaction.commit();
}
break;

case R.id.button3:
fragmentTransaction.replace(R.id.linearLayout,fragment2);
fragmentTransaction.commit();
break;

}
}

public void onFragmentInteraction(Uri uri)
{

}
}

这是 fragment 类:

public class BlankFragment extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;

public BlankFragment() {
// Required empty public constructor
}

/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment BlankFragment.
*/
// TODO: Rename and change types and number of parameters
public static BlankFragment newInstance(String param1, String param2) {
BlankFragment fragment = new BlankFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
TextView textView = ((TextView) rootView.findViewById(R.id.textView));
textView.setText(mParam1);
return rootView;
}

// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}

@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}

@Override
public void onDetach() {
super.onDetach();
mListener = null;
}

/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}

这是 list :

<?xml version="1.0" encoding="utf-8"?>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

</application>

嗯,我有 2 个 fragment 。当我单击第一个按钮时,我想添加第二个 fragment 。如果我单击此按钮 10 次,后堆栈中是否会有 11 个 fragment (10 个 fragment 编号 2 和 1 个 fragment 编号 1)?还是只有两个 fragment ?当我单击第二个按钮时,我会删除编号为 2 的 fragment (如果有的话)。但是如果我点击第一个按钮两次或多次,如果我点击第二个按钮 200 次,第二个 fragment 仍然存在......为什么?当我单击第三个按钮时,我想用前一个 fragment 替换第二个 fragment 。如果我单击第一个按钮两次或多次,如果我单击第三个按钮,然后单击第二个按钮,则第二个 fragment 不会保留......为什么?如果我打开应用程序并单击第三个按钮,或者先单击第二个按钮,然后单击第三个按钮,则应用程序崩溃

这是日志猫

02-07 21:33:31.040 17090-17090/com.example.utente.fragment E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.utente.fragment, PID: 17090
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:5610)
at android.view.View$PerformClick.run(View.java:22265)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
at android.support.v4.app.BackStackRecord.doAddOp(BackStackRecord.java:380)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:430)
at android.support.v4.app.BackStackRecord.replace(BackStackRecord.java:421)
at com.example.utente.fragment.MainActivity.onClick(MainActivity.java:50)
at java.lang.reflect.Method.invoke(Native Method) 
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288) 
at android.view.View.performClick(View.java:5610) 
at android.view.View$PerformClick.run(View.java:22265) 
at android.os.Handler.handleCallback(Handler.java:751) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:154) 
at android.app.ActivityThread.main(ActivityThread.java:6077) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755) 

如果我单击第一个按钮,然后单击第三个按钮,应用程序不会崩溃...为什么?错误在哪里?按钮不在 fragment 中,而是在 Activity 中

最佳答案

首先,查看this post .

Well, I have 2 fragments. When I click the first button, I want to add the second fragment. If I click this button 10 times, will there be 11 fragments in the back stack (10 fragments number 2 and 1 number 1)? Or only two fragments?

如果要将交易添加到返回堆栈,请添加

fragmentTransaction.addToBackStack(null);

在您提交事务之前。然后您可以稍后在 FragmentManager 上使用 popBackStack()。

When I click the second button, I remove the fragment number 2, if there is, of course. But if I click two or more times the first button, if I click 200 times the second button, the second fragment remains...why?

这是因为当您单击第一个按钮时,您将fragment2 设置为 fragment 的新实例,即使它已经是一个实例,从而丢失了对旧实例的引用。

在按第一个按钮两次后,每次按第二个按钮时,每次都会尝试删除最新创建的 fragment 。因此,它将始终显示您创建的第二个最新 fragment ,该 fragment 始终是“fragment 2”。

When I click the third button, I want to replace the second fragment with the previous fragment. If I click two or more times the first button, if I click the third button and then the second button, the second fragment doesn't remain...why?

replace() 方法将删除所有先前添加的 fragment 并添加您要添加​​的 fragment 。当您按下第三个按钮时,您将删除所有其他 fragment 并添加 fragment 2。当您按下第二个按钮时,它将删除fragment2,然后就没有其他内容可显示了。

If I open the app and I click the third button or I click first the second button and then the third, the app crashes

这是因为如果不按第一个按钮,fragment2 将为 null。按第二个按钮不会执行任何操作,因为fragment2 为空。按第三个按钮将尝试添加fragment2,该 fragment 为空,然后显示错误。

看起来你的第二个和第三个按钮实际上是用来做同样的事情的。也许将其减少为两个按钮,第一个按钮添加一个 fragment ,第二个按钮弹出后堆栈。

关于java - Android, fragment : Problems with Replace and remove methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42100616/

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