java - 在 viewPager 中的 2 个 fragment 之间共享 listView

标签 java android fragment

我有一个ViewPager,在第二页中,我有一个Form来连接Ftp。 当我按下连接按钮时,它会用另一个 fragment (ftp 列表文件夹)替换该 fragment 。 我不知道如何将 FTPClient 对象从一个 fragment 传递到另一个 fragment 。 有什么建议吗?

MainActivity.java

public class MainActivity extends FragmentActivity {
  FileAdapter adapter = null;
  int mColor = 0;
  File[] files = null;
  File mCurrentFile = null;
  List<File> lfiles = null;
  public List<FTPFile> lftpFiles = null;
  ViewPager pager = null;
  // ListView lv = null;
  RelativeLayout ftp = null;
  List<Fragment> fragments = null;
  private boolean mCountdown = false;// Se pone a true cuando se le pica una

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.viewpager);
    fragments = new Vector<Fragment>();
    fragments.add(Fragment.instantiate(this, LocalFragment.class.getName()));
    fragments.add(Fragment.instantiate(this, FtpFragment.class.getName()));
    fragments.add(Fragment.instantiate(this, CreditsFragment.class.getName()));

    ViewPagerAdapter mPagerAdapter = new ViewPagerAdapter(
            super.getSupportFragmentManager(), fragments);
    pager = (ViewPager) super.findViewById(R.id.viewpager);
    pager.setAdapter(mPagerAdapter);
}


@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK && pager.getCurrentItem() == 0) {
        File parent = ((LocalFragment) fragments.get(0)).mCurrentFile.getParentFile();
        if (parent != null) {
            ((LocalFragment) fragments.get(0)).updateDirectory(parent);
            ((LocalFragment) fragments.get(0)).mCurrentFile = parent;
            mCountdown = false;
        } else {// estamos a la raiz, desplegamos un toast
            Toast.makeText(getApplicationContext(),"Ya esta a la raiz, pica de nuevo para salir",
                    Toast.LENGTH_SHORT).show();
            if (mCountdown == false) {
                mCountdown = true;
            } else
                finish();

        }
    } else if (keyCode == KeyEvent.KEYCODE_BACK && pager.getCurrentItem() != 0){
        return super.onKeyDown(keyCode, event);
    }
      else{
        return false; // return super.onKeyDown(keyCode, event);
    }
    return true;
}

// pager.setCurrentItem(0, true);

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.action_settings:
        Intent i = new Intent(this, ExploradorPreference.class);
        startActivity(i);
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

}

FtpFragment.java

public class FtpFragment extends Fragment {
  public FileAdapter adapter;
  Context mContext;
  List<File> lfiles = null;
  File[] files = null;
  File mCurrentFile = null;
  ListView lv = null;
  int mColor = 0;
  String server = null;
  String user = null;
  String pass = null;
  FTPClient ftpClient=null;
  FtpListFragment ftpList = null;
  List<FTPFile> ftpLstDir = null;
  List<FTPFile> ftpLstFiles =null;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = getActivity();

}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.ftp, container, false);
    Button b = (Button) v.findViewById(R.id.connect);
    EditText txtServer = (EditText) v.findViewById(R.id.TxtServidor);
    EditText txtUser = (EditText) v.findViewById(R.id.TxtUser);
    EditText txtPass = (EditText) v.findViewById(R.id.TxtPass);
    txtServer.setText("ftpperso.free.fr");
    txtUser.setText("fleur.de.lotus");
    txtPass.setText("9sz07jd0");
    server = ((EditText) v.findViewById(R.id.TxtServidor)).getText()
            .toString();
    user = ((EditText) v.findViewById(R.id.TxtUser)).getText().toString();
    pass = ((EditText) v.findViewById(R.id.TxtPass)).getText().toString();
    ftpList = new FtpListFragment();

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (server.equalsIgnoreCase("") || user.equalsIgnoreCase("")
                    || pass.equalsIgnoreCase("")) {
                Toast.makeText(mContext,
                        "A lo menos un campo no esta lleno", Toast.LENGTH_LONG).show();
            } else {
                boolean conectionOk = ftpConnect(server, user, pass);
                if (conectionOk) {
                    Toast.makeText(mContext, "Conexion Succeed", Toast.LENGTH_LONG).show();
                    try {
                         String toppath = new String();
                            FTPFile[] ftpDirs = ftpClient.listDirectories();
                            FTPFile[] ftpdirs2 = ftpClient.listFiles(toppath);
                            ftpLstDir = Arrays.asList(ftpDirs);
                            ftpLstFiles = Arrays.asList(ftpdirs2);

                        }
                            // Remplazar el fragento
                            final FragmentManager fm = getActivity().getSupportFragmentManager();
                            final FragmentTransaction ft = fm.beginTransaction();
                            // We can also animate the changing of fragment
                              ft.setCustomAnimations(android.R.anim.slide_in_left,android.R.anim.slide_out_right);
                            ft.replace(R.id.ftp_fragment_form, ftpList);
                              ft.setTransition(FragmentTransaction.TRANSIT_EXIT_MASK);
                            ft.commit();


                    }catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    Toast.makeText(mContext, "Conexion Failed", Toast.LENGTH_LONG).show();
                }

            }
        }
    });
    return v;
}

