【问题标题】:Fragment inner class should be static片段内部类应该是静态的
【发布时间】:2013-03-12 08:22:39
【问题描述】:

我有一个带有内部类的FragmentActivity 类,应该显示Dialog。但我必须做到static。 Eclipse 让我可以使用@SuppressLint("ValidFragment") 抑制错误。如果我这样做是不是很糟糕,可能的后果是什么?

public class CarActivity extends FragmentActivity {
//Code
  @SuppressLint("ValidFragment")
  public class NetworkConnectionError extends DialogFragment {
    private String message;
    private AsyncTask task;
    private String taskMessage;
    @Override
    public void setArguments(Bundle args) {
      super.setArguments(args);
      message = args.getString("message");
    }
    public void setTask(CarActivity.CarInfo task, String msg) {
      this.task = task;
      this.taskMessage = msg;
    }
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
      // Use the Builder class for convenient dialog construction
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setMessage(message).setPositiveButton("Go back", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
          Intent i = new Intent(getActivity().getBaseContext(), MainScreen.class);
          startActivity(i);
        }
      });
      builder.setNegativeButton("Retry", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
          startDownload();
        }
      });
      // Create the AlertDialog object and return it
      return builder.create();
    }
  }

startDownload() 启动 Asynctask。

【问题讨论】:

  • 一般来说忽略 lint 是不好的做法。这是一个非常聪明的工具。尝试发布您的代码,以实际获得有关如何做得更好的答案。
  • 您检查过这个code.google.com/p/android/issues/detail?id=41800 是否知道这是关于ValidFragment 的? lint 说:'每个片段都必须有一个空的构造函数,所以它可以被实例化'
  • 我做到了。但我不明白为什么我不能忽略这个警告。可能的后果是什么?

标签: android fragment android-dialogfragment


【解决方案1】:

非静态内部类确实持有对其父类的引用。使 Fragment 内部类成为非静态的问题在于您始终持有对 Activity 的引用。 GarbageCollector 无法收集您的Activity。因此,如果例如方向发生变化,您可以“泄露”Activity。因为 Fragment 可能仍然存在并被插入到新的 Activity 中。

编辑:

由于有人问我一些例子,我开始写一个,在这样做时,我发现使用非静态片段时出现了更多问题:

  • 它们不能在 xml 文件中使用,因为它们没有空构造函数(它们可以有一个空构造函数,但您通常通过 myActivityInstance.new Fragment() 实例化非静态嵌套类,这与仅调用空构造函数不同)
  • 它们根本不能被重用——因为FragmentManager 有时也会调用这个空构造函数。如果您在某些事务中添加了 Fragment

因此,为了使我的示例正常工作,我必须添加

wrongFragment.setRetainInstance(true);

在方向改变时不会使应用崩溃的行。

如果您执行此代码,您将有一个带有一些文本视图和 2 个按钮的活动 - 这些按钮会增加一些计数器。片段显示了他们认为他们的活动所具有的方向。一开始一切正常。但是在更改屏幕方向后,只有第一个 Fragment 可以正常工作 - 第二个 Fragment 仍在其旧活动中调用内容。

我的活动课:

package com.example.fragmenttest;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class WrongFragmentUsageActivity extends Activity
{
private String mActivityOrientation="";
private int mButtonClicks=0;
private TextView mClickTextView;


private static final String WRONG_FRAGMENT_TAG = "WrongFragment" ;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    int orientation = getResources().getConfiguration().orientation;
    if (orientation == Configuration.ORIENTATION_LANDSCAPE)
    {
        mActivityOrientation = "Landscape";
    }
    else if (orientation == Configuration.ORIENTATION_PORTRAIT)
    {
        mActivityOrientation = "Portrait";
    }

    setContentView(R.layout.activity_wrong_fragement_usage);
    mClickTextView = (TextView) findViewById(R.id.clicksText);
    updateClickTextView();
    TextView orientationtextView = (TextView) findViewById(R.id.orientationText);
    orientationtextView.setText("Activity orientation is: " + mActivityOrientation);

    Fragment wrongFragment = (WrongFragment) getFragmentManager().findFragmentByTag(WRONG_FRAGMENT_TAG);
    if (wrongFragment == null)
    {
        wrongFragment = new WrongFragment();
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.mainView, wrongFragment, WRONG_FRAGMENT_TAG);
        ft.commit();
        wrongFragment.setRetainInstance(true); // <-- this is important - otherwise the fragment manager will crash when readding the fragment
    }
}

