java - 带有自定义 Java Generic 的 newInstance()?

标签 java android generics android-fragments

我正在开发我的第一个“非教程”应用程序,以发展和加强我的 Android 开发技能。

我一直在使用大量 Java 泛型来增强可重用性和调试性,特别是因为我的许多 fragment 都对 Question 类的子类执行相同的操作。

我刚遇到一个对我来说很陌生的传统模式,想知道我是否可以将它应用于 Java 中的泛型类。

根据文本,应在 Fragment 类中创建一个 newInstance(args,...) 方法来处理 Intent Extras Fragment 的转换参数

例子:

SomeActivity.class

@​O​v​e​r​r​i​d​e​
p​r​o​t​e​c​t​e​d​ ​F​r​a​g​m​e​n​t​ ​c​r​e​a​t​e​F​r​a​g​m​e​n​t​(​)​ ​{​
 ​ ​ ​ ​r​e​t​u​r​n​ ​n​e​w​ ​ObjectF​r​a​g​m​e​n​t​(​)​;​

 ​ ​ ​ ​U​U​I​D​ ​object​I​d​ ​=​ ​(​U​U​I​D​)​g​e​t​I​n​t​e​n​t​(​)​
 ​ ​ ​ ​ ​ ​ ​ ​.​g​e​t​S​e​r​i​a​l​i​z​a​b​l​e​E​x​t​r​a​(Object​F​r​a​g​m​e​n​t​.​E​X​T​R​A​_​OBJECT_​I​D​)​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​Object​F​r​a​g​m​e​n​t​.​n​e​w​I​n​s​t​a​n​c​e​(object​I​d​)​;​
}​

ObjectFragment.class

p​u​b​l​i​c​ ​s​t​a​t​i​c​ ObjectF​r​a​g​m​e​n​t​ ​n​e​w​I​n​s​t​a​n​c​e​(​U​U​I​D​ ​object​I​d​)​ ​{​
 ​ ​ ​ ​B​u​n​d​l​e​ ​a​r​g​s​ ​=​ ​n​e​w​ ​B​u​n​d​l​e​(​)​;​
 ​ ​ ​ ​a​r​g​s​.​p​u​t​S​e​r​i​a​l​i​z​a​b​l​e​(​E​X​T​R​A​_​C​R​I​M​E​_​I​D​,​ ​object​I​d​)​;​

 ​ ​ ​ ​ObjectF​r​a​g​m​e​n​t​ ​f​r​a​g​m​e​n​t​ ​=​ ​n​e​w​ ​ObjectF​r​a​g​m​e​n​t​(​)​;​
 ​ ​ ​ ​f​r​a​g​m​e​n​t​.​s​e​t​A​r​g​u​m​e​n​t​s​(​a​r​g​s​)​;​

 ​ ​ ​ ​r​e​t​u​r​n​ ​f​r​a​g​m​e​n​t​;​
}​

摘自:Brian Hardy。 “Android 编程:大 Nerd 牧场指南。”

但是使用 Java 泛型的情况呢?

我正在处理的代码:

QuestionListActivity.class

public class QuestionListActivity extends SingleFragmentActivity {


    // CONSTANTS
    public static final String EXTRA_FRAGMENT_TYPE = "com.renaissanceartsmedia.flashcard.editquestionactivity.fragment";
    public static final String EXTRA_ACTIVITY_TITLE = "ListQuestionActivity.EXTRA_ACTIVITY_TITLE";
    public static final String TAG = "QuestionListActivity";

    // Member Properties
    QuestionType mFragmentType;

    @Override
    protected Fragment createFragment() {

        mFragmentType = (QuestionType) getIntent().getSerializableExtra(EXTRA_FRAGMENT_TYPE);
        System.out.println("mFragmentType: " + mFragmentType);

        // Switch on Enumeration
        switch (mFragmentType) {

            case MULTIPLE_ANSWER_QUESTION:
            case MULTIPLE_CHOICE_QUESTION:
            case TRUE_FALSE_QUESTION:

                // PREVIOUS METHOD
                //return new QuestionListFragment<MultipleAnswerQuestion>();

                // Attempting to refactor to newInstance(Bundle args)
                return QuestionListFragment<MultipleAnswerQuestion>.newInstance(getIntent().getExtras()); // ERROR

            case MATCHING_QUESTION:
                return new QuestionListFragment<MatchingQuestion>();

            case BLANK_QUESTION:
                //return new BQFragment();
                return new QuestionListFragment<BlankQuestion>();
            default:
                return new QuestionListFragment<Question>();
        }

    }
}

