android學習之fragment的簡單使用

<pre name="code" class="java">package com.example.myexercise;

import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.RadioGroup;

public class MainActivity extends AppCompatActivity {
RadioGroup radioGroup;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        radioGroup = (RadioGroup) findViewById(R.id.my_radiogroup);
        radioGroup.setOnCheckedChangeListener(OnCheckedChangeListener);
    }

    RadioGroup.OnCheckedChangeListener OnCheckedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup radioGroup, int i) {
            switch (i){
                case R.id.first:
                    Intent intent = new Intent(MainActivity.this,MainActivity2.class);
                    startActivity(intent);
                    break;

                case R.id.second:
                    FirstFragment firstFragment = new FirstFragment();
                    FragmentManager fragmentManager = getFragmentManager();
                    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                    fragmentTransaction.add(R.id.content,firstFragment);
                    //返回之前的狀態
                    fragmentTransaction.addToBackStack(null);
                    fragmentTransaction.commit();
                    break;

                case R.id.third:
                    Intent intent1 = new Intent(MainActivity.this,MainActivity3.class);
                    startActivity(intent1);
                    break;

                case R.id.fourth:
                    Intent intent2 = new Intent(MainActivity.this,MainActivity4.class);
                    startActivity(intent2);
                    break;
            }
        }
    };
}

package com.example.myexercise;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/7/9 0009.
 */
public class MainActivity2 extends Activity{
    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_fragment);
        tv = (TextView) findViewById(R.id.first_textview);
        //靜態加載的fragment可以通過findviewbyid直接找到fragment裏面的控件
        Button button = (Button) findViewById(R.id.first_button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tv.setText("我改變了");
            }
        });
    }


}

package com.example.myexercise;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/7/12 0012.
 */
public class MainActivity3 extends Activity {
    LinearLayout linearLayout;
    TextView textView;
    Button button;
    boolean oneOrTwo = true;
    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;
    Fragment one;
    Fragment two;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.first_fragment_view);
        initViews();
        fragmentManager = getFragmentManager();
        fragmentTransaction = fragmentManager.beginTransaction();
        one = new SecondFragment();
        two = new ThirdFragment();
        fragmentTransaction.add(R.id.layout,one);
        fragmentTransaction.commit();
    }

    private void initViews(){
        linearLayout = (LinearLayout) findViewById(R.id.layout);
        textView = (TextView) findViewById(R.id.first_textview);
        button = (Button) findViewById(R.id.first_button);
        button.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()){
                case R.id.first_button:
                    changeFragment();
                    break;
            }
        }
    };

    /**
     * 切換fragment
     */
    private void changeFragment(){
        fragmentTransaction = fragmentManager.beginTransaction();
        if(oneOrTwo){
            fragmentTransaction.replace(R.id.layout,two);
            fragmentTransaction.commit();
            oneOrTwo = false;
        }else{
            fragmentTransaction.replace(R.id.layout,one);
            oneOrTwo = true;
            fragmentTransaction.commit();
        }
    }
}

package com.example.myexercise;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by Administrator on 2016/7/12 0012.
 */
public class MainActivity4 extends Activity implements FourthFragment.MyListener{
    private EditText editText;
    private Button button;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main4);
        initViews();
    }

    private void initViews(){
        editText = (EditText) findViewById(R.id.edit);
        button = (Button) findViewById(R.id.send);
        button.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(view.getId() == R.id.send){
                String text = editText.getText().toString();
                FourthFragment fourthFragment = new FourthFragment();
                Bundle bundle = new Bundle();
                bundle.putString("name",text);
                fourthFragment.setArguments(bundle);
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                //第三個參數時動態的給fragment設置tag(標籤)
                fragmentTransaction.add(R.id.zzz,fourthFragment,"fragment5");
                fragmentTransaction.commit();
                Toast.makeText(MainActivity4.this,"數據發送成功",Toast.LENGTH_SHORT).show();
            }
        }
    };

    @Override
    public void sendData(String aaa) {
        Toast.makeText(MainActivity4.this,aaa,Toast.LENGTH_SHORT).show();
    }
}

package com.example.myexercise;


import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/7/9 0009.
 */

public class FirstFragment extends Fragment {

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        /**
         * 參數1:需要加載的佈局文件
         * 參數2:包裹此佈局文件的父viewgroup
         * 參數3:是否返回父viewGroup
         */
      // View view = inflater.inflate(R.layout.first_fragment_view,container,false);
        View view = inflater.inflate(R.layout.first_fragment_view,null);
        TextView textView = (TextView) view.findViewById(R.id.first_textview);
        textView.setText("我就日了狗了");
        return view;
    }
}

package com.example.myexercise;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/7/12 0012.
 */
public class SecondFragment extends Fragment {

    //啓動fragment->屏幕鎖屏->屏幕解鎖->切換到其他fragment->回到桌面->回到應用->退出fragment

    /**
     * 當fragment被添加到Activity時,會回調這個方法,並且只調用一次
     */
    @Override
    public void onAttach(Context context) {
        Log.i("fragment1","onAttach");
        super.onAttach(context);
    }

