从Fragment_a到Fragment_b的数据

时间:2014-09-03 08:05:07

标签: java android android-fragments fragment android-ui

我已经在关于Fragments的android.developer页面上红了,但我需要的是:Fragment_A有一个EditText而Fragment_B只有一个Button。当我按下按钮时,我想在EditText的数据中做一个Toast。

我该怎么做?谢谢你的帮助。

MainActivity:

package rs.sqllogin.androidloginsql;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements OnClickListener {

    EditText etUser, etPass;
    Button btnLogin;

    String username, password;
    // creat httpclient as the form container
    HttpClient httpclient;
    // httpPost method
    HttpPost httppost;
    // create an array list for the input data to be sent
    ArrayList<NameValuePair> nameValuePairs;
    // create a httpResponse and HttpEntity
    HttpResponse response;
    HttpEntity entity;

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

        initialise();

    }

    private void initialise() {
        etUser = (EditText) findViewById(R.id.etUser);
        etPass = (EditText) findViewById(R.id.etPass);
        btnLogin = (Button) findViewById(R.id.btnSubmit);

        btnLogin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        // Toast.makeText(getApplicationContext(), "Gomb le lett nyomva",
        // Toast.LENGTH_LONG).show();
        if (etUser.getText().toString().equals("")
                || etPass.getText().toString().equals("")) {
            Toast.makeText(getApplicationContext(), "Enter some Data!",
                    Toast.LENGTH_LONG).show();
        } else {

            new HttpAsyncTask().execute();

        }

    }

    public String POST() {

        // Create a new deafult httpclient
        httpclient = new DefaultHttpClient();

        // Create a new HTTP Post with URL
        httppost = new HttpPost("http://10.0.2.2/checklogin.php");

        username = etUser.getText().toString();
        password = etPass.getText().toString();

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("username", username));
        nameValuePairs.add(new BasicNameValuePair("password", password));
        String str = "";

        try {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);
            str = convertInputStreamToString(response.getEntity().getContent())
                    .toString();

        } catch (UnsupportedEncodingException e) {

            e.printStackTrace();
        } catch (ClientProtocolException e) {
            Log.e("Catch1", "ClientProtocolE");
            e.printStackTrace();
        } catch (IllegalStateException e) {
            Log.e("Catch2", "IllegalStatementE");
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("Catch3", "IOExpection");
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return str;

    }

    private static String convertInputStreamToString(InputStream inputStream)
            throws IOException {
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));
        String line = "";
        String result = "";
        while ((line = bufferedReader.readLine()) != null)
            result += line;

        inputStream.close();
        return result;

    }

    private class HttpAsyncTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {

            return POST();
        }

        @Override
        protected void onPostExecute(String result) {

            super.onPostExecute(result);

            if (result.toString().equals("true")) {

                MyFragmentAdapter adapter = new MyFragmentAdapter(
                        getSupportFragmentManager());
                ViewPager p = (ViewPager) findViewById(R.id.pager);
                p.setAdapter(adapter);
                p.setCurrentItem(MyFragmentAdapter.NUM_ITEMS - 2);

            } else {
                Toast.makeText(getApplicationContext(),
                        "Helytelen bejelentkezes!", Toast.LENGTH_LONG).show();
            }
        }

    }

}

onPostExecute挂起UI ..

MyFragmentAdapter.java:

package rs.sqllogin.androidloginsql;

import java.util.ArrayList;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyFragmentAdapter extends FragmentPagerAdapter {

    public static final int NUM_ITEMS = 2;
    private ArrayList<Fragment> fragments;

    public MyFragmentAdapter(FragmentManager fm) {
        super(fm);

        fragments = new ArrayList<Fragment>();
        fragments.add(new FragmentOne());
        fragments.add(new FragmentTwo());
    }

    @Override
    public Fragment getItem(int pos) {

        return fragments.get(pos);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return NUM_ITEMS;
    }

}

FragmentOne.java:

package rs.sqllogin.androidloginsql;

import java.util.ArrayList;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyFragmentAdapter extends FragmentPagerAdapter {

    public static final int NUM_ITEMS = 2;
    private ArrayList<Fragment> fragments;

    public MyFragmentAdapter(FragmentManager fm) {
        super(fm);

        fragments = new ArrayList<Fragment>();
        fragments.add(new FragmentOne());
        fragments.add(new FragmentTwo());
    }

    @Override
    public Fragment getItem(int pos) {

        return fragments.get(pos);
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return NUM_ITEMS;
    }

}

FragmentTwo.java:

package rs.sqllogin.androidloginsql;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;


public class FragmentTwo extends Fragment implements OnClickListener{

    public static final String TAG = "FragmentTwo";



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View v = View.inflate(getActivity(), R.layout.fragmenttwo, null);
        Button btnSend = (Button) v.findViewById(R.id.btn1);
        btnSend.setOnClickListener(this);



        return v;


    }



    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }



}

2 个答案:

答案 0 :(得分:0)

要访问从一个片段到另一个片段的任何内容,您可以创建其静态实例,如下所示 -

private static FragmentOne fragmentOne;

    public static FragmentOne getInstance() {
        if (fragmentOne == null) {
            fragmentOne = new FragmentOne();
        }
        return fragmentOne;
    }

//you have edit text
public EditText myEditText;

现在在第二个片段中,您可以通过 -

访问它
FragmentOne.getInstance().myEditText

答案 1 :(得分:0)

EditTextButton处于不同Fragments的任何特定原因?

我认为这比编程问题更具设计性。

片段应包含UI的自主部分(例如,表单)。每个片段应该尽可能少地了解另一个片段。

如果您在Toast提交时确实需要显示Activity。 在Fragment_B中添加一个监听器:

public static interface FragmentBListener
{
   void onSubmit();
{

Fragment_B

private FragmentBListener mListener;
@Override
public void onAttach(Activity activity)
{
    super.onAttach(activity)
    try{
        mListener = (FragmentBListener) activity;
    }
    catch( ClassCastException e )
    {
         throw new IllegalArgumentException("Activity must iimplement FragmentBListener!");
    }

}

FragmentA添加方法

public String getSubmitedText()
{
    return mEditTextInstance.getText().toString;
}

FragmentBListener Activity放入@Override public void onSubmit() { String toastMessage = mFragmentA.getSubmitedText(); //show Toast }

{{1}}