Android开发-Fragment之间传值-2-AndroidStudio

修改了之前博客中MainActivity,直接实例化3个Fragment,然后进行隐藏和显示,通过MyData的position。

我们来看下具体代码:

AndroidManiFest.xml:

xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iwanghang.fragmenttransactiondemo">

    
    android:name="android.permission.INTERNET" />

            android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        android:name=".MainActivity"
            android:screenOrientation="portrait">
            
                android:name="android.intent.action.MAIN" />

                android:name="android.intent.category.LAUNCHER" />
            
        
    

    
    

MainActivity.java:

package com.iwanghang.fragmenttransactiondemo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;

/**
 * 实现OnItemClickListener(Item点击事件监听),OnClickListener(按钮点击事件监听)
 * 刷新
 * 个推
 * Volley:第三方插件 主要用于post、get解析
 */

public class MainActivity extends FragmentActivity implements OnClickListener{

   private LinearLayout oneLinearLayout;
   private LinearLayout twoLinearLayout;
   private LinearLayout threeLinearLayout;
   private OneFragment oneFragment;
   private TwoFragment twoFragment;
   private ThreeFragment threeFragment;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      initView();
      initFragment();
      showOneFragment();
   }

   private void initView() {
      oneLinearLayout = (LinearLayout)this.findViewById(R.id.oneLinearLayout);
      twoLinearLayout = (LinearLayout)this.findViewById(R.id.twoLinearLayout);
      threeLinearLayout = (LinearLayout)this.findViewById(R.id.threeLinearLayout);
      oneLinearLayout.setOnClickListener(this);
      twoLinearLayout.setOnClickListener(this);
      threeLinearLayout.setOnClickListener(this);
   }

   private void initFragment() {
      //从 FragmentManager 获得一个FragmentTransaction的实例 :
      FragmentManager fragmentManager = getSupportFragmentManager();
      //FragmentTransaction对fragment进行添加,移除,替换,以及执行其他动作。
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      //每一个事务都是同时要执行的一套变化.可以在一个给定的事务中设置你想执行的所有变化,
      // 使用诸如 add(), remove(), 和 replace().然后, 要给activity应用事务, 必须调用 commit().

      oneFragment = new OneFragment();
      twoFragment =  new TwoFragment();
      threeFragment =  new ThreeFragment();
      //将Fragment two设置成Fragment one的目标 Fragment 然后Fragment two就可以接收Fragment one发送的消息了
      oneFragment.setTargetFragment(twoFragment, OneFragment.requestCode);
      //将Fragment one设置成Fragment two的目标 Fragment 然后Fragment one就可以接收Fragment two发送的消息了
      twoFragment.setTargetFragment(oneFragment, TwoFragment.requestCode);
      //这样Fragment one和 Fragment two就能够实现互相通信了

      fragmentTransaction.add(R.id.oneFragment_container, oneFragment);
      fragmentTransaction.add(R.id.twoFragment_container,twoFragment);
      fragmentTransaction.add(R.id.threeFragment_container,threeFragment);
      fragmentTransaction.hide(twoFragment); // 隐藏twoFragment
      fragmentTransaction.hide(threeFragment); // 隐藏threeFragment
      //一定要记得提交
      fragmentTransaction.commit();
   }

   @Override
   public void onClick(View arg0) {
      switch (arg0.getId()) {
         case R.id.oneLinearLayout:
            showOneFragment();
            break;
         case R.id.twoLinearLayout:
            showTwoFragment();
            break;
         case R.id.threeLinearLayout:
            showThreeFragment();
            break;
         default:
            break;
      }
   }

   /**
    * 切换到OneFragment
    */
   public void showOneFragment() {
      FragmentManager fragmentManager = getSupportFragmentManager();
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      fragmentTransaction.show(oneFragment);
      fragmentTransaction.hide(twoFragment);
      fragmentTransaction.hide(threeFragment);
      //一定要记得提交
      fragmentTransaction.commit();
   }

   /**
    * 切换到TwoFragment
    */
   public void showTwoFragment() {
      FragmentManager fragmentManager = getSupportFragmentManager();
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      fragmentTransaction.hide(oneFragment);
      fragmentTransaction.show(twoFragment);
      fragmentTransaction.hide(threeFragment);
      //一定要记得提交
      fragmentTransaction.commit();
   }

   /**
    * 切换到ThreeFragment
    */
   public void showThreeFragment() {
      FragmentManager fragmentManager = getSupportFragmentManager();
      FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
      fragmentTransaction.hide(oneFragment);
      fragmentTransaction.hide(twoFragment);
      fragmentTransaction.show(threeFragment);
      //一定要记得提交
      fragmentTransaction.commit();
   }

}

