如何将变量从Activity传递给Fragment

时间:2016-09-26 21:04:00

标签: android android-fragments android-intent

我无法在OneFragment的textView中显示String描述的值。 我是Android编程的新手,任何帮助都将不胜感激。

这是MainActivity

package com.example.dell.myop;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;


import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;

import com.example.dell.myop.R;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.TextView;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import com.example.dell.myop.fragments.OneFragment;

import com.example.dell.myop.fragments.ThreeFragment;
import com.example.dell.myop.fragments.TwoFragment;





public class MainActivity extends AppCompatActivity {

    private Toolbar toolbar;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    String description;






    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);



        setContentView(R.layout.activity_main);
        DownloadTask task = new DownloadTask();
        task.execute("http://api.openweathermap.org/data/2.5/weather?q=hamirpur,india&appid=41352ca35dd1be72cc7d9f47351d1b41");



        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);
    }




    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new OneFragment(), "Today");
        adapter.addFragment(new TwoFragment(), "Tomorrow");
        adapter.addFragment(new ThreeFragment(), "Day After");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }
}

DownloadTask

package com.example.dell.myop;

import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import com.example.dell.myop.fragments.OneFragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import static android.support.v4.app.ActivityCompat.startActivity;

public class DownloadTask extends AsyncTask<String,Void,String> {





    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection urlConnection= null;


        try {
            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data = reader.read();
            while(data!=-1){
                char current = (char)data;
                result += current;
                data = reader.read();


            }
            return  result;


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        try {
            JSONObject jObject = new JSONObject(result);
            JSONArray jArray = jObject.getJSONArray("weather");
            for (int i=0; i < jArray.length(); i++)
            {
                try {
                    JSONObject oneObject = jArray.getJSONObject(i);
                    // Pulling items from the array
                    String main = oneObject.getString("main");
                    String description = oneObject.getString("description");
                    Log.i("main",main);
                    Log.i("description",description);






                } catch (JSONException e) {
                    // Oops
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }
}

这是OneFragment

package com.example.dell.myop.fragments;

/**
 * Created by Dell on 13-09-2016.
 */
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.example.dell.myop.DownloadTask;
import com.example.dell.myop.MainActivity;
import com.example.dell.myop.R;

import com.example.dell.myop.R;


public class OneFragment extends Fragment{







    public OneFragment() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);




    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_one, container, false);
        TextView textView = (TextView) view.findViewById(R.id.textView);

        textView.setText(description);
        return view;
    }




}

3 个答案:

答案 0 :(得分:0)

将一个函数setDescription(String text)添加到片段中。在活动中,您将获得片段然后调用该函数。该函数应设置textview。

答案 1 :(得分:0)

要将AsyncTask中的值传递回启动它的Activity,可以将Activity对象注入Task,然后调用Activity对象的方法来传回结果。

在您的情况下,您可以覆盖DownloadTask构造函数以将Activity作为参数。然后,当任务完成时,您可以调用一个方法,例如activity.setDescription(description)为活动提供价值。然后,Activity将更改片段的UI。

我也是Android新手,请原谅我,如果有更好的方法可以做到这一点。

答案 2 :(得分:0)

使用类似的东西,从活动发送

 EditOption editOption = new EditOption();-- your fragment 
            Bundle args = new Bundle();
            args.putInt("id", z);
            args.putString("title",title);
            args.putString("desc",des);
            editOption.setArguments(args);
片段中的

            String title = getArguments().getString("title");
            String des = getArguments().getString("desc");
            z=  getArguments().getInt("id");

根据您的情况编辑代码,

希望这个帮助