首页 文章

如何在父 Activity 中的 asynctask 类中更改 Fragment 中的 TextView?

提问于
浏览
-1

我正在开发 Android 应用程序。选项卡的视图来自fragments。所以我从服务器检索JSON数据。在fragment的父视图类中AsyncTask正在检索JSON数据。现在从我从服务器检索到的数据,我想相应地更改TextView文本,这是在fragment内。

这是我的fragment layout

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MutualFunds"
    android:id="@+id/fragment_mutual_funds">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/fund_name_bf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="28dp"
            android:text="@string/mutualfundfrag_iclbf_title"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/fund_definition_bf"
            android:layout_width="319dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="8dp"
            android:text="@string/mutualfundfrag_iclbf_definition"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fund_name_bf" />

        <TextView
            android:id="@+id/current_nav_bf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="12dp"
            android:text="@string/mutualfundfrag_iclbf_current_nav"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fund_definition_bf" />

        <TextView
            android:id="@+id/current_return_bf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="12dp"
            android:text="@string/mutualfundfrag_iclbf_current_return"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/current_nav_bf" />

        <TextView
            android:id="@+id/fund_performance_bf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="12dp"
            android:text="@string/mutualfundfrag_iclbf_fund_performance"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/current_return_bf" />

        <TextView
            android:id="@+id/fund_name_gf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="28dp"
            android:text="@string/mutualfundfrag_bcbiclgf_title"
            android:textAppearance="@style/TextAppearance.AppCompat.Large"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fund_performance_bf" />

        <TextView
            android:id="@+id/fund_definition_gf"
            android:layout_width="315dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="12dp"
            android:text="@string/mutualfundfrag_bcbiclgf_definition"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fund_name_gf" />

        <TextView
            android:id="@+id/current_nav_gf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="12dp"
            android:text="@string/mutualfundfrag_iclbf_current_nav"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/fund_definition_gf" />

        <TextView
            android:id="@+id/current_return_gf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="12dp"
            android:text="@string/mutualfundfrag_iclbf_current_return"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/current_nav_gf" />

        <TextView
            android:id="@+id/fund_performance_gf"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="12dp"
            android:text="@string/mutualfundfrag_iclbf_fund_performance"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/current_return_gf" />

    </android.support.constraint.ConstraintLayout>

</FrameLayout>

这是我的fragment activity课程:

package com.testappl.ivest;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.testappl.ivest.model.FundMaster;