MyData.java:

package com.iwanghang.fragmenttransactiondemo;

import java.io.Serializable;

public class MyData implements Serializable {
    public int position;

    public int getPosition() {
        return position;
    }

    public void setPosition(int position) {
        this.position = position;
    }
}

OneFragment.java:

package com.iwanghang.fragmenttransactiondemo;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

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

import java.util.ArrayList;
import java.util.List;

/**
 * 实现OnItemClickListener(Item点击事件监听),OnClickListener(按钮点击事件监听)
 */

public class OneFragment extends Fragment implements OnItemClickListener {

   /**
    * item
    */
   private ListView listViewTask;
   private List list;
   private LayoutInflater inflater;
   private TaskAdapter taskAdapter;

   /**
    * MainActivity
    */
   private MainActivity mainActivity;

   /**
    * Json
     */
   private String title;
   private Volley4Json volley4Json;

   /**
    * 传值
     */
   public static int requestCode = 0;
   public static String key = "OneFragment.key";

   //onAttach(),当fragment被绑定到activity时被调用(Activity会被传入.).
   @Override
   public void onAttach(Context context) {
      super.onAttach(context);
      mainActivity = (MainActivity) context;
   }

   //onCreateView(),创建和fragment关联的view hierarchy时调用.
   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

      /**
       * 实例化volley4Json
       */
      volley4Json = new Volley4Json(mainActivity);
      /**
       * UI组件初始化
       */
      View view = inflater.inflate(R.layout.fragment_one,null);
      /**
       * item初始化
       */
      listViewTask = (ListView) view.findViewById(R.id.listViewTask);
      /**
       * 解析Json
       */
      list = new ArrayList();
      volley4Json.getJsonResult(new Volley4Json.VolleyCallBack() {
         @Override
         public void onSuccess(JSONObject result) {
            /**
             * 解析Json中的标题 并设置到 list
             */
            try {
               JSONArray jsonArray = result.getJSONArray("data");
               for (int i = 0; i < jsonArray.length(); i++) {
                  JSONObject obj2 = jsonArray.getJSONObject(i);
                  Log.e("TAG", obj2.getString("title"));
                  title = obj2.getString("title");
                  list.add(i + " . " + title);
               }
               taskAdapter = new TaskAdapter();
               listViewTask.setAdapter(taskAdapter);
            } catch (JSONException e) {
               e.printStackTrace();
            }
         }
      });

      /**
       * Item点击事件监听
       */
      listViewTask.setOnItemClickListener(this);

