0

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

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


}
4

1 回答 1

2

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

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

  • 在 MainActivity 中创建 FtpClient 并使用像Otto这样的事件总线将其传递给片段

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

  • 使用依赖注入将其注入到视图中,例如使用GuiceRoboGuice

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

于 2013-05-17T18:56:32.210 回答