public boolean ftpConnect(String server, String loginName, String password) {
    try {
        ftpClient = new FTPClient();
        ftpClient.connect(InetAddress.getByName(server));
        ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        ftpClient.login(loginName, password);

        System.out.println("status :: " + ftpClient.getStatus());
        System.out.println("status :: " + ftpClient.getReplyString());
        System.out.println("status :: " + ftpClient.getStatus());
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}


public void onDestroyView() {
    try{
        ftpClient.logout();
        ftpClient.disconnect();
        Log.d("DISCONNECT","Desconectando");
        super.onDestroyView();
    }catch (IOException e){
        System.out.println(e.getMessage());
    }

}

FtpListFragment.java

public class FtpListFragment extends ListFragment {
public FtpFileAdapter adapter;
List<FTPFile> lfiles=null;
Context mContext;
FTPClient ftpClient = null;


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = getActivity();

}

public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.ftplist, container, false);
        lfiles = new ArrayList<FTPFile>();
        try {
            // I'd like to get my ftpClient object from the FtpFragment !



        }catch (Exception e) {
            e.printStackTrace();
        }

        adapter = new FtpFileAdapter(mContext, lfiles);
        setListAdapter(adapter);    
    return v;
}


}

最佳答案

嗯,好吧,那么 FtpFragment 是负责创建 FtpClient 的人,您需要在某个时候将 FtpClient 传递给 FtpListFragment 吗?我建议您不要在FtpFragment中创建FtpClient。你可以:

  • 在 MainActivity 中创建 FtpClient,并在使用 setFtpClient 创建 FtpFragment 和 FtpListFragment 时将其传递给它们

  • 在 MainActivity 中创建 FtpClient 并使用类似 Otto 的事件总线将其传递给 fragment 。

  • 将整个 FtpClient 包装在一个单例类中,并使用静态 getInstance() 方法使其可用

  • 使用依赖注入(inject)将其注入(inject) View ,例如使用 GuiceRoboGuice

  • 在 MainActivity 中创建 FtpClient 并创建公共(public) getFtpClient() 方法,并让 fragment 使用 ((MainActivity)getActivity()).getFtpClient() 获取 FtpClient。然而,这确实在 fragment 和 Activity 之间创建了不健康的依赖关系

关于java - 在 viewPager 中的 2 个 fragment 之间共享 listView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16615213/

相关文章:

java - 从 SQL 中的单独表中获取 ID

java - Android:XmlPullParserFactory.newInstance 说找不到符号类 newInstance

android - 将月份转换为 MMM 格式

java - getMap() 空点异常

android - 无法在项目单击监听器上获取 gridView

android - 适用于 Android 的 PhoneGap - 包含 PhoneGap 的 fragment

java - Spring Boot 错误激活 Bean 验证集成

java - 从数据库获取行数据到 JSP

java - 如何在 DialogFragment 上定位 EditText

android - 如何在 Exoplayer 通知中设置自定义布局和字体?