      return view;
   }

   @Override
   public void onItemClick(AdapterView parent, View view, int position, long id) {

      MyData data = new MyData();
      data.setPosition(position);
      Intent intent = new Intent();
      intent.putExtra(key, data);
      //用于发送消息给Fragment two
      getTargetFragment().onActivityResult(requestCode, Activity.RESULT_OK, intent);

      mainActivity.showTwoFragment();
   }

   public class TaskAdapter extends BaseAdapter {
      public TaskAdapter() {
         super();
         inflater = LayoutInflater.from(mainActivity);
      }

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

      @Override
      public Object getItem(int position) {
         return list.get(position);
      }

      @Override
      public long getItemId(int position) {
         return position;
      }

      @Override
      public View getView(int position, View convertView, ViewGroup parent) {
         View view = convertView;
         if (view == null) {
            view = inflater.inflate(R.layout.item_task_list, parent, false);
            ViewHolder viewHolder = new ViewHolder();
            viewHolder.content = (TextView) view.findViewById(R.id.textView_task);
            view.setTag(viewHolder);
         }
         ViewHolder viewHolder = (ViewHolder) view.getTag();
         viewHolder.content.setText(list.get(position));
         return view;
      }
   }

   private class ViewHolder {
      private TextView content;
   }

}
TwoFragment.java:

package com.iwanghang.fragmenttransactiondemo;

import android.app.Activity;
import android.content.Intent;
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;

/*
 * 用于实现Fragment通信的例子
 * 定义了一个TextView用来显示Fragment one发过来的信息
 * 定义了一个EditText用力啊输入发送给Fragment one的内容
 * 定义了一个Button用来触发发送消息的事件
 * 定义了一个MyData 序列化对象用来存储数据
 * */

public class TwoFragment extends Fragment {

   private View view;
   private int position;
   private TextView twoFragmentText;

   public static int requestCode = 1;
   public static String key = "TwoFragment.key";

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

      System.out.println("TwoFragment onCreateView");

      view = inflater.inflate(R.layout.fragment_two, container,false);

      return view;
   }

   //该方法用来接收 Fragment one发送过来的消息
   @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
      if( resultCode != Activity.RESULT_OK)
         return ;
      if( requestCode == OneFragment.requestCode)
      {
         MyData mydata = (MyData) data.getSerializableExtra(OneFragment.key);
         System.out.println("TwoFragment mydata = " + mydata.toString());
         String positionString = String.valueOf(mydata.getPosition());
         System.out.println("TwoFragment positionString = " + positionString);

         twoFragmentText = (TextView) view.findViewById(R.id.twoFragmentText);
         twoFragmentText.setText(positionString);
      }
   }
}
ThreeFragment.java:

package com.iwanghang.fragmenttransactiondemo;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class ThreeFragment extends Fragment {

   private View rootView;

   @Override
   public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      if(container==null)
         return null;
      rootView = inflater.inflate(R.layout.fragment_three, container,false);

      return rootView;
   }


}
Volley4Json.java:

package com.iwanghang.fragmenttransactiondemo;

import android.content.Context;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

public class Volley4Json {

    public static Context context;
    public Volley4Json(Context context){
        this.context = context;
    }

    /**
     * 获取Json
     */
    public static void getJsonResult(final VolleyCallBack volleyCallBack) {
        // 初始化一个请求队列
        RequestQueue requestQueue = Volley.newRequestQueue(context);
        // json串: http://www.ytiantuan.com//api.php/index/index.html
        String jsonUrl = "http://api.zsreader.com/v2/pub/channel/list?&page=1&tp=1&size=20";
        // 根据给定的URL新建一个请求
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, jsonUrl, null, new Response.Listener() {
            @Override
            public void onResponse(JSONObject response) {
                // 在这里操作UI组件是安全的,因为响应返回时这个函数会被post到UI线程来执行
                // 在这里尽情蹂躏响应的response。

                volleyCallBack.onSuccess(response);

                //成功的回调
                //System.out.println("成功返回:"+ response.toString());
            }
        }, new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError error) {
                // 出错了怎么办?凉拌!并且在这里拌。
                System.out.println("发生了一个错误!");
                error.printStackTrace();
            }
        });
        // 把这个请求加入请求队列
        requestQueue.add(jsonObjectRequest);
    }

    /**
     * VolleyCallback
     */
    public interface VolleyCallBack{
        void onSuccess(JSONObject result);
    }
}

你可能感兴趣的:(JAVA,Android,AndroidFragment)