如何通过单击按钮启动片段在带有工具栏的活动中

时间:2017-03-02 08:39:23

标签: java android

我知道这个问题已被提出,但我没有解决这个案例显然我有两个片段包含相同的细节,一个作为列表视图,其他视图作为网格从数据库获得并具有一个活动包含工具栏此工具栏只包含一个图标按钮,如enter image description here

所有我只需要一个方法,如果我单击网格图标显示同一活动中的网格片段与相同的工具栏,如果我单击列表图标只需用每个片段的方式替换网格片段与列表片段有一个适配器和一个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错误

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)

3 个答案:

答案 0 :(得分:1)

将此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);
    }

希望这有帮助。

答案 1 :(得分:0)

我总是在我的项目中使用片段,如下所示: 首先在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方法。

答案 2 :(得分:0)

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

Here您可以看到RecyclerView的文档。

RecyclerView提供这些内置布局管理器:

  1. LinearLayoutManager在垂直或水平滚动列表中显示项目。
  2. GridLayoutManager显示网格中的项目。
  3. StaggeredGridLayoutManager以交错网格显示项目。
  4. 因此,对于列表视图,您可以设置

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

    和网格视图

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

    其中2是单行单元格数。