    /**
     * 創建fragment時會回調此方法,並且只調用一次
     * @param savedInstanceState
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i("fragment1","onCreate");
        super.onCreate(savedInstanceState);
    }

    /**
     * 當activity要得到fragment的layout時,調用此方法,fragment在其中創建自己的layout(界面)。
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.first_fragment_view,container,false);
        TextView textView = (TextView) view.findViewById(R.id.first_textview);
        textView.setText("我是fragment1");
        Log.i("fragment1","onCreateView");
        return view;
    }

    /**
     * 當所在Activity啓動完成後調用
     * @param savedInstanceState
     */
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.i("fragment1","onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * 啓動fragment
     */
    @Override
    public void onStart() {
        Log.i("fragment1","onStart");
        super.onStart();
    }

    /**
     * 恢復fragment時會被回調,調用onstart()方法後一定會調用onResume()方法
     */
    @Override
    public void onResume() {
        Log.i("fragment1","onResume");
        super.onResume();
    }

    /**
     * 暫停fragment時會回調此方法
     */
    @Override
    public void onPause() {
        Log.i("fragment1","onPause");
        super.onPause();
    }

    /**
     * 停止fragment時會回調此方法
     */
    @Override
    public void onStop() {
        Log.i("fragment1","onStop");
        super.onStop();
    }

    /**
     * 銷燬fragment所包含的視圖
     */
    @Override
    public void onDestroyView() {
        Log.i("fragment1","onDestroyView");
        super.onDestroyView();
    }

    /**
     * 銷燬fragment時回調
     */
    @Override
    public void onDestroy() {
        Log.i("fragment1","onDestroy");
        super.onDestroy();
    }


    /**
     * 當fragment被從activity中刪掉時被調用。
     */
    @Override
    public void onDetach() {
        Log.i("fragment1","onDetach");
        super.onDetach();
    }
}

package com.example.myexercise;

import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

/**
 * Created by Administrator on 2016/7/12 0012.
 */
public class ThirdFragment extends Fragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Log.i("fragment2","onCreate");
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onAttach(Context context) {
        Log.i("fragment2","onAttach");
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.first_fragment_view,container,false);
        TextView textView = (TextView) view.findViewById(R.id.first_textview);
        textView.setText("我是fragment2");
        Log.i("fragment2","onCreateView");
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Log.i("fragment2","onActivityCreated");
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onStart() {
        Log.i("fragment2","onStart");
        super.onStart();
    }

    @Override
    public void onResume() {
        Log.i("fragment2","onResume");
        super.onResume();
    }

    @Override
    public void onPause() {
        Log.i("fragment2","onPause");
        super.onPause();
    }

    @Override
    public void onStop() {
        Log.i("fragment2","onStop");
        super.onStop();
    }

    @Override
    public void onDestroy() {
        Log.i("fragment2","onDestroy");
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        Log.i("fragment2","onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onDetach() {
        Log.i("fragment2","onDetach");
        super.onDetach();
    }
}

package com.example.myexercise;

import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Administrator on 2016/7/12 0012.
 */
public class FourthFragment extends Fragment {
    private MyListener listener;
    public interface MyListener{
        void sendData(String aaa);
    }



    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        super.onAttach(activity);
        listener = (MyListener) activity;
        listener.sendData("感謝你發送過來的數據包");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.first_fragment_view,container,false);
        TextView textView = (TextView) view.findViewById(R.id.first_textview);
        textView.setText("我是fragment4");
        String text = (String) getArguments().get("name");
        textView.setText(text);
        Toast.makeText(getActivity(),"成功接收到Activity發過來的數據",Toast.LENGTH_SHORT).show();
        return view;
    }


}

activity_main.xml:


<pre name="code" class="plain"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.example.myexercise.MainActivity">

    <LinearLayout
        android:id="@+id/content"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:orientation="vertical"
        android:layout_weight="5"
        ></LinearLayout>

    <RadioGroup
        android:id="@+id/my_radiogroup"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:orientation="horizontal">

        <RadioButton
            android:id="@+id/first"
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="match_parent"
            android:drawableTop="@mipmap/ic_launcher"
            android:text="靜態"
            android:gravity="center"
            android:button="@null"/>

        <RadioButton
            android:id="@+id/second"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:drawableTop="@mipmap/ic_launcher"
            android:text="動態"
            android:gravity="center"
            android:button="@null"/>

        <RadioButton
            android:id="@+id/third"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:drawableTop="@mipmap/ic_launcher"
            android:text="靜態"
            android:gravity="center"
            android:button="@null"/>

        <RadioButton
            android:id="@+id/fourth"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:drawableTop="@mipmap/ic_launcher"
            android:text="靜態"
            android:gravity="center"
            android:button="@null"/>
    </RadioGroup>
</LinearLayout>

first_fragment.xml:


<pre name="code" class="plain"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="我是標題"
        android:gravity="center"/>
    <!--通過靜態加載時必須給id或者tag-->
    <fragment
        android:id="@+id/fist_fragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.example.myexercise.FirstFragment"
        android:tag="wocalei"
        tools:layout="@layout/first_fragment_view" />
</LinearLayout>

first_fragment_view.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"
    android:gravity="center"
    android:id="@+id/layout"
    >

    <TextView
        android:id="@+id/first_textview"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="我是靜態的fragment"/>

    <Button
        android:id="@+id/first_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="改變"/>
</LinearLayout>

main4.xml:


<pre name="code" class="plain"><?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"
    android:id="@+id/zzz">

    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/send"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="發送數據"/>
</LinearLayout>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章