从父Activity获取片段中不同字段的值

时间:2014-11-06 19:17:54

标签: java android android-fragments

我有一个addActivity托管5个片段,每个片段上都有一些字段要填充。
我想从addActivity获取这些字段的值。我试过这样的事情:
AddActivity.java

public class AddActivity extends FragmentActivity {
    ViewPager vp;
    ProgressDialog dialog;

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

        vp = (ViewPager) findViewById(R.id.pager);
        PagerAdapter pa = new FragPagerAdapter(getSupportFragmentManager());
        vp.setAdapter(pa);}

    public class getValueOfFields() {
  //here I'm trying to get the value of differents fields in the different fragments but I get 

always "editText == Null" If the editText is in The fragment 1 or 2 or 3 it will get null
     EditText editTextFromFrag1 = (EditText) findViewById(R.id.visitDateFiled); // this == null
// If the EditText is in Fragment 4 or 5 it will get the value normaly without any issue


             ...}

FragPagerAdapter.java

public class FragPagerAdapter extends FragmentPagerAdapter {
    public FragPagerAdapter(FragmentManager fm) {
        super(fm);}

    @Override
    public Fragment getItem(int index) {
        switch (index) {
            case 0:
                return new FirstFragment();
            case 1:
                return new SecondFragment();
            case 2:
                return new HousingFragment();
            case 3:
                return new FeedingFragment();
            case 4:
                return new OtherFragment();
        }

        return null;
    }

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

OtherFragment.java 公共类OtherFragment extends Fragment {     按钮btn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_other, container, false);
    btn = (Button) view.findViewById(R.id.send);
    btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//Call the getValueOfFields (After filling the differnts fields the user click the send button) 
                ((AddActivity) getActivity()).getValueOfFields();
            }
        });
        return view;
    }
}

已更新
我得到的问题始终是EditText(和其他要获取的字段)等于null如果它们位于片段1或2或3中。 否则我得到正确的价值

4 个答案:

答案 0 :(得分:1)

您好Chlebta您需要设置pager.setOffscreenPageLimit(5);。当您在片段之间滑动时,片段可能会被破坏。这就是你得到null的原因。

或者,一个简单的解决方案是你设置

pager.setOnPageChangeListener(new OnPageChangeListener() {

                @Override
                public void onPageSelected(int arg0) {
                    // Now here you get your fragment object. 
                   // To get the Fragment Object you need to store them in an ArrayList in your FragPagerAdapter class.
                  //  create a method `getMyFraggment ` which return your Fragment from Arraylist.
                 //   Now create a method in your each Fragment which return your EditText values. Here you can use HashMap to store the values.

                // Here you use switch cases to get your Fragment Object I just wrote 1 here                        
                MyFragment f =  ((FragPagerAdapter)pager.getAdapter()).getMyFraggment(arg0);

                HashMap <String, String> hashMap = f.getValuesFromFragment();
                myValues.putAll(hashMap);    // myValues is global hashmap in your Activity. 
               // Now you get All values in your Global HashMap. But remember here you can get duplicate values if user swipe a fragment more than 1 time. You should do a logic here to remove duplicate values.

                }

                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onPageScrollStateChanged(int arg0) {
                    // TODO Auto-generated method stub

                }
            });

答案 1 :(得分:0)

您可以尝试将文本更改的侦听器添加到每个片段上的编辑文本字段,并在用户更改文本时将您设置的字符串字段设置为等于edittext视图的值。然后在FragPagerAdapter中保存片段的每个实例,并创建一个公共方法,该方法将返回数组中每个单独片段的所有字符串或者您想要的方式。从Activity中调用该方法。

答案 2 :(得分:0)

您很可能遇到此问题,因为您没有从正确的视图中获取XML元素,或者您尝试从中获取数据的视图在您尝试访问之前被销毁。

但是,我不确定为什么完全您遇到此问题,但我确实有一个解决办法建议:

每次用户输入字段时,您都可以将其存储在将用作存储单元的SharedPreferencesstatic类中。

我不确定用户是如何输入所有数据的,但您可以使用不同的侦听器(例如OnClickListener)来跟踪用户何时输入某个数据字段。

然后,您可以使用上面提到的两种方法之一存储数据。以下是使用static存储类的示例。

您的应用程序中的某处:

class Storage {
    public static String dateFilled;
    // ... rest of your data
}

然后,一旦用户使用问题中的示例,停止在EditText中为dateFilled输入信息(他们将注意力集中在它上面),您存储此信息:

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(hasFocus){
        // user is still typing so we do nothing
    }else {
        // user finished typing and moved on so we store the data
        Storage.dateFilled = editText.getText().toString();
    }
   }
});

您还可以使用某种Button作为存储信息的触发器:

myBtn.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        Storage.dateFilled = editText.getText().toString(); 
    }
}

然后您可以使用存储的数据,如:

public class getValueOfFields() {
    Toast.makeText(getApplicationContext(), Storage.dateFilled, Toast.LENGTH_LONG);
    // ...
}

如果您想使用SharedPreferenceshere is a good example

答案 3 :(得分:0)

执行以下操作:

创建用于将片段传递给活动的界面:

import android.widget.EditText;

public interface FormInterface {

    public void returnEditedEditText(EditText editText);

}

创建一个实例化接口的基础片段,并覆盖EditText被修改后的通信方法。确保Fragment还实现了OnEditorActionListener:

import android.app.Activity;
import android.app.Fragment;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

public class FormFragment extends Fragment implements OnEditorActionListener {

    protected final String FRAGMENT_NAME = getClass().getName();

    protected FormInterface formInterface;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        //ensure activity implements interface
        try {
            formInterface = (FormInterface) activity;
        } catch (ClassCastException ex) {
            String errorString = activity.toString() + " must implement FormInterface";
            Log.e(FRAGMENT_NAME, errorString);
            throw new ClassCastException(errorString);
        }
    }

    @Override
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        if(actionId == EditorInfo.IME_ACTION_DONE)
            formInterface.returnEditedEditText((EditText) view);
        return true;
    }

 }

然后在make中你的其他片段扩展基本片段:

YOURFRAGMENT extends FormFragment {
    //FOR EACH EDIT TEXT DO THE FOLLOWING
    EDITTEXT.setOnEditorActionListener(this);
}

然后确保您的活动实现自定义界面:

import android.app.Activity;
import android.widget.EditText;

public class FormActivity extends Activity implements FormInterface {

    @Override
    public void returnEditedEditText(EditText editText) {

        String input = editText.getEditableText().toString();

        switch(editText.getId()) {
            case R.id.editText_FirstName:
                mFirstName = input;
                break;
            ...
        }
    }
}