/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MutualFunds.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MutualFunds#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MutualFunds extends Fragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;
    private static View view;
    private OnFragmentInteractionListener mListener;

    public MutualFunds() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MutualFunds.
     */
    // TODO: Rename and change types and number of parameters
    public static MutualFunds newInstance(String param1, String param2) {
        MutualFunds fragment = new MutualFunds();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

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

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    //Change the texts of Balanced Fund
    public static void changeBFTexts(FundMaster fm){
        TextView mBFLabel=view.findViewById(R.id.fund_name_bf);
        TextView mBFDefintion=view.findViewById(R.id.fund_definition_bf);
        TextView mBFCurrentNAV=view.findViewById(R.id.current_nav_bf);
        TextView mBFCurrentReturn=view.findViewById(R.id.current_return_bf);
        mBFLabel.setText(fm.getFundName());
        mBFDefintion.setText(fm.getFundDefinition());


    }

    //Change the texts of Growth Fund
    public static void changeGFTexts(FundMaster fm){
        TextView mGFLabel=view.findViewById(R.id.fund_name_gf);
        TextView mGFDefinition=view.findViewById(R.id.fund_definition_gf);
        TextView mGFCurrentNAV=view.findViewById(R.id.current_nav_gf);
        TextView mGFCurrentReturn=view.findViewById(R.id.current_return_gf);
        mGFLabel.setText(fm.getFundName());
        mGFDefinition.setText(fm.getFundDefinition());
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}

这是我正在检索数据的父活动的AsyncTask

private class JsonTask extends AsyncTask<String, String, String> {

        protected void onPreExecute() {
            super.onPreExecute();

            pd = new ProgressDialog(ICLProducts.this);
            pd.setMessage("Please wait");
            pd.setCancelable(false);
            pd.show();
        }

        protected String doInBackground(String... params) {


            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();


                InputStream stream = connection.getInputStream();

                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();
                String line = "";

                while ((line = reader.readLine()) != null) {
                    buffer.append(line+"\n");
                    Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-)

                }

                return buffer.toString();


            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
                try {
                    if (reader != null) {
                        reader.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (pd.isShowing()){
                pd.dismiss();
            }
            try {
                JSONArray resultJsonArray = new JSONArray(result);
                ArrayList<FundMaster> fundsData=new ArrayList<FundMaster>();

                for(int i=0;i<resultJsonArray.length();i++){
                    JSONObject jsonObject= (JSONObject) resultJsonArray.get(i);
                    fundsData.add(new FundMaster(Integer.valueOf(jsonObject.get("f_id").toString()),
                            Integer.valueOf(jsonObject.get("fund_id").toString()),
                            jsonObject.get("fund_name").toString(),
                            jsonObject.get("fund_definition").toString(),
                            jsonObject.get("fund_date").toString()));
                }
                for(FundMaster fm:fundsData){
                    Log.d("Fund Name",fm.getFundName());
                    Log.d("Fund Launch Date",fm.getFundLaunchDate());

                    if(fm.getFundId()==1){
                        MutualFunds.changeBFTexts(fm);
                    }else if(fm.getFundId()==2){
                        MutualFunds.changeGFTexts(fm);
                    }

                }



            } catch (JSONException e){
                Log.e("JSON Error","JSON problem");
            }

父活动的布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ICLProducts">

    <android.support.design.widget.TabLayout
        android:id="@+id/icl_product_page_tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:elevation="6dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        />
    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/icl_product_page_tabs"/>

</RelativeLayout>

在此先感谢您的支持。

2 回答

  • 0

    不要使用静态方法。并将 textView 声明为全局。然后,

    通过 TAG 获取 Fragment,这是在片段出现时已经给出的。之后你可以调用方法。喜欢,

    MutualFunds fr = (MutualFunds) getSupportFragmentManager().findFragmentByTag(MutualFunds .class.getName());
    if (fr != null) {
           fr.changeBFTexts(fm);
    }
    
  • 0

    根据你的问题,你只想显示一个来自 received(which 的记录是一个 JSONArray)。如果是这样,你应该在你的活动中有一个方法来改变 assyncTask 完成后片段的变化:

    public void changefrag(Fragment frag) {
    
        FragmentManager manager = getSupportFragmentManager();
    
        if (!manager.beginTransaction().isEmpty()) {
            manager.beginTransaction().detach(frag);
        }
        manager.beginTransaction()
                .replace(R.id.your_frament_layout_inside_your_activity, frag).commit();
    
    }
    

    在你的 jsonTask 的 onPostExecute 方法中你应该调用它:

    @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (pd.isShowing()){
                pd.dismiss();
            }
            try {
                JSONArray resultJsonArray = new JSONArray(result);
                ArrayList<FundMaster> fundsData=new ArrayList<FundMaster>();
    
                for(int i=0;i<resultJsonArray.length();i++){
                    JSONObject jsonObject= (JSONObject) resultJsonArray.get(i);
                    fundsData.add(new FundMaster(Integer.valueOf(jsonObject.get("f_id").toString()),
                            Integer.valueOf(jsonObject.get("fund_id").toString()),
                            jsonObject.get("fund_name").toString(),
                            jsonObject.get("fund_definition").toString(),
                            jsonObject.get("fund_date").toString()));
                }
                for(FundMaster fm:fundsData){
                    Log.d("Fund Name",fm.getFundName());
                    Log.d("Fund Launch Date",fm.getFundLaunchDate());
    
                    //change fragment and passe data you want to show to it
                    changeFrag(MutualFunds.newInstance(fm.getFundName(),fm.getFundLaunchDate());
    
                    }
    
            } catch (JSONException e){
                Log.e("JSON Error","JSON problem");
            }
    

    }

    在你的片段 classe in 创建你应该这样做来显示数据:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        view=inflater.inflate(R.layout.fragment_mutual_funds, container, true);
        TextView mBFLabel=view.findViewById(R.id.fund_name_bf);
        TextView mBFDefintion=view.findViewById(R.id.fund_definition_bf);
        TextView mBFCurrentNAV=view.findViewById(R.id.current_nav_bf);
        TextView mBFCurrentReturn=view.findViewById(R.id.current_return_bf);
        mBFLabel.setText(mParam1);
        mBFDefintion.setText(mParam2);
    
        return inflater.inflate(R.layout.fragment_mutual_funds, container, false);
    }
    

    如果您需要显示所有收到的数据,那么您需要在片段中使用 recycleView。

相关问题