片段活动片段通信

时间:2013-11-30 18:32:48

标签: android android-fragments

我的活动包含两个片段( Frag1 Frag2 )。

Frag1 中,我有 EditText

Frag2 中,我有一个按钮 TextView

我想要做的是,当我点击按钮时,我在EditText中键入的内容将显示在Textview中。这是我的代码,但它不起作用,因为每当我试图运行它时我的应用程序崩溃了:

Frag1:

public class Frag1 extends Fragment {

    EditText edit1;

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

        View v =  inflater.inflate(R.layout.frag2, container, false);       

        edit1 = (EditText) getActivity().findViewById(R.id.edit_1); 
        String str = edit1.getText().toString();

        Intent intent = new Intent(getActivity().getBaseContext(),
                MainActivity.class);
        intent.putExtra("message", str);
        getActivity().startActivity(intent);

        return v;
    }

}

活动:

public class MainActivity extends FragmentActivity{

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

        viewPager = (ViewPager) findViewById(R.id.pager);
        FragmentManager fragmentManager = getSupportFragmentManager();
        viewPager.setAdapter(new MyAdapter(fragmentManager));

        Intent intent = getIntent();
        String message = intent.getStringExtra("message");

        Bundle bundle=new Bundle();
        bundle.putString("message", message);

        Frag2 fragobj=new Frag2();
        fragobj.setArguments(bundle);
    }
    public class MyAdapter extends FragmentStatePagerAdapter {
        public MyAdapter (FragmentManager fm) {
            super(fm);
        }
        @Override
        public Fragment getItem(int i) {
            Fragment fragment = null;

            if (i == 0)
            {
                fragment = new Frag1();
            }
            if (i == 1)
            {
                fragment = new Frag2();
            }
            return fragment;
        }
        @Override
        public int getCount() {
            return 2;
        }
    }
}

Frag2:

public class Frag2 extends Fragment implements OnClickListener {

    Button button1;
    TextView text1;
    String strtext;

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

        View v =  inflater.inflate(R.layout.frag2, container, false);

        button1 = (Button) getActivity().findViewById(R.id.button1);
        button1.setOnClickListener(this);       
        text1 = (TextView) getActivity().findViewById(R.id.text1);

        strtext=getArguments().getString("message");

        return v;
    }

    @Override
    public void onClick(View arg0) { 

        text1.setText(strtext);
    }

}

logcat的:

12-01 02:47:22.763: D/jdwp(4115): sendBufferedRequest : len=0x31
12-01 02:47:22.769: W/asset(4115): AssetManager-->addDefaultAssets CIP path not exsit!
12-01 02:47:23.061: V/PhoneWindow(4115): DecorView setVisiblity: visibility = 4
12-01 02:47:23.084: V/PhoneWindow(4115): DecorView setVisiblity: visibility = 0
12-01 02:47:23.160: D/AndroidRuntime(4115): Shutting down VM
12-01 02:47:23.160: W/dalvikvm(4115): threadid=1: thread exiting with uncaught exception (group=0x40d819a8)
12-01 02:47:23.178: E/AndroidRuntime(4115): FATAL EXCEPTION: main
12-01 02:47:23.178: E/AndroidRuntime(4115): java.lang.NullPointerException
12-01 02:47:23.178: E/AndroidRuntime(4115):     at lmf.sample5.Frag1.onCreateView(Frag1.java:21)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1478)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:927)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1104)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1460)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:472)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.view.ViewPager.populate(ViewPager.java:1068)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.view.ViewPager.populate(ViewPager.java:914)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1436)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.View.measure(View.java:15635)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.View.measure(View.java:15635)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.View.measure(View.java:15635)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4919)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2200)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.View.measure(View.java:15635)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2165)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1249)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1443)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4872)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.Choreographer.doCallbacks(Choreographer.java:579)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.Choreographer.doFrame(Choreographer.java:548)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.os.Handler.handleCallback(Handler.java:800)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.os.Handler.dispatchMessage(Handler.java:100)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.os.Looper.loop(Looper.java:194)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at android.app.ActivityThread.main(ActivityThread.java:5371)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at java.lang.reflect.Method.invokeNative(Native Method)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at java.lang.reflect.Method.invoke(Method.java:525)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
12-01 02:47:23.178: E/AndroidRuntime(4115):     at dalvik.system.NativeStart.main(Native Method)

3 个答案:

答案 0 :(得分:2)

要访问片段内的元素,您需要膨胀的视图而不是父活动。例如

    edit1 = (EditText) getActivity().findViewById(R.id.edit_1); 

应更改为此

    edit1 = (EditText) v.findViewById(R.id.edit_1); 

编辑:

根据log cat,你现在在Frag 1第21行得到一个空指针异常。我认为这一行:

   String str = edit1.getText().toString();

首次创建片段时,edit1中没有文本,其值为null,并且您尝试在空对象上调用toString(),这会导致空指针异常。你应该先检查它是否为null。例如:

    String str =null;
    if(edit1.getText()!==null)
        str = edit1.getText().toString();

答案 1 :(得分:0)

您可以使用两个界面来完成。你的策略是这样的:

TestActivity持有Fragment1Fragment2

Fragment1有:

EditText etEditHere;

Fragment2有:

TextView tvFetchedValue;
    Button btnGetValue;

您的动机是etEditHere fragment1btnGetValueFragment2etEditHere文字将显示在tvFetchedValue Fragment2 1}}。

这是解决方案:

你必须提醒一下,一个片段不能直接与另一个片段通信。但片段可以通过活动进行交流。

你必须创建2个接口,一个用于TestActivity,一个用于Fragment1。

Activity将实现此接口:

    public interface IActivityTest {
    public String getValueFromFragment1();
}

Fragment1 will implements this interface:

    public interface IFragment1 {
    public String getValueFromEditTextInFragment1();
}

此处TestActivity实施IActivityTest,它将采用getValue()方法。

此处,当按下btnGetValue时,它会以这种方式调用getValueFromEditTextInFragment1() TestActivity

tvFetchedValue.setText(((IActivityTest)getActivity()).getValueFromFragment1());

getValueFromFragment1()的{​​{1}}方法中,它会调用TestActivity的{​​{1}}。 getValueFromFragment1()会将editText值返回Fragment1Fragment1将返回TestActivity

您的完整代码在此处:

TestActivity Layout:

TestActivity

Fragment1布局:

Fragment2

Fragment1 Java文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:baselineAligned="false"
    android:orientation="vertical" >

    <fragment
        android:id="@+id/fragmentTwo"
        android:name="YOUR_PACKAGE.Fragment2"
        android:layout_width="fill_parent"
        android:layout_height="200dp"/>

    <fragment
        android:id="@+id/fragmentOne"
        android:layout_marginTop="10dp"
        android:name="YOUR_PACKAGE.Fragment1"
        android:layout_width="fill_parent"
        android:layout_height="200dp" />

</LinearLayout>

Fragment2布局文件:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.nuspay.uddiponmarketplace.fragments.Fragment1">

    <EditText
        android:id="@+id/etEditHere"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="20dp"
        android:hint="Write Here"/>

</FrameLayout>

Fragment2 java文件:

public class Fragment1 extends Fragment implements IFragment1 {

    EditText etEditHere;

    public Fragment1() {
    }


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

        initView(view);
        return view;
    }

    private void initView(View view) {
        etEditHere= (EditText) view.findViewById(R.id.etEditHere);
    }

    @Override
public String getValueFromEditTextInFragment1() {
    return etEditHere.getText().toString().trim();
}
}

最后,这是<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.nuspay.uddiponmarketplace.fragments.Fragment2" android:orientation="vertical"> <!-- TODO: Update blank fragment layout --> <TextView android:id="@+id/tvFetchedValue" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Value will come here" android:gravity="center" android:textSize="17dp" android:padding="10dp"/> <Button android:id="@+id/btnGetValue" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Get Value From Fragment1" android:gravity="center" android:textStyle="bold" android:textSize="17dp" android:padding="10dp"/> </LinearLayout>

 public class Fragment2 extends Fragment {


        TextView tvFetchedValue;
        Button btnGetValue;
        public Fragment2() {
            // Required empty public constructor
        }


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

            initView(view);
            return view;
        }

        private void initView(View view) {
            tvFetchedValue= (TextView) view.findViewById(R.id.tvFetchedValue);
            btnGetValue= (Button) view.findViewById(R.id.btnGetValue);

            btnGetValue.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    tvFetchedValue.setText(((IActivityTest)getActivity()).getValueFromFragment1());
                }
            });
        }

    }

片段到活动通信答案是here

感谢和抱歉英语不好:)

答案 2 :(得分:0)

您对两个片段使用了相同的布局:R.layout.frag2

这是空指针。