Android ViewPager教程毫无意义

时间:2015-12-12 23:57:19

标签: android android-fragments

我访问了Android开发者网站,了解如何在页面之间滑动。所以我按照他们的教程:http://developer.android.com/training/animation/screen-slide.html#viewpager

我创建了一个片段,它会在每个滑动页面上膨胀我想要的视图。然后,我创建了一个FragmentActivity以及一个适配器,每次刷卡都会创建一个新的Fragment。但随后教程结束了。现在我只有一个黑屏,我甚至不知道PageViewer是否正常工作。他们在教程中没有提到如何为每个页面滑动分配内容。示例:第一页滑动我想要一个textview和一个图像,下一个滑动将包含一个不同的textview和一个不同的图像等(只有3)。在用户定向到我的主要活动之前,这将是我的应用程序的开始屏幕。

我知道当我使用recyclerview时,我们可以为每一行分配东西。在ViewPager中没有那种类型吗?

我几乎和android网站一样:

片段活动:

public class ScreenSlideActivity extends FragmentActivity {

private static final int NUM_PAGES = 3;

ViewPager mPager;
private PagerAdapter mPagerAdapter;

@Override
public void onBackPressed() {

    int pos = mPager.getCurrentItem();

    if (pos == 0) {
        super.onBackPressed();
    } else mPager.setCurrentItem(pos - 1);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_screen_slide);

    mPager = (ViewPager) findViewById(R.id.pager);
    mPagerAdapter = new adapter(getSupportFragmentManager());
    mPager.setAdapter(mPagerAdapter);



}


private class adapter extends FragmentStatePagerAdapter {
    public adapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        return new ScreenSlidePageFragment();
    }

    @Override
    public int getCount() {
        return NUM_PAGES;
    }
}
}

片段

public class ScreenSlidePageFragment extends Fragment {

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    ViewGroup group = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
    return group;

}
}

1 个答案:

答案 0 :(得分:0)

  

我知道当我使用recyclerview时,我们可以为每一行分配东西。在ViewPager中没有那种类型吗?

您可以在片段内部执行此操作,就像处理任何其他片段一样。通常,您告诉片段在创建它时应该显示的内容的一般参数(或通过setter方法更新该信息),并且片段会根据需要更新其小部件。

例如,在this sample app中,我将SampleAdapter(一个FragmentPagerAdapter子类)传递到一个文件中,以便加载到newInstance()工厂方法中EditorFragment 1}}:

/***
  Copyright (c) 2012-2015 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    https://commonsware.com/Android
 */

package com.commonsware.android.fileseditor;

import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.os.Environment;
import android.support.v13.app.FragmentPagerAdapter;
import java.io.File;

public class SampleAdapter extends FragmentPagerAdapter {
  private static final int[] TITLES={R.string.internal,
      R.string.external, R.string.pub};
  private static final int TAB_INTERNAL=0;
  private static final int TAB_EXTERNAL=1;
  private static final String FILENAME="test.txt";
  private final Context ctxt;

  public SampleAdapter(Context ctxt, FragmentManager mgr) {
    super(mgr);

    this.ctxt=ctxt;
  }

  @Override
  public int getCount() {
    return(3);
  }

  @Override
  public Fragment getItem(int position) {
    File fileToEdit;

    switch(position) {
      case TAB_INTERNAL:
        fileToEdit=new File(ctxt.getFilesDir(), FILENAME);
        break;

      case TAB_EXTERNAL:
        fileToEdit=new File(ctxt.getExternalFilesDir(null), FILENAME);
        break;

      default:
        fileToEdit=
            new File(Environment.
                  getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),
                FILENAME);
        break;
    }

    return(EditorFragment.newInstance(fileToEdit));
  }

  @Override
  public String getPageTitle(int position) {
    return(ctxt.getString(TITLES[position]));
  }
}

EditorFragment将参数Bundle中的信息存储起来(以便File幸免于配置更改,如屏幕旋转),然后使用AsyncTask加载文本内容并将其转移到构成EditText UI大部分内容的EditorFragment中。当片段暂停时,它还会启动SaveThread来更新文件:

/***
  Copyright (c) 2012-2015 CommonsWare, LLC
  Licensed under the Apache License, Version 2.0 (the "License"); you may not
  use this file except in compliance with the License. You may obtain a copy
  of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
  by applicable law or agreed to in writing, software distributed under the
  License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
  OF ANY KIND, either express or implied. See the License for the specific
  language governing permissions and limitations under the License.

  From _The Busy Coder's Guide to Android Development_
    https://commonsware.com/Android
 */

package com.commonsware.android.fileseditor;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class EditorFragment extends Fragment {
  private static final String KEY_FILE="file";
  private EditText editor;
  private LoadTextTask loadTask=null;
  private boolean loaded=false;

  static EditorFragment newInstance(File fileToEdit) {
    EditorFragment frag=new EditorFragment();
    Bundle args=new Bundle();

    args.putSerializable(KEY_FILE, fileToEdit);
    frag.setArguments(args);

    return(frag);
  }

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

    setRetainInstance(true);
  }

  @Override
  public View onCreateView(LayoutInflater inflater,
                           ViewGroup container,
                           Bundle savedInstanceState) {
    View result=inflater.inflate(R.layout.editor, container, false);

    editor=(EditText)result.findViewById(R.id.editor);

    return(result);
  }

  @Override
  public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    if (!loaded) {
      loadTask=new LoadTextTask();
      loadTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
          (File)getArguments().getSerializable(KEY_FILE));
    }
  }

  @Override
  public void onPause() {
    if (loaded) {
      new SaveThread(editor.getText().toString(),
          (File)getArguments().getSerializable(KEY_FILE)).start();
    }

    super.onPause();
  }

  @Override
  public void onDestroy() {
    if (loadTask!=null) {
      loadTask.cancel(false);
    }

    super.onDestroy();
  }

  private class LoadTextTask extends AsyncTask<File, Void, String> {
    @Override
    protected String doInBackground(File... files) {
      String result=null;

      if (files[0].exists()) {
        BufferedReader br;

        try {
          br=new BufferedReader(new FileReader(files[0]));

          try {
            StringBuilder sb=new StringBuilder();
            String line=br.readLine();

            while (line!=null) {
              sb.append(line);
              sb.append("\n");
              line=br.readLine();
            }

            result=sb.toString();
          }
          finally {
            br.close();
          }
        }
        catch (IOException e) {
          Log.e(getClass().getSimpleName(), "Exception reading file", e);
        }
      }

      return(result);
    }

    @Override
    protected void onPostExecute(String s) {
      editor.setText(s);
      loadTask=null;
      loaded=true;
    }
  }

  private static class SaveThread extends Thread {
    private final String text;
    private final File fileToEdit;

    SaveThread(String text, File fileToEdit) {
      this.text=text;
      this.fileToEdit=fileToEdit;
    }

    @Override
    public void run() {
      try {
        fileToEdit.getParentFile().mkdirs();

        FileOutputStream fos=new FileOutputStream(fileToEdit);

        Writer w=new BufferedWriter(new OutputStreamWriter(fos));

        try {
          w.write(text);
          w.flush();
          fos.getFD().sync();
        }
        finally {
          w.close();
        }
      }
      catch (IOException e) {
        Log.e(getClass().getSimpleName(), "Exception writing file", e);
      }
    }
  }
}

同样的模式适用于许多其他场景(例如,PagerAdapter为片段提供数据库主键,该数据库查询数据库并填充其小部件。)