目前,我正在从 QuestionListFragment 的 onCreate() 方法中获取 Extras。我知道如果过渡到 newInstance() 约定应该与 Java 泛型一起使用,我将删除这段代码。

QuestionListFragment.class

    public class QuestionListFragment<E extends Question> extends ListFragment implements QuestionDialogInterface {

        // Constants
        public static final String TAG = "QuestionListFragement";
        public static final String DIALOG_TITLE = "QuestionListFragment.DIALOG_TITLE";
        public static final String DIALOG_MESSAGE = "QuestionListFragment.DIALOG_MESSAGE";
        public static final String QUESTION_TYPE = "QUESTION_TYPE";
        private static final int DIALOG_FRAGMENT = 1;

        // Member Properties
        Flashcard mFlashcard;
        QuestionType mQuestionType;
        String mActivityTitle;
        ArrayList<E> mQuestions;
        DialogFragment mDialogFragment;

// SOMETHING LIKE THIS???
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public static QuestionListFragment<? extends Question> newInstance(Bundle args) {
            // Create a new instance of QuestionListFragment<? extends Question>
            QuestionListFragment<? extends Question> fragment = new QuestionListFragment();

            // Set the arguments
            fragment.setArguments(args);

            // Return the Fragment
            return fragment;
        }

        @SuppressWarnings("unchecked")
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.d(TAG,"Enter onCreate(Bundle savedInstanceState)");
            // Enable Options Menu
            setHasOptionsMenu(true);

            // Create the ActionBar 'UP' Button
            getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);

            // The Intent Extras
            Bundle extras = getActivity().getIntent().getExtras();

            // Extract the Flashcard from the extras
            UUID flashcardId = (UUID) extras.getSerializable(Flashcard.EXTRA_FLASHCARD_ID);
            mFlashcard = FlashcardStore.get(getActivity()).getFlashcard(flashcardId);
            mQuestionType = (QuestionType) extras.getSerializable(EditQuestionActivity.EXTRA_FRAGMENT_TYPE);
            mActivityTitle = extras.getString(QuestionListActivity.EXTRA_ACTIVITY_TITLE);


            // Get a Container of Multiple Answer Questions
            mQuestions = (ArrayList<E>) mFlashcard.getQuestions(mQuestionType);

            // Set the Title of the Fragment's Activity
            getActivity().setTitle(mActivityTitle);

            // Create a list 
            ListItemLayoutAdapter adapter = new ListItemLayoutAdapter(mQuestions);

            // Set the adapter for the list
            setListAdapter(adapter);
            Log.d(TAG,"Exit onCreate(Bundle savedInstanceState)");
        }
    ....
    }

关于 Android fragment 和 Java 泛型的最佳实践是什么?有人可以描述它们是什么,为什么要使用它们。如果应该使用 newInstance(),请通过提供正确的声明语法来帮助我修复错误:

// Attempting to refactor to newInstance(Bundle args)
 return QuestionListFragment<MultipleAnswerQuestion>.newInstance(getIntent().getExtras()); // ERROR

最佳答案

    public static <T extends Question> QuestionListFragment<T> newInstance(Bundle args) {
        // Create a new instance of QuestionListFragment<? extends Question>
        QuestionListFragment<T> fragment = new QuestionListFragment<T>();

        // Set the arguments
        fragment.setArguments(args);

        // Return the Fragment
        return fragment;
    }

然后调用它:

    QuestionListFragment.<MultipleAnswerQuestion>newInstance(getIntent().getExtras()‌​);

关于java - 带有自定义 Java Generic 的 newInstance()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24380930/

相关文章:

android - 在向 wifiiManager 添加新的 wifiConfiguration 时总是得到 -1

delphi - 如何修改TList<record>值?

java - 如何使用restful服务返回json数组

android - Facebook Graph 错误消息的可靠性

java - 从 "regular"文件或 jarred 文件读取资源文件

java - Socket线程接收时阻塞主线程

java - 创建通用类型的枚举集

c# - DictionaryBase 到泛型。

java - pdfbox:如何克隆页面

java - Eclipse插件: create a treeview that displays all the deprecated methods