Java 在哪里可以在 Fragment 中创建 Android Spinner?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20020961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 22:23:15  来源:igfitidea点击:

Where to create Android Spinner in Fragment?

javaandroidandroid-fragmentsandroid-spinner

提问by Turbut Alin

My question is rather simple: how can one use(populate) Spinnersin Fragments? Or better said, what is wrong with my code below? Adding Spinneras I did is as simple as it gets, but after trying in all the different ways, nothing worked. What is FragmentPagerAdapterhas to do with Spinner? If I add the Spinnerfrom a method declared somewhere else, the spinneris populated with no problems(for example if populating the spinnerfrom a button).

我的问题很简单:如何使用(填充)Spinnersin Fragments?或者更好地说,我下面的代码有什么问题?Spinner像我一样添加很简单,但是在尝试了所有不同的方法之后,没有任何效果。什么是FragmentPagerAdapter必须做的Spinner?如果我添加Spinnerfrom a 其他地方声明的方法,spinner则填充没有问题(例如,如果填充spinnerfrom a button)。

Thanks in advance

提前致谢

public class MainActivity extends FragmentActivity {

/**
 * The {@link android.support.v4.view.PagerAdapter} that will provide
 * fragments for each of the sections. We use a
 * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which
 * will keep every loaded fragment in memory. If this becomes too memory
 * intensive, it may be best to switch to a
 * {@link android.support.v4.app.FragmentStatePagerAdapter}.
 */
SectionsPagerAdapter mSectionsPagerAdapter;
public List<String> fragments = new Vector<String>();

/**
 * The {@link ViewPager} that will host the section contents.
 */
ViewPager mViewPager;
private MySQLite database;

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

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager); // pager
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // We initialise the database
    database = new MySQLite(this);

    Spinner spin = (Spinner)findViewById(R.id.spinner1);
    List<String> toSpin = new ArrayList<String>();
    toSpin.add("ONE");
    toSpin.add("TWO");
    toSpin.add("THREE");
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,toSpin);
    spin.setAdapter(adapter);
}

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

/**
 * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
 * one of the sections/tabs/pages.
 */

public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
        fragments.add(ConnectionFragment.class.getName());
        fragments.add(DataFragment.class.getName());

    }

    @Override
    public Fragment getItem(int position) {
        // we need to instantiate the list of fragments
        return Fragment.instantiate(getBaseContext(),
                fragments.get(position));

    }

    @Override
    public int getCount() {
        // Show 3 total pages.
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        Locale l = Locale.getDefault();
        switch (position) {
        case 0:
            return getString(R.string.title_section1).toUpperCase(l);
        case 1:
            return getString(R.string.title_section2).toUpperCase(l);
        }
        return null;
    }
}

/**
 * A dummy fragment representing a section of the app, but that simply
 * displays dummy text.
 */
public static class ConnectionFragment extends Fragment {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    public static final String ARG_SECTION_NUMBER = "section_number";

    public ConnectionFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View connectionView = inflater.inflate(
                R.layout.fragment_main_dummy, container, false);
        return connectionView;
    }
}

public static class DataFragment extends Fragment {

    public DataFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View dataView = inflater.inflate(R.layout.fragment_linear,
                container, false);
        return dataView;
    }
}

Logcat:

日志猫:

11-16 18:26:13.092: E/AndroidRuntime(16442): FATAL EXCEPTION: main
11-16 18:26:13.092: E/AndroidRuntime(16442): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.iwallet/com.example.iwallet.MainActivity}: java.lang.NullPointerException
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2071)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2096)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.app.ActivityThread.access0(ActivityThread.java:138)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1207)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.os.Looper.loop(Looper.java:213)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.app.ActivityThread.main(ActivityThread.java:4787)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at java.lang.reflect.Method.invokeNative(Native Method)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at java.lang.reflect.Method.invoke(Method.java:511)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at dalvik.system.NativeStart.main(Native Method)
11-16 18:26:13.092: E/AndroidRuntime(16442): Caused by: java.lang.NullPointerException
11-16 18:26:13.092: E/AndroidRuntime(16442):    at com.example.iwallet.MainActivity.onCreate(MainActivity.java:65)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.app.Activity.performCreate(Activity.java:5008)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-16 18:26:13.092: E/AndroidRuntime(16442):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2035)
11-16 18:26:13.092: E/AndroidRuntime(16442):    ... 11 more

采纳答案by fllo

If you want to make your Spinner in your Fragment, maybe you must to declare in these Fragment in onCreatedView(). Not in onCreate()of your FragmentActivity.

如果您想在 Fragment 中创建 Spinner,也许您必须在onCreatedView()中的这些 Fragment 中声明。不在您的 FragmentActivity 的onCreate()中。

And you can do it like this: Error populating spinner in a fragment

你可以这样做:在片段中填充微调器时出错