如何为从另一个片段接收的片段的textview设置值?

时间:2017-04-15 09:13:14

标签: android android-fragments bundle textview

当从另一个片段接收到值时,我不知道如何设置第二个片段的textview。我在第二个片段中收到的数据是StringList的"值" 对象,但我现在不知道如何为它设置数据。

StringList类:

public class StringList {

    public String authorName;
    public String headline;
    public String publishedTime;
    public String newsDetail;

}

MainActivity:

//only useful code pasted below for tranfering thre value from fragment to another fragment and i have implemented the TransferValue to the mainActivity

        public void sendValue(StringList value, int positionValue) {

            FragmentTransaction transaction = frag.beginTransaction();
            BusinessDetail businessDetail = new BusinessDetail();
            businessDetail.receiveValue(value, positionValue);
            transaction.replace(R.id.content_frame, businessDetail);
            transaction.commit();

        }

片段1:

    public class Business extends Fragment  {

        public List<StringList> businessNews = new ArrayList<>();

        TransferValue SendData;//here

        private RecyclerView recyclerView;
         public Business() {

        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

            View view = inflater.inflate(R.layout.fragment_business, container, false);
            recyclerView = (RecyclerView) view.findViewById(R.id.business_recycler_view);

            FetchLists f = new FetchLists();
            f.execute(10, 0);
            return view;
        }

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

        @Override
        public void onAttach(Context context) {
            super.onAttach(context);
    //here
            try {
                SendData = (TransferValue) context;
            } catch (ClassCastException e) {
                Log.d("ashu", "implement the methods");
                throw new ClassCastException("implemented the methods");
            }
        }

//here
        public interface TransferValue {

            public void sendValue(StringList value, int positionValue);

        }

        public class FetchLists extends AsyncTask<Integer, Void, List<StringList>> {

            @Override
            protected List<StringList> doInBackground(Integer... params) {

                int count = params[0];
                int offset = params[1];
    //api key changed
                String urlString = "https://newspi.og/v1/article?source=bloomerg&sortBy=tp&apiKey=5fdfd54f4aba5a5fdfvdf476ff528a8";
                urlString = urlString + "&count=" + count + "&offset=" + offset;

                try {
                    URL url = new URL(urlString);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    InputStream stream = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                    String line = reader.readLine();
                    String response = "";
                    while (line != null) {
                        response += line;
                        line = reader.readLine();
                    }

                    JSONObject object = new JSONObject(response);
                    JSONArray emailLists = object.getJSONArray("articles");

                    for (int i = 0; i < emailLists.length(); i++) {
                        JSONObject listData = (JSONObject) emailLists.get(i);

                        StringList stringList = new StringList();
                        stringList.authorName = listData.getString("author");
                        stringList.headline = listData.getString("title");
                        stringList.publishedTime = listData.getString("publishedAt");
                        stringList.newsDetail = listData.getString("description");

                        businessNews.add(stringList);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return businessNews;
            }

            @Override
            protected void onPostExecute(List<StringList> result) {
                super.onPostExecute(result);

                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                BusinessAdapter adapter = new BusinessAdapter(Business.this, result);
                recyclerView.setAdapter(adapter);

            }
        }

        public class BusinessAdapter extends RecyclerView.Adapter<BusinessHolder> {

            int prevposition = 0;
            private List<StringList> c;

            public BusinessAdapter(Business context, List<StringList> result) {
                c = context.businessNews;

            }

            @Override
            public BusinessHolder onCreateViewHolder(ViewGroup parent, int viewType) {

                Context context = parent.getContext();
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.layout_news, parent, false);

                return new BusinessHolder(view);
            }

            @Override
            public void onBindViewHolder(BusinessHolder holder, int position) {

                StringList m = c.get(position);
                holder.bindListName(m, position);

            @Override
            public int getItemCount() {
                return c.size();
            }
        }

        public class BusinessHolder extends RecyclerView.ViewHolder {

            public TextView headlineTextview;
            public TextView authorTextview;
            public TextView timeTextview;

            public BusinessHolder(View itemView) {
                super(itemView);

                headlineTextview = (TextView) itemView.findViewById(R.id.id_headline);
                authorTextview = (TextView) itemView.findViewById(R.id.id_author);
                timeTextview = (TextView) itemView.findViewById(R.id.id_time);

            }

            public void bindListName(final StringList stringList, final int position) {

                headlineTextview.setText(stringList.headline);
                authorTextview.setText(stringList.authorName);
                timeTextview.setText(stringList.publishedTime);

                itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                         BusinessDetail s = new BusinessDetail();
                        FragmentTransaction transaction = getFragmentManager().beginTransaction();
                        transaction.replace(R.id.content_frame, s);
                        transaction.addToBackStack(null);
                        transaction.commit();
                    } });}}}}

片段2:

public class BusinessDetail extends Fragment {

    Bundle bundle;
    private TextView headlineSecond;
    private TextView authorSecond;
    private TextView detailsSecond;
    private List<StringList> s;

    public BusinessDetail() {
    }

    public void receiveValue(StringList value, int positionValue) {

        bundle = new Bundle();
        bundle.putString("news", value.authorName);
      }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_business_detail, container, false);

        headlineSecond = (TextView) view.findViewById(R.id.id_headline_second);
        authorSecond = (TextView) view.findViewById(R.id.id_author_second);
        detailsSecond = (TextView) view.findViewById(R.id.id_details_second);

// I want to set the values received to the textview here

        return view;}}

2 个答案:

答案 0 :(得分:2)

请考虑使用newInstance模式将值传递给fragment,因为在实例化片段后调用receiveValue方法不是一个好习惯。您应该将对象定义为{{1通过Parcelable方法将其传递给新的片段。

但是,如果通过调用方法newInstance收到值,则无需使用receiveValue。如果要将值从BundleBundle传递到另一个Fragment,则会使用Activity。要保存值,您可以像使用Fragment一样定义全局变量。例如:

TextView

P.S:但是为了将来参考,您可以通过调用Bundle bundle; StringList mStringList; private TextView headlineSecond; private TextView authorSecond; private TextView detailsSecond; private List<StringList> s; public BusinessDetail() { } public void receiveValue(StringList value, int positionValue) { mStringList = value; } Bundle检索字符串值。在你的情况下,它会像:

getString(String key)

同样删除这些行,除非您尝试启动新的String value = bundle.getString("news"); yourTextView.setText(value); ,否则他们不会在您当前的片段中执行任何操作:

Fragment

有关片段与示例和代码段的通信的详细说明,您可以访问: http://www.androiddesignpatterns.com/2012/05/using-newinstance-to-instantiate.html

答案 1 :(得分:2)

您可以使用 Parcelable 从一个活动/片段向下一个活动/片段发送任何自定义类数据的arraylist。

在之前的片段中使用putParcelableArrayList方法在bundle中添加数据。例如。

bundle.putParcelableArrayList("KEY_NAME",arrayName);

在下一个frgament中使用getParcelableArrayList方法在onCreate中获取该数据。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        ArrayList<Item> itemArray = getArguments().getParcelableArrayList("KEY_NAME");
    }
}

主要的是将StringList类更改为Parcelable。对于Parcelable类示例,请单击下面的链接..

Parcelable Class