private void updateClickTextView()
{
    mClickTextView.setText("The buttons have been pressed " + mButtonClicks + " times");
}

private String getActivityOrientationString()
{
    return mActivityOrientation;
}


@SuppressLint("ValidFragment")
public class WrongFragment extends Fragment
{


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        LinearLayout result = new LinearLayout(WrongFragmentUsageActivity.this);
        result.setOrientation(LinearLayout.VERTICAL);
        Button b = new Button(WrongFragmentUsageActivity.this);
        b.setText("WrongFragmentButton");
        result.addView(b);
        b.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                buttonPressed();
            }
        });
        TextView orientationText = new TextView(WrongFragmentUsageActivity.this);
        orientationText.setText("WrongFragment Activities Orientation: " + getActivityOrientationString());
        result.addView(orientationText);
        return result;
    }
}

public static class CorrectFragment extends Fragment
{
    private WrongFragmentUsageActivity mActivity;


    @Override
    public void onAttach(Activity activity)
    {
        if (activity instanceof WrongFragmentUsageActivity)
        {
            mActivity = (WrongFragmentUsageActivity) activity;
        }
        super.onAttach(activity);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        LinearLayout result = new LinearLayout(mActivity);
        result.setOrientation(LinearLayout.VERTICAL);
        Button b = new Button(mActivity);
        b.setText("CorrectFragmentButton");
        result.addView(b);
        b.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                mActivity.buttonPressed();
            }
        });
        TextView orientationText = new TextView(mActivity);
        orientationText.setText("CorrectFragment Activities Orientation: " + mActivity.getActivityOrientationString());
        result.addView(orientationText);
        return result;
    }
}

public void buttonPressed()
{
    mButtonClicks++;
    updateClickTextView();
}

}

请注意,如果您想在不同的活动中使用您的 Fragment,您可能不应该在 onAttach 中转换活动 - 但在这里它适用于示例。

activity_wrong_fragement_usage.xml:

<LinearLayout 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:orientation="vertical"
tools:context=".WrongFragmentUsageActivity" 
android:id="@+id/mainView">

<TextView
    android:id="@+id/orientationText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />

<TextView
    android:id="@+id/clicksText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="" />



<fragment class="com.example.fragmenttest.WrongFragmentUsageActivity$CorrectFragment"
          android:id="@+id/correctfragment"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" />


</LinearLayout>

【讨论】:

  • 非常有趣且可能非常有用的答案。我正在处理同样的问题。您介意删除您的答案所基于的某种来源吗?
  • @Egis 也许这可以让您对嵌套静态内部类有所了解:docs.oracle.com/javase/tutorial/java/javaOO/nested.html
  • 你有这个答案的参考吗?
  • 我相信 WrongFragment 实例保持其对旧 Activity 实例的引用(onCreateView() 中使用的WrongFragmentActivity.this),因为WrongFragment.onCreateView() 没有被再次调用;由于setRetainInstance(true) 和通过findFragmentByTag()“保留”片段,视图永远不会重新创建,而不是通过 XML 布局文件fragment 元素的 CorrectFragment 的新实例。您所描述的 Android 架构的次要问题和副产品,但值得理解。
  • onAttach 已弃用
【解决方案2】:

我不会谈论内部片段,而是更具体地说是在 Activity 中定义的 DialogFragment,因为它是这个问题的 99%。
从我的角度来看,我不希望我的 DialogFragment(您的 NetworkConnectionError)是静态的,因为我希望能够从其中的包含类(Activity)中调用变量或方法。
它不会是静态的,但我也不想产生 memoryLeaks。
解决办法是什么?
简单的。当你进入 onStop 时,确保你杀死你的 DialogFragment。就这么简单。 代码看起来像这样:

public class CarActivity extends AppCompatActivity{

/**
 * The DialogFragment networkConnectionErrorDialog 
 */
private NetworkConnectionError  networkConnectionErrorDialog ;
//...  your code ...//
@Override
protected void onStop() {
    super.onStop();
    //invalidate the DialogFragment to avoid stupid memory leak
    if (networkConnectionErrorDialog != null) {
        if (networkConnectionErrorDialog .isVisible()) {
            networkConnectionErrorDialog .dismiss();
        }
        networkConnectionErrorDialog = null;
    }
}
/**
 * The method called to display your dialogFragment
 */
private void onDeleteCurrentCity(){
    FragmentManager fm = getSupportFragmentManager();
     networkConnectionErrorDialog =(DeleteAlert)fm.findFragmentByTag("networkError");
    if(networkConnectionErrorDialog ==null){
        networkConnectionErrorDialog =new DeleteAlert();
    }
    networkConnectionErrorDialog .show(getSupportFragmentManager(), "networkError");
}

这样可以避免内存泄漏(因为这很糟糕),并且可以确保没有无法访问活动字段和方法的 [expletive] 静态片段。 从我的角度来看,这是处理该问题的好方法。

【讨论】:

  • 看起来不错,但它会在生成 apk 时出现错误,就像下面提到的@hakri Reddy
  • 是的,但这并不是因为 lint 不够聪明,我们需要“像它一样愚蠢”,使用这种技术可以消除内存泄漏(CanaryLeak 会告诉你)......方式,我首先使用 lint 运行我的 apk 以检测我可以在我的代码中完成的其他错误,修复我认为需要解决的问题,然后使用 abortOnError 错误运行它。在某些项目中,我根据这个特定规则自定义 Lint(“内部类应该是静态的”下降到弱警告)
  • 哦...但在我的情况下,实际的 apk 生成是由坐在美国办公室的不同团队完成的(我在印度,我只提供 git 代码存储库链接),因为他们没有与任何人共享公司签名证书文件。所以他们绝对不会听我的理由,也不会改变他们的设置:(
  • 是的,有时不仅有技术限制:),我们必须接受它们:)
  • 这种方法给了我一个Fragment must be a public static class crash error
【解决方案3】:

如果你在 android studio 中开发它,那么如果你不把它作为静态的就没有问题。项目将运行没有任何错误,在生成 apk 时你会得到错误:这个片段内部类应该是静态的 [ValidFragment ]

这是 lint 错误,您可能正在使用 gradle 构建,要禁用错误中止,添加:

lintOptions {
    abortOnError false
}

构建.gradle。`

【讨论】:

  • 你说得对,它会通过构建过程,但是这样使用它对吗?因为存在内存泄漏问题,这就是 android studio 警告我们的原因。
  • 有时我认为 abortOnError 为 false 太难了,我更喜欢将 lint 的规则“内部类应该是静态的”自定义为弱警告或信息。
【解决方案4】:

如果你想访问外部类(Activity)的成员并且仍然不想在Activity中使成员静态(因为片段应该是公共静态的),你可以覆盖onActivityCreated

public static class MyFragment extends ListFragment {

    private OuterActivityName activity; // outer Activity

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        activity = (OuterActivityName) getActivity();
        ...
        activity.member // accessing the members of activity
        ...
     }

【讨论】:

    【解决方案5】:

    在内部类之前添加注释

    @SuppressLint("validFragment")

    【讨论】:

      猜你喜欢
      • 2015-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多