8

私は Android 用のファイル マネージャー アプリを作成しています。以下の 2 つのクラスは、そのためのロジックの大部分です。私がやっていることは、ContentList の起動時に、ContentListFragment を ContestList xml のコンテナー レイアウトに追加することです。ContentListFragment を追加することで、現在のパスを取得し、setFileDir(String S) を呼び出します。これは基本的に、渡されたパスでファイルを取得し、その場所でファイルのリストを取得し、配列を初期化し、アダプターを初期化します。次に、アダプターを設定し、アクション バー UI を設定し、コンテキスト アクション バーを設定します。これで、ContentListFragment の項目が押されるたびに、選択された項目のパスを使用して別の ContentListFragment が作成されます。その後、前のフラグメントがバックスタックに追加されます。これですべてうまくいき、ダンディになりました。

ContentListFragment の onCreate の setRetainInstance(true) は、アプリの向きが変わったときにアプリ全体が強制的に閉じられないようにする唯一のものです。ただし、このようにすると、しばらくしてアプリに戻ったときにアプリが強制的に閉じられます(これが主な問題であり、理由がわかりません)。

方向の変更時にアクティビティが再作成されるときに、現在の ContentListFragment を新しいものに置き換えようとしましたが (このコードは以下にありません)、アプリの強制終了も setFileDir() で NullPointerException が発生するため、他のすべてが崩壊します。

フラグメントの状態を保存して、方向の変更時にすべてが方向の変更前と同じままになり、後で戻ったときに強制的に閉じないようにするにはどうすればよいですか?

念のため、私のアプリは、再帰的な ContentListFragments を持つ 1 つのアクティビティです。

public class ContentList extends DrawerActivity implements ContentListFragment.listFragmentListener{

    // instance variables
    private FragmentManager fm;
    private FragmentTransaction ft;
    private String currentPath;

    // Initializes variables.
    // If Activity is started for the first time, a path to the storage is
    // received.
    // Else, if it's an orientation change, the path is just retained.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_list);

        if (savedInstanceState == null) {
            fm = getSupportFragmentManager();
            ft = fm.beginTransaction();
            File file = Environment.getExternalStorageDirectory();
            currentPath = file.getPath();
            ft.add(R.id.content_container_fragment_listview, new ContentListFragment());
            ft.commit();
        } else {
            fm = getSupportFragmentManager();
            currentPath = savedInstanceState.getString("PATH");
        }
    }

    // Grabs the currentPath in case of orientation changes.
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("PATH", currentPath);
    }

dfsas

public class ContentListFragment extends SherlockListFragment {

    // instance variables
    private ArrayList<Item> items;
    private ArrayList<Item> copy_move_queue_items;
    private ItemAdapter adapter;
    private listFragmentListener lfListener;
    private String currentPath;
    private MenuItem menuItemRename;

    // instantiates variables using setFileDir() and the path from the container Activity.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
        currentPath = ((ContentList) getActivity()).getCurrentPath();
        setFileDir(currentPath);

    }

    // Gets a reference to Activity interface
    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            lfListener = (listFragmentListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + "must implement listFragmentListener");
        }
    }

    // Sets the UI of the listView and the ActionBar
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.content_list_fragment, container, false);

        File file = Environment.getExternalStorageDirectory();
        String rootPath = file.getPath();

        // Sets Action Bar title to current directory, and creates an Up
        // affordance if the root path doesn't equal the current Path
        getSherlockActivity().getSupportActionBar().setTitle(null);
        getSherlockActivity().getSupportActionBar().setLogo(R.drawable.ab_icon);

        if (currentPath.equals(rootPath)) {
            getSherlockActivity().getSupportActionBar()
                    .setDisplayHomeAsUpEnabled(false);
            getSherlockActivity().getSupportActionBar()
                    .setHomeButtonEnabled(false);
        } else {
            getSherlockActivity().getSupportActionBar()
                    .setDisplayHomeAsUpEnabled(true);



            // getSherlockActivity().getSupportActionBar().setTitle("/" +
            // (currentPath.substring(currentPath.lastIndexOf("/") +1)));
        }

        return v;

    }

    // Sets the long click Contextual Action Mode to the ListView
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setActionMode();
        setListAdapter(adapter);
    }
    // Gets the list of files at the path and adds them to the Item ArrayList,
// initializing the adapter as well
public void setFileDir(String path) {
    File file = new File(path);
    File[] files = file.listFiles();
    Arrays.sort(files, new fileComparator());
    items = new ArrayList<Item>();
    for (File f : files) {
        items.add(new Item(f));
    }
    adapter = new ItemAdapter(getActivity(), R.layout.content_list_item, items);
}
4

3 に答える 3

16

これは私のために働いた

@Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        onCreate(savedInstanceState);
    }

Activityタグ内のマニフェストファイル

android:configChanges="orientation|screenSize"

于 2016-01-14T16:58:27.713 に答える
15

これを使用して、向きのフラグメントの状態を保存します。

onCreate(Bundle save)
{
   super.onCreate(save);
   setRetainInstance(true);
}
于 2012-12-21T09:50:24.357 に答える
0

これは仕事とインタビューの両方で直面する大きな懸念事項であるため、これを投稿するだけです:) API 13の前は、非推奨の onRetainNonConfigurationInstance()を使用していました (このメソッドは、現在フラグメントに移動されているアクティビティに関連していました)。setRetainInstance()として知られるメソッド (フラグメント クラスのメソッド部分) は、アクティビティの作成後もフラグメントの状態を保存します。

于 2015-10-27T12:01:07.983 に答える