从fragment.newInstance字符串设置文本值

时间:2015-10-25 17:16:19

标签: android android-fragments android-activity

我正在尝试将字符串设置为textview,但每次单击按钮Quiz时,活动只是刷新而不是片段活动。

总结了这种情况。

  1. 我有一个名为Quiz_Container的动态viewPager内部活动
  2. 在public Fragment getItem(int position)或FragmentStatePagerAdapter中只使用一个片段(Module_Topics_Content_Quiz)。
  3. 每次刷卡时,我都想从活动中更改片段中textview的文本。
  4. 我使用newInstance传递字符串,参数从activity到片段
  5. 该字符串来自quizQuestion.get(position)
  6. 我使用Log.d获得了正确的值,但在将其设置为textview时,活动只是刷新。
  7. 这是我的代码。

    Quiz_Container.java

    public class Quiz_Container extends AppCompatActivity implements Module_Topics_Content_Quiz.OnFragmentInteractionListener {
    
        android.support.v7.app.ActionBar actionBar;
    
        ViewPager quizPager;
    
        private int topicID;
        private int moduleID;
        private int subModuleID;
    
        private ArrayList<Integer> quizID;
        private ArrayList<String> quizQuestion;
        private ArrayList<String> choiceA;
        private ArrayList<String> choiceB;
        private ArrayList<String> choiceC;
        private ArrayList<String> choiceD;
        private ArrayList<String> quizAnswer;
    
    
        private FragmentManager fragmentManager;
    
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_quiz__container);
    
            actionBar = getSupportActionBar();
            actionBar.setTitle("Quiz");
            actionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#f1ad1e")));
    
    
    
            Bundle extras = getIntent().getExtras();
            topicID = extras.getInt("topicID");
            moduleID = extras.getInt("moduleID");
            subModuleID = extras.getInt("subModuleID");
    
            Log.d("quizTopicID", "" + topicID);
            Log.d("quizModuleID", "" + moduleID);
            Log.d("quizSubModuleID", "" + subModuleID);
    
            new quizTask().execute();
    
        }
    
        @Override
        public void onFragmentInteraction(Uri uri) {
    
        }
    
        public boolean isOnline() {
            ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
    
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                return true;
            } else {
                return false;
            }
        } // Check Internet Connection
    
        class quizTask extends AsyncTask<String, String, String> {
    
            @Override
            protected void onPreExecute() {
    
            }
    
            @Override
            protected String doInBackground(String... params) {
                BufferedReader reader = null;
    
                try {
                    URL quizURL = new URL("http://192.168.1.110/science/index.php/users/get_quiz_items/" + topicID + "/" + moduleID + "/" + subModuleID + "" );
    
                    HttpURLConnection con = (HttpURLConnection)quizURL.openConnection();
    
                    StringBuilder sb = new StringBuilder();
    
                    reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    
                    String quizResponse;
    
                    while ((quizResponse = reader.readLine()) != null) {
    
                        return  quizResponse;
    
                    }
    
                    return sb.toString();
    
                } catch (IOException e) {
                    e.printStackTrace();
                    return null;
                } finally {
                    if(reader != null) {
                        try {
                            reader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                            return  null;
                        }
                    }
                }
            }
    
            @Override
            protected void onPostExecute(String quizResponses) {
    
                Log.d("quizResponse", "" + quizResponses);
    
                try {
                    JSONObject quizObject = new JSONObject(quizResponses);
    
                    boolean result = quizObject.getBoolean("success");
    
                    if (result) {
    
                        JSONArray quizArray = quizObject.getJSONArray("data");
    
                        quizID = new ArrayList<>();
                        quizQuestion = new ArrayList<>();
                        choiceA = new ArrayList<>();
                        choiceB = new ArrayList<>();
                        choiceC = new ArrayList<>();
                        choiceD = new ArrayList<>();
                        quizAnswer = new ArrayList<>();
    
                        for (int i = 0; i < quizArray.length(); i ++) {
    
                            JSONObject dataQuiz = quizArray.getJSONObject(i);
                            quizID.add(dataQuiz.getInt("id"));
                            quizQuestion.add(dataQuiz.getString("question"));
                            choiceA.add(dataQuiz.getString("a"));
                            choiceB.add(dataQuiz.getString("b"));
                            choiceC.add(dataQuiz.getString("c"));
                            choiceD.add(dataQuiz.getString("d"));
                            quizAnswer.add(dataQuiz.getString("answer"));
    
                        }
    
                        Log.d("quizSize", "" + quizID.size());
    
                        quizPager = (ViewPager) findViewById(R.id.quizPager);
                        fragmentManager = Quiz_Container.this.getSupportFragmentManager();
                        quizPager.setAdapter(new quizAdapter(getSupportFragmentManager()));
                        quizPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    
                            @Override
                            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    
                            }
    
                            @Override
                            public void onPageSelected(int position) {
    
                            }
    
                            @Override
                            public void onPageScrollStateChanged(int state) {
    
                            }
                        });
                    }
                    else {
                        Toast.makeText(getApplication(), "no quiz yet", Toast.LENGTH_LONG).show();
                    }
    
    
    
                } catch (JSONException e) {
                    e.printStackTrace();
                }
    
            }
        } // end of quizTask
    
        class quizAdapter extends FragmentStatePagerAdapter {
    
            public quizAdapter(FragmentManager fm) {
                super(fm);
            }
    
            @Override
            public Fragment getItem(int position) {
    
                Fragment fragment = null;
    
                for (int i = 0; i < quizID.size; i++) {
                    if (i == position) {
                        fragment = Module_Topics_Content_Quiz.newInstance(quizQuestion.get(position));
                        Log.d("testQuestion", "" + quizQuestion.get(position)); // this code is working
                    }
                }
                return fragment;
    
            }
    
            @Override
            public int getCount() {
                return quizID.size();
            }
        }
    
    }
    

    Module_Topics_Content_Quiz.java

    public class Module_Topics_Content_Quiz extends Fragment {
    
        TextView textQuizQuestion;
    
        private String qQuestion;
    
    
        public Module_Topics_Content_Quiz() {
            // Required empty public constructor
        }
    
    
        public interface OnFragmentInteractionListener {
            // TODO: Update argument type and name
            public void onFragmentInteraction(Uri uri);
        }
    
        public static Module_Topics_Content_Quiz newInstance(String question) {
            Module_Topics_Content_Quiz fragment = new Module_Topics_Content_Quiz();
            Bundle args = new Bundle();
            args.putString("question", question);
            fragment.setArguments(args);
    
            return fragment;
        }
    
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            if (getArguments() != null) {
                qQuestion = getArguments().getString("question");
            }
    
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View rootView =  inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);
    
            textQuizQuestion = (TextView) getActivity().findViewById(R.id.textQuestion);
    
            Log.d("question", "" + qQuestion); // this is working
    //        textQuizQuestion.setText(qQuestion); // error if enable
            return rootView;
        }
    
    
    }
    

    请帮忙。谢谢。

1 个答案:

答案 0 :(得分:1)

在您的片段中,尝试使用返回的TextViewView进行充气,而不是使用getActivity()

您需要对片段视图进行充气,并在其返回的findViewById()上调用View

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView =  inflater.inflate(R.layout.fragment_module__topics__content__quiz, container, false);

        // inflate the View inside Fragment using the View returned
        textQuizQuestion = (TextView) rootView.findViewById(R.id.textQuestion);

        Log.d("question", "" + qQuestion); // this is working
        textQuizQuestion.setText(qQuestion);
        return rootView;
    }

您还可以使用Fragment中的getView()来获取根视图。

如果您想从封闭的活动中打电话,请使用

getFragmentManager().findFragmentById(R.id.your_fragment_id).getView().findViewById(R.id.your_view);