android 之Fragment的详解
友情鏈接:點擊打開鏈接
1.將Activity傳值到Fragment
具體步驟:
<1>聲明碎片事務器對象
private FragmentManager fragmentManager;
<2>得到碎片事務器對象
FragmentTransaction fragmentTransaction ?= this.FragmentManager.beginTransaction();
<3>將我們需要添加的Fragment對象作為子元素添加到LinearLayout的Container容器中
fragmentTransaction.add(R.id.linearLayout_container,Fragment);
<4>將之前添加的Fragment對象也向Fragment的返回棧添加一份
fragmentTransaction.addBackStack(null);
<5>提交碎片事務,提交之后的操作才會生效。
fragmentTransaction.commit();
具體效果:
實例代碼:
業務邏輯代碼:
package com.example.tf.fragment_demo;import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.example.tf.fragment_demo.fragments.OneFragment; import com.example.tf.fragment_demo.fragments.TwoFragment;public class MainActivity extends AppCompatActivity {/*** 聲明碎片管理器對象*/private FragmentManager fragmentManager;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//1.得到碎片管理器對象this.fragmentManager=this.getFragmentManager();}//private OneFragment oneFragment=new OneFragment();//多次添加同一個地址報錯private OneFragment oneFragment;/*** 添加Fragment* 注意:同一個fragment對象只能往同一個容器中添加一次,如果多次添加會報異常:java.lang.IllegalStateException: Fragment already added: OneFragment{5352c090 #0 id=0x7f0c0053}* @param view*/public void add(View view){oneFragment=new OneFragment();//2.通過碎片管理器對象得到碎片事務對象FragmentTransaction fragmentTransaction=this.fragmentManager.beginTransaction();//將oneFragment對象作為linearLayout_container的子元素添加到linearLayout_container容器里面fragmentTransaction.add(R.id.linearLayout_container,oneFragment);//將之前添加到容器linearLayout_container里面的fragment 也添加到fragment 返回棧中一份fragmentTransaction.addToBackStack(null);//提交碎片事務,提交之后之前的操作才會生效fragmentTransaction.commit();System.out.println("===add=====");}private TwoFragment twoFragment;/*** 修改Fragment* @param view*/public void update(View view){//2.通過碎片管理器對象得到碎片事務對象FragmentTransaction fragmentTransaction=this.fragmentManager.beginTransaction();twoFragment=new TwoFragment();//使用TwoFragment 替換LinearLayout 容器中的其它子元素,如果之前添加了多個子元素,則只替換其中部分子元素//replace 在替換指定Fragment 對象時會首先判斷LinearLayout容器中是否有子元素,如果沒有則直接添加一個子元素fragmentTransaction.replace(R.id.linearLayout_container,twoFragment);//提交碎片事務,提交之后之前的操作才會生效fragmentTransaction.commit();System.out.println("===update=====");}/*** 刪除Fragment* @param view*/public void delete(View view){//2.通過碎片管理器對象得到碎片事務對象FragmentTransaction fragmentTransaction=this.fragmentManager.beginTransaction();//將twoFragment對象從碎片事務管理器中刪除,即從指定容器中刪除了fragmentTransaction.remove(twoFragment);//提交碎片事務,提交之后之前的操作才會生效fragmentTransaction.commit();System.out.println("===delete=====");} }主UI視圖的xml代碼:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="添加"android:onClick="add"android:textSize="30sp"android:id="@+id/button_add"android:layout_alignParentTop="true"android:layout_alignParentStart="true"android:layout_marginTop="127dp" /><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="修改"android:onClick="update"android:textSize="30sp"android:id="@+id/button_update"android:layout_centerVertical="true"android:layout_alignParentStart="true" /><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="刪除"android:onClick="delete"android:textSize="30sp"android:id="@+id/button_delete"android:layout_marginTop="52dp"android:layout_below="@+id/button_update"android:layout_alignParentStart="true" /><!--如果想同時實現水平和垂直兩個方向的滾動操作,則可以使用ScrollView 嵌套HorizontalScrollView或者HorizontalScrollView嵌套ScrollView都可以實現水平和垂直兩個方向的滾動操作--><ScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_toEndOf="@+id/button_add"><HorizontalScrollViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:layout_toEndOf="@+id/button_add"><LinearLayoutandroid:id="@+id/linearLayout_container"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_alignParentTop="true"android:layout_toEndOf="@+id/button_add"></LinearLayout></HorizontalScrollView></ScrollView></RelativeLayout><1>第一個Fragment.java
package com.example.tf.fragment_demo.fragments;import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;import com.example.tf.fragment_demo.R;import java.util.zip.Inflater;/*** Created by TF on 2018/6/13.*/ public class OneFragment extends Fragment {@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {return inflater.inflate(R.layout.fragment_one,null);} }<2>第二個Fragment.java
同上,基本沒有區別
[1]第一個的xml布局代碼:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="我是OneFragment we help each other and we love each other love me love my dog"android:singleLine="true"android:gravity="center"android:textSize="30sp"android:id="@+id/textView_one" /> </LinearLayout>[2]第二個的xml布局代碼:
同上,與第一個沒有區別
2.將Fragment傳值給Activity
1.得到Fragment所依附的Activity并通過findViewById()查找控件并賦值。 ?
2.通過得到fragment所依附的Activity并給Activity提供setter函數傳值到Activity或者讓Activity實現傳值的
接口來實現。
實例效果:
業務邏輯代碼:
主類代碼:
package com.example.lenovo.dialog_demo;import android.content.DialogInterface; import android.preference.DialogPreference; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast;import com.example.lenovo.dialog_demo.interfaces.PassValue;import org.w3c.dom.Text;import java.lang.reflect.Field;public class MainActivity extends AppCompatActivity implements PassValue{private TextView textView_name;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);textView_name = (TextView) this.findViewById(R.id.textView_name);}//通過setter函數傳值到當前Activity@Overridepublic void setName(String name) {textView_name.setText(name);} }副類代碼:
package com.example.lenovo.dialog_demo.fragments;import android.app.Fragment; import android.os.Bundle; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.EditText;import com.example.lenovo.dialog_demo.R; import com.example.lenovo.dialog_demo.interfaces.PassValue;public class DetailFragment extends Fragment{private EditText editText_userName;@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view = inflater.inflate(R.layout.fragment_detail,container,false);editText_userName = (EditText) view.findViewById(R.id.editText_userName);Button button_pass = (Button) view.findViewById(R.id.button_pass);button_pass.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String userName = editText_userName.getText().toString();if(TextUtils.isEmpty(userName)){editText_userName.setError("用戶名不能為空");editText_userName.requestFocus();return;}//得到當前Fragment所依附的Activity//MainActivity mainActivity = (MainActivity) getActivity();//方式一:找到Activity中的TextView控件//TextView textView_name = mainActivity.findViewById(R.id.textView_name);//textView_name.setText(userName);//方式二:給Activity增加setter函數傳值給Activity//mainActivity.setName(userName);//使用接口完成通用傳值操作PassValue passValue = (PassValue) getActivity();passValue.setName(userName);}});return view;} }定義一個接口:
package com.example.lenovo.dialog_demo.interfaces;public interface PassValue {void setName(String name); }用戶界面的xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="match_parent"><LinearLayoutandroid:id="@+id/linearLayout_left"android:orientation="vertical"android:layout_weight="1"android:layout_height="match_parent"android:layout_width="match_parent"><fragmentandroid:id="@+id/fragment"android:layout_width="match_parent"android:layout_height="wrap_content"android:name="com.example.lenovo.dialog_demo.fragments.DetailFragment"/></LinearLayout><LinearLayoutandroid:id="@+id/linearLayout_right"android:orientation="vertical"android:layout_weight="1"android:layout_width="match_parent"android:layout_height="match_parent"><TextViewandroid:layout_width="match_parent"android:layout_height="match_parent"android:gravity="center"android:text="姓名"android:textSize="30sp"android:id="@+id/textView_name"/></LinearLayout></LinearLayout>用戶輸入界面的xml:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"><EditTextandroid:layout_width="match_parent"android:layout_height="wrap_content"android:hint="請輸入你的姓名"android:id="@+id/editText_userName"/><Buttonandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:text="傳值到Activity"android:id="@+id/button_pass"/> </LinearLayout>3.Fragment傳值給Fragment(中心思想:并不是傳值,而是通過查找目標控件,將要傳的值"塞"給"目標控件")。
注意:一個Fragment的子類listFragment
繼承listFragment有哪些好處?
A.自帶界面并且界面上有一個ListView,這個ListView對象為mList
B.點擊用戶界面獲取數據時,監聽器不用自己寫,ListFragment已經封裝好了,可以直接使用
主要方式:一個Fragment得到FragmentManager查找到另一個Fragment。
1.并通過setter函數查找控件并賦值。
2.getView方法得到view查找控件并賦值。
FragmentLeft(要傳值的):
package com.hsj.example.fragmentpassvaluetofragmentdemo05.fragments;import android.app.ListFragment; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView;import com.hsj.example.fragmentpassvaluetofragmentdemo05.R;import java.util.ArrayList; import java.util.List;/*** 繼承ListFragment 有哪些好處?* A:自帶界面并且界面上有一個ListView,通過查看源碼發現這個ListView 對象為mList* B:點擊用戶條目獲取數據時監聽器不用自己編寫,ListFragment 已經封裝好了,我們直接使用*/ public class LeftFragment_bak01 extends ListFragment {private List<String> data;@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);data=new ArrayList<>();for(int i=0;i<20;i++){data.add("小麗"+i);}ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,data);setListAdapter(adapter);}/*** 當用戶點擊ListView控件上的條目時自動調用的方法* @param l* @param v* @param position* @param id*/@Overridepublic void onListItemClick(ListView l, View v, int position, long id) {String item=data.get(position);//由于現在LeftFragment 和RightFragment 使用的是同一個FragmentManager 添加到MainActivity 界面上的,因此可以通過FragmentManager 找到需要的Fragment////TextView textView_name= (TextView) getActivity().getFragmentManager().findFragmentById(R.id.fragment_right).getView().findViewById(R.id.textView_name);//textView_name.setText(item);//Toast.makeText(getActivity(), "item="+item, Toast.LENGTH_SHORT).show();RightFragment rightFragment= (RightFragment) getActivity().getFragmentManager().findFragmentById(R.id.fragment_right);//rightFragment.setName(item);} }FragmentRight(接受的):
package com.hsj.example.fragmentpassvaluetofragmentdemo05.fragments;import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.TextView;import com.hsj.example.fragmentpassvaluetofragmentdemo05.R;/*** Created by hsjwcf on 2018/6/14.*/ public class RightFragment extends Fragment {private TextView textView_name;@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view=inflater.inflate(R.layout.fragment_right,null);textView_name= (TextView) view.findViewById(R.id.textView_name);LeftFragment leftFragment= (LeftFragment) getActivity().getFragmentManager().findFragmentById(R.id.fragment_left);ListView listView=leftFragment.getListView();listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {//1.通過適配器控件獲取數據//String item=parent.getItemAtPosition(position).toString();//textView_name.setText(item);//2.通過用戶點擊的條目獲取數據String item=((TextView)view).getText().toString();textView_name.setText(item);}});return view;}}3.注意:萬能的接口回調(適合所有的處置方式):
使用步驟:
1.自定義傳值的接口:
? ? interface PassValue{
????? ? void setName(String name);
}
2.聲明一個接口類型的對象:
private PassValue passvalue
3.給接口類型的對象提供setter函數:
public void setPassValue(PassValue passvalue){
????? ? this.passvalue = passvalue;
}
4.在傳值的目標端(RightFragment)調用setter函數
5.在需要傳值的地方調用PassValue接口類型的對象passValue.setValue(需要傳遞的值)
1.leftFragment:
package com.hsj.example.omnipotentinterfacecallbackdemo06.fragments;import android.app.ListFragment; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView;import java.util.ArrayList; import java.util.List;/*** 萬能的接口回調的編寫步驟:* 1.自定義傳值的接口* interface PassValue{void setName(String name);}2.聲明一個接口類型的對象private PassValue passValue;3.給接口類型的對象提供setter 函數public void setPassValue(PassValue passValue){this.passValue=passValue;}4.在需要傳值的目標對象中調用setter函數,相當于注冊監聽器對象LeftFragment leftFragment= (LeftFragment) getActivity().getFragmentManager().findFragmentById(R.id.fragment_left);//相當于注冊監聽器leftFragment.setPassValue(new LeftFragment.PassValue() {@Overridepublic void setName(String name) {textView_name.setText(name);}});5.在需要傳值的地方調用傳值對象的傳值方法完成傳值操作passValue.setName(item);**/ public class LeftFragment extends ListFragment {private List<String> data;//1.自定義傳值的接口interface PassValue{void setName(String name);}//2.聲明一個接口類型的對象private PassValue passValue;//3.給接口類型的對象提供setter 函數public void setPassValue(PassValue passValue){this.passValue=passValue;}@Overridepublic void onActivityCreated(Bundle savedInstanceState) {super.onActivityCreated(savedInstanceState);data=new ArrayList<>();for(int i=0;i<20;i++){data.add("小麗"+i);}ArrayAdapter<String> adapter=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_list_item_1,data);setListAdapter(adapter);}/*static class Add{int add(int num1,int num2){int sum=num1+num2;return sum;}}static class Test{public static void main(String[] args){Add a=new Add();a.add(5,6);}}*/@Overridepublic void onListItemClick(ListView l, View v, int position, long id) {String item= data.get(position);//執行傳值操作,相當于用戶點擊了按鈕passValue.setName(item);} }2.rightFragment:
package com.hsj.example.omnipotentinterfacecallbackdemo06.fragments;import android.app.Fragment; import android.os.Bundle; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView;import com.hsj.example.omnipotentinterfacecallbackdemo06.R;/*** Created by hsjwcf on 2018/6/14.*/ public class RightFragment extends Fragment {private TextView textView_name;@Nullable@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {View view=inflater.inflate(R.layout.fragment_right,null);textView_name= (TextView) view.findViewById(R.id.textView_name);LeftFragment leftFragment= (LeftFragment) getActivity().getFragmentManager().findFragmentById(R.id.fragment_left);//相當于注冊監聽器/*leftFragment.setPassValue(new LeftFragment.PassValue() {@Overridepublic void setName(String name) {textView_name.setText(name);}});*/MyPassValue myPassValue=new MyPassValue();leftFragment.setPassValue(myPassValue);return view;}class MyPassValue implements LeftFragment.PassValue{@Overridepublic void setName(String name) {textView_name.setText(name);}}}總結
以上是生活随笔為你收集整理的android 之Fragment的详解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 商业承兑汇票风险大的原因是什么?
- 下一篇: android 之SharedPrefe