1. 程式人生 > >Android Studio 將Activity改成Fragment

Android Studio 將Activity改成Fragment

lse navig ive art tools ins schema 1.0 this

項目中遇到一個尷尬的問題,因為初學Android,所以用了大量Activity,但現在想要改成Fragment,但是Activity太多,感覺很頭大,研究了很久怎麽改,沒有看到合適的文章,但好在最後還是成功了

這裏舉一個例子,免得忘記做法了:

那麽就隨意貼一個需要修改的Activity:

public class SetActivity extends AppCompatActivity {

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

        Resources resourse 
= this.getResources(); String[] data = resourse.getStringArray(R.array.set); //android.R.layout.simple_list_item_1這是Android內置的布局文件,裏面只有一個TextView,可用於簡單顯示一段文本 ArrayAdapter<String> adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, data ); ListView listview_set
= findViewById(R.id.listview_set); listview_set.setAdapter(adapter); UsersInfo user = UsersInfo.getCurrentUser(UsersInfo.class); //設置item監聽事件 listview_set.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void
onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position){ case 0://修改密碼 Intent intent_pwdchange = new Intent(SetActivity.this, PwdchangeActivity.class); startActivity(intent_pwdchange); break; case 1://修改註冊郵箱並發送驗證 Intent intent_changeemail = new Intent(SetActivity.this, ChangeemailActivity.class); startActivity(intent_changeemail); break; case 2://修改手機號碼 Intent intent_changephone = new Intent(SetActivity.this, ChangephoneActivity.class); startActivity(intent_changephone); break; case 3://退出登錄,返回到登錄界面 UsersInfo.logOut();//退出登錄,同時清除緩存用戶對象。 Intent intent_logout = new Intent(SetActivity.this, LoginActivity.class); startActivity(intent_logout); break; case 4: Intent intent_verifyphone = new Intent(SetActivity.this, VerifyphoneActivity.class); startActivity(intent_verifyphone); break; } } }); } }

下面是對應的activity_set.xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".set.SetActivity">

    <ListView
        android:id="@+id/listview_set"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>
</LinearLayout>

復制一份activity_set.xml,還是放在layout文件裏,更名為fragment_set.xml

修改activity_set.xml代碼如下

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/contain_set"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    </FrameLayout>

</LinearLayout>

接下來新建一個fragment,名為SetFragment

把activity裏的邏輯放到frgment裏面去,註意這裏很關鍵

View view = View.inflate(getActivity(),R.layout.fragment_set,null);
其實沒有什麽改變的,就是把原本activity中onCreate()中的邏輯放到了Fragment的onCreateView()裏面去,
1、布局是通過inflate來的,
2、把this替換為getActivity()
3、findViewById->view.findViewById
public class SetFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = View.inflate(getActivity(),R.layout.fragment_set,null);

        Resources resourse = getActivity().getResources();
        String[] data = resourse.getStringArray(R.array.set);
        //android.R.layout.simple_list_item_1這是Android內置的布局文件,裏面只有一個TextView,可用於簡單顯示一段文本
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getActivity(), android.R.layout.simple_list_item_1, data
        );

        ListView listview_set = view.findViewById(R.id.listview_set);
        listview_set.setAdapter(adapter);

        UsersInfo user = UsersInfo.getCurrentUser(UsersInfo.class);

        //設置item監聽事件
        listview_set.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                switch (position){
                    case 0://修改密碼
                        Toast.makeText(getActivity(), "修改密碼!", Toast.LENGTH_SHORT).show();
//                        Intent intent_pwdchange = new Intent(SetActivity.this, PwdchangeActivity.class);
//                        startActivity(intent_pwdchange);

                        break;
                    case 1://修改註冊郵箱並發送驗證
                        Toast.makeText(getActivity(), "點擊1", Toast.LENGTH_SHORT).show();
//                        Intent intent_changeemail = new Intent(SetActivity.this, ChangeemailActivity.class);
//                        startActivity(intent_changeemail);
                        break;
                    case 2://修改手機號碼
                        Toast.makeText(getActivity(), "點擊2", Toast.LENGTH_SHORT).show();
//                        Intent intent_changephone = new Intent(SetActivity.this, ChangephoneActivity.class);
//                        startActivity(intent_changephone);
                        break;
                    case 3://退出登錄,返回到登錄界面
                        Toast.makeText(getActivity(), "點擊3", Toast.LENGTH_SHORT).show();
//                        UsersInfo.logOut();//退出登錄,同時清除緩存用戶對象。
//                        Intent intent_logout = new Intent(SetActivity.this, LoginActivity.class);
//                        startActivity(intent_logout);
                        break;
                    case 4:
                        Toast.makeText(getActivity(), "點擊4", Toast.LENGTH_SHORT).show();
//                        Intent intent_verifyphone = new Intent(SetActivity.this, VerifyphoneActivity.class);
//                        startActivity(intent_verifyphone);
                        break;
                }
            }
        });
        // Inflate the layout for this fragment
        return view;
    }
}

最後在需要添加fragment的主activity中:

getSupportFragmentManager().beginTransaction().add(R.id.main_body,new SetFragment()).commit();
因為我是想要一個底部導航欄的效果,那我這裏直接用了android studio中寫好的一個底部導航欄,然後稍微改了一點兒:
技術分享圖片

嗯還是貼一下代碼吧,MainActivity:

public class MainActivity extends AppCompatActivity {


    private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
            = new BottomNavigationView.OnNavigationItemSelectedListener() {

        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem item) {
            switch (item.getItemId()) {
                case R.id.navigation_home:
                    //getSupportFragmentManager().beginTransaction().replace(R.id.main_body,new HomeFragment()).commit();

                    return true;
                case R.id.navigation_dashboard:
                    getSupportFragmentManager().beginTransaction().replace(R.id.main_body,new SetFragment()).commit();

                    return true;
                case R.id.navigation_notifications:

                    return true;
            }
            return false;
        }
    };

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

        setMain();


        BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
        navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
    }

    //用於打開初始頁面
    private void setMain() {
        //getSupportFragmentManager() -> beginTransaction() -> add -> (R.id.main_boy, new Fragment()
        this.getSupportFragmentManager().beginTransaction().add(R.id.main_body,new HomeFragment()).commit();
    }

}

下面是activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <LinearLayout
        android:orientation="vertical"
        android:background="@android:color/white"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <!--標題欄-->
        <!--<include layout="@layout/main_title_bar" />-->
        <!--放置Fragment的main_body-->
        <RelativeLayout
            android:id="@+id/main_body"
            android:background="@android:color/white"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center">

        </RelativeLayout>
    </LinearLayout>


    <android.support.design.widget.BottomNavigationView
        android:id="@+id/navigation"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="0dp"
        android:layout_marginEnd="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation" />

</android.support.constraint.ConstraintLayout>

嗯 大致就是這樣啦

 

Android Studio 將Activity改成Fragment