繁体   English   中英

如何通过单击按钮使用工具栏在活动中启动片段

[英]How to start fragment In activity with tool bar by click button

我知道有人问过这个问题,但是我显然没有解决这个问题,我有两个包含相同细节的片段,一个是列表视图,另一个是从数据库中获取网格并包含工具的活动视图。栏此工具栏仅包含一个像这样的图标按钮 在此处输入图片说明

我只需要一个方法,如果我单击网格图标在同一活动中使用相同的工具栏显示网格片段,并且如果单击列表图标,只需将网格片段替换为列表片段即可,每个片段都有一个适配器以及一个getter和setter类,这是包含工具栏的活动

package abtech.waiteriano.com.waitrer;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;

public class MenuActivity extends AppCompatActivity {
    private android.support.v7.widget.Toolbar toolbar;
    private ArrayList<String> category ;

    ImageView listIcon, gridIcon;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu);

        String menugridSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        ResultSet rs = ConnectionClass.Ret_RS(menugridSTR);

        listIcon = (ImageView) findViewById(R.id.listicon);
        gridIcon = (ImageView) findViewById(R.id.gridicon);
        category = new ArrayList<String>() ;
        String str = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        rs = ConnectionClass.Ret_RS(str);
        try {
            while (rs.next()) {
                category.add(rs.getString("Name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        Spinner navigationSpinner = new Spinner(getSupportActionBar().getThemedContext());
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, category);
        navigationSpinner.setAdapter(adapter);
        toolbar.addView(navigationSpinner, 0);

        navigationSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MenuActivity.this,
                        "you selected: " + category.get(position),
                        Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.iconmenu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()){
            case R.id.searchicon:
                // ...
                return true;
            case R.id.listicon:
                setContentView(R.layout.activity_menu_lv);
                return true;
            case R.id.gridicon:
                // ...
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

和这个activity.xml文件

<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="wrap_content"
    android:orientation="vertical"
    tools:context="abtech.waiteriano.com.waitrer.MenuActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize" />
</LinearLayout>

这是网格片段类

package abtech.waiteriano.com.waitrer.fragments;

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.GridView;
import android.widget.ImageView;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.adapters.CustomMenuGridViewAdapter;
import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;
import abtech.waiteriano.com.waitrer.getters_and_setters.MenuItem;

public class MenuGridFragment extends Fragment {

    View rootView;
    GridView menuGridView;
    static ArrayList<MenuItem> menuGridArray = new ArrayList<MenuItem>();
    CustomMenuGridViewAdapter customMenuGridViewAdapter;

    ImageView listIcon, gridIcon;


    public MenuGridFragment() {
        // Required empty public constructor
    }


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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        menuGridView = (GridView) rootView.findViewById(R.id.menuGridView);
        customMenuGridViewAdapter = new CustomMenuGridViewAdapter(getActivity(), R.layout.menu_row_grid, menuGridArray);
        menuGridView.setAdapter(customMenuGridViewAdapter);
        String menugridSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        ResultSet rs = ConnectionClass.Ret_RS(menugridSTR);
        try {
            while (rs.next()) {
                menuGridArray.add(new MenuItem(rs.getString("Name")));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rootView;
    }

}

这是xml文件

<FrameLayout 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"
    tools:context="abtech.waiteriano.com.waitrer.fragments.MenuGridFragment">

    <GridView
        android:id="@+id/menuGridView"
        android:layout_width="match_parent"
        android:background="#d2d2d2"
        android:layout_height="fill_parent"
        android:layout_margin="4dp"
        android:columnWidth="80dp"
        android:gravity="center"
        android:horizontalSpacing="5dp"
        android:numColumns="3"
        android:stretchMode="columnWidth"
        android:layout_below="@+id/toolbar" />

</FrameLayout>

这是列表片段类

package abtech.waiteriano.com.waitrer.fragments;

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.ListView;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import abtech.waiteriano.com.waitrer.R;
import abtech.waiteriano.com.waitrer.adapters.CustomMenuListViewAdapter;
import abtech.waiteriano.com.waitrer.connection_class.ConnectionClass;
import abtech.waiteriano.com.waitrer.getters_and_setters.MenuListItem;

public class MenuLVFragment extends Fragment {

    View rootView;
    ListView menuListView;
    static ArrayList<MenuListItem> listMenuArray = new ArrayList<MenuListItem>();
    CustomMenuListViewAdapter customMenuListViewAdapter;

    public MenuLVFragment() {
        // Required empty public constructor
    }


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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        menuListView = (ListView) rootView.findViewById(R.id.menuLV);
        customMenuListViewAdapter = new CustomMenuListViewAdapter(getActivity(), R.layout.menu_row_list,listMenuArray);
        menuListView.setAdapter(customMenuListViewAdapter);
        String menuListSTR = "Select ID,Code,Name,Name2 From Presets Where Active = 1 And Rest_ID_Active = 1 AND OutLet_ID_Active = 1 ORDER BY Code";
        ResultSet rs = ConnectionClass.Ret_RS(menuListSTR);
        try {
            while (rs.next()){
                listMenuArray.add(new MenuListItem(rs.getString("Name")));

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rootView;
    }
}

这是xml文件

<FrameLayout 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"
    tools:context="abtech.waiteriano.com.waitrer.fragments.MenuLVFragment">

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

</FrameLayout>

顺便说一句,我需要网格片段是默认视图,因为当我开始此活动时,始终将网格片段显示为默认视图,如果有任何不清楚的地方,如果代码太长,如果有任何发现,请发表评论LogCat Error

03-02 13:59:23.352 6741-6741/? E/ERRO: Unknown server host name 'Host is unresolved: null'.
03-02 13:59:23.389 6741-6741/? E/ERRO: Unknown server host name 'Host is unresolved: null'.
03-02 13:59:23.403 6741-6741/? E/ERRO: Unknown server host name 'Host is unresolved: null'.
03-02 13:59:23.508 6741-6766/? E/GED: Failed to get GED Log Buf, err(0)
03-02 13:59:23.526 6741-6766/? E/[PropSet]: connect fail
03-02 13:59:23.526 6741-6766/? E/libc: __system_property_set error : retry fail, errno 13(Permission denied)
03-02 13:59:23.526 6741-6766/? E/[PropSet]: send_prop_msg return err -5
03-02 14:01:34.965 6741-6741/abtech.waiteriano.com.waitrer E/AndroidRuntime: FATAL EXCEPTION: main
                                                                             Process: abtech.waiteriano.com.waitrer, PID: 6741
                                                                             java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
                                                                                 at abtech.waiteriano.com.waitrer.fragments.MenuLVFragment.onCreateView(MenuLVFragment.java:40)
                                                                                 at android.app.Fragment.performCreateView(Fragment.java:2069)
                                                                                 at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:899)
                                                                                 at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1072)
                                                                                 at android.app.BackStackRecord.run(BackStackRecord.java:852)
                                                                                 at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
                                                                                 at android.app.FragmentManagerImpl$1.run(FragmentManager.java:452)
                                                                                 at android.os.Handler.handleCallback(Handler.java:815)
                                                                                 at android.os.Handler.dispatchMessage(Handler.java:104)
                                                                                 at android.os.Looper.loop(Looper.java:214)
                                                                                 at android.app.ActivityThread.main(ActivityThread.java:6102)
                                                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
                                                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)

我总是在项目中使用片段,例如:首先在Activity中,我要作为片段的宿主,然后在布局活动中创建一个容器,例如<FrameLayout...

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

在Activity类中,您应该将片段声明为类下方的字段:

private ProfileFragment profileFragment;
private EditProfileFragment editProfileFragment;

在托管活动的第二部分,我使用延迟加载来实例化一个或多个这样的片段,当然我是在onResume() method上执行此操作的:

    @Override
protected void onResume() {
    super.onResume();
    getProfileFragment();
    getEditProfileFragment();
}

接着 :

    private ProfileFragment getProfileFragment() {
    if (profileFragment == null) {
        profileFragment = new ProfileFragment();

    }
    return profileFragment;
}

private EditProfileFragment getEditProfileFragment() {
    if (editProfileFragment == null) {
        editProfileFragment = new EditProfileFragment();

    }
    return editProfileFragment;
}

例如,如果您想通过单击一个按钮,一个片段是开始交易,则应在按钮操作上编写如下代码:

private void addFragment () {
getSupportFragmentManager().beginTransaction().
replace(R.id.profile_container, getProfileFragment()).commit();

R.id.profile_container是我的托管活动布局中的容器。

如果您希望默认情况下将一个片段放在您的容器上,则可以在onResume()只需调用片段的方法即可:

        @Override
protected void onResume() {
    super.onResume();
    getProfileFragment();
    getEditProfileFragment();
    addFragment ();

}

对不起,如果我的英语不好。

对于toolBar,您可以创建一个菜单,然后在菜单中的Item操作调用您像上面创建的Fragment方法。

首先,如果要在ListView和GridView中显示相同的数据,则不需要为ListView和GridView创建单独的片段,而应该使用RecyclerView,它可以以List格式和Grid格式显示数据。

在这里,您可以查看RecyclerView的文档。

RecyclerView提供了以下内置布局管理器:

  1. LinearLayoutManager在垂直或水平滚动列表中显示项目。
  2. GridLayoutManager在网格中显示项目。
  3. StaggeredGridLayoutManager在交错网格中显示项目。

因此,对于列表视图,您可以设置

 LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
 mRecyclerView.setLayoutManager(mLayoutManager);

和用于网格视图

 GridLayoutManager mLayoutManager = new GridLayoutManager(this,2);
 mRecyclerView.setLayoutManager(mLayoutManager);

其中2是单行中的单元格数。

将此FrameLayout添加到您的activity.xml

<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="wrap_content"
    android:orientation="vertical"
    tools:context="abtech.waiteriano.com.waitrer.MenuActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize" />

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

</LinearLayout>

用MainActivity的OnCreate()中的MenuGridFragment替换此框架。 (正如您所说的,MenuGridFragment是您的默认片段)

FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame, new MenuGridFragment()).commit();

加载片段取决于onMenuItemSelected()中的所选图标:

@Override
    public boolean onOptionsItemSelected(android.view.MenuItem item) {
        switch (item.getItemId()){
            case R.id.searchicon:
                // ...
                return true;
            case R.id.listicon:
                 FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame, new MenuLVFragment()).commit();
                return true;
            case R.id.gridicon:
                // ...
                 FragmentManager fm = getFragmentManager();
        fm.beginTransaction().replace(R.id.content_frame, new MenuGridFragment()).commit();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM