70

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()非同期タスクを開始します。

4

5 に答える 5

95

非静的内部クラスは、それらの親クラスへの参照を保持します。Fragment内部クラスを非静的にすることの問題は、常にActivityへの参照を保持することです。GarbageCollectorはあなたのアクティビティを収集できません。したがって、たとえば向きが変わった場合に、アクティビティを「リーク」することができます。フラグメントはまだ生きていて、新しいアクティビティに挿入される可能性があるためです。

編集:

何人かの人々が私にいくつかの例を求めたので、私はそれを書き始めました、これをしている間、私は非静的フラグメントを使用するときにいくつかのより多くの問題を見つけました:

  • 空のコンストラクターがないため、xmlファイルで使用することはできません(空のコンストラクターを持つことができますが、通常は、静的でないネストされたクラスをインスタンス化することmyActivityInstance.new Fragment()で、これは空のコンストラクターを呼び出すだけとは異なります)
  • これらはまったく再利用できませんFragmentManager。この空のコンストラクターを呼び出すこともあるためです。一部のトランザクションでフラグメントを追加した場合。

したがって、私の例を機能させるために、私はを追加する必要がありました

wrongFragment.setRetainInstance(true);

向きの変更時にアプリがクラッシュしないようにするための行。

このコードを実行すると、いくつかのテキストビューと2つのボタンを使用したアクティビティが発生します。ボタンによってカウンターが増加します。そして、フラグメントは、彼らが彼らの活動が持っていると思う方向性を示しています。最初はすべてが正しく機能します。ただし、画面の向きを変更した後は、最初のフラグメントのみが正しく機能します。2番目のフラグメントは、以前のアクティビティでまだ呼び出しを行っています。

私のアクティビティクラス:

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();
}

}

フラグメント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>
于 2013-03-22T17:19:55.137 に答える
18

内部フラグメントについては説明しませんが、より具体的には、アクティビティ内で定義された DialogFragment について説明します。これは、この質問の 99% のケースです。
私の観点からは、含まれているクラス (Activity) から変数またはメソッドを呼び出せるようにしたいので、DialogFragment (あなたの NetworkConnectionError) を静的にしたくありません。
静的ではありませんが、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");
}

こうすることで、メモリ リークを回避し (悪いことなので)、アクティビティのフィールドやメソッドにアクセスできない [罵倒] 静的フラグメントを確実に回避できます。私の観点からすると、これはその問題を処理する良い方法です。

于 2016-03-10T12:29:31.383 に答える
5

Androidスタジオで開発する場合、静的として指定しなくても問題ありません.プロジェクトはエラーなしで実行され、apkの生成時にエラーが発生します:このフラグメント内部クラスは静的である必要があります[ValidFragment]

これは lint エラーです。おそらく gradle でビルドしているのでしょう。エラーによる中止を無効にするには、以下を追加します。

lintOptions {
    abortOnError false
}

build.gradle へ。`

于 2015-07-17T07:28:51.897 に答える
-2

内部クラスの前に注釈を追加する

@SuppressLint("validFragment")

于 2017-03-07T07:42:45.513 に答える