无法从FragmentActivity访问片段小部件

时间:2014-09-14 09:23:43

标签: android android-layout android-fragments android-fragmentactivity

访问Fragment Widgets(TextView,ImageView)时遇到问题 我在Fragment类中创建了setter,当我在FragmentActivity类中调用setTextView()时,我得到错误:

我做错了什么?什么是片段ID?

logcat的:

E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.radioinfo, PID: 3248
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.radioinfo/com.example.radioinfo.ActivityStation}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5139)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.radioinfo.ActivityStation.onCreate(ActivityStation.java:31)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2264)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5139)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
            at dalvik.system.NativeStart.main(Native Method)

FragmentActivity:

public class ActivityStation extends FragmentActivity implements ActionBar.TabListener {
    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    private String[] tabs = { "first", "second", "third" };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initXMLStuff();
    initPageChangeListener();
    //initBundle();
    StationSecondFragment fragment_obj = (StationSecondFragment)getSupportFragmentManager().
            findFragmentById(R.id.second_frag);
    fragment_obj.setTextViewRadioName("something");
}

private void initXMLStuff() {
    setContentView(R.layout.activity_station);
    getWindow().setBackgroundDrawableResource(R.drawable.bg1);
    viewPager = (ViewPager) findViewById(R.id.pager);
    actionBar = getActionBar();
    mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
    viewPager.setAdapter(mAdapter);
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    for (String tab_name : tabs) {
        actionBar.addTab(actionBar.newTab().setText(tab_name)
                .setTabListener(this));
    }
    actionBar.setSelectedNavigationItem(1);
}

private void initPageChangeListener() {
    viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            actionBar.setSelectedNavigationItem(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {
        }

        @Override
        public void onPageScrollStateChanged(int arg0) {
        }
    });
}

}

StationSecondFragment:

public class StationSecondFragment extends Fragment {
    private View rootView;
    private TextView textViewRadioName;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_second, container, false);
        textViewRadioName = (TextView) rootView.findViewById(R.id.radio_info_tvRadioName);
        return rootView;
    }

    public void setTextViewRadioName(String text) {
        textViewRadioName.setText(text);
    }
}

TabsPagerAdapter:

public class TabsPagerAdapter extends FragmentPagerAdapter {

    public TabsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int index) {

        switch (index) {
            case 0:
                return new StationFirstFragment();
            case 1:
                return new StationSecondFragment();
            case 2:
                return new StationThirdFragment();
        }
        return null;
    }

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

fragment_second.xml:

<?xml version="1.0" encoding="utf-8"?>

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:orientation="vertical"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:id="@+id/second_frag"
        >

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="RadioStation"
            android:id="@+id/radio_info_tvRadioName"
            android:layout_gravity="center_horizontal"/>

        <ImageView
            android:layout_marginTop="45dp"
            android:layout_marginLeft="15dp"
            android:layout_width="225dp"
            android:layout_height="220dp"
            android:id="@+id/radio_info_ivCover"
            android:background="@drawable/empty"
            android:layout_gravity="center_horizontal"/>
    </LinearLayout>

activity_station.xml

<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
                                   android:id="@+id/pager"
                                   android:layout_width="match_parent"
                                   android:layout_height="match_parent">
</android.support.v4.view.ViewPager>

1 个答案:

答案 0 :(得分:1)

最后,
我想出了一种改变Fragment Widgets的新方法。 我无法弄清楚如何在不设置ID的情况下从Activity访问Fragments Widget,所以我退出了这个场景,并通过 BroadcastReceiver 找到了新的解决方案:

在FragmentActivity类中,我为Filtering Broadcast创建静态变量:

public static String UPDATEFRAGMENT = "UPDATEFRAGMENT";

在Fragment类中,我使用覆盖方法 onReceive()创建 new BroadcastReceiver()实例:

BroadcastReceiver onNotice = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            setTextView("sometext");
        }
    };

然后我在onCreateView()方法中使用IntentFilter registerReceiver()

LocalBroadcastManager.getInstance(getActivity()).registerReceiver(onNotice, 
                        new IntentFilter(ActivityStation.UPDATEFRAGMENT));

最后我在FragmentActivity类中调用Broadcast:

LocalBroadcastManager.getInstance(ActivityStation.this).sendBroadcast(new Intent(ActivityStation.UPDATEFRAGMENT));

一切都很完美。