如何修复Android中的“无重力左找不到抽屉视图”

时间:2019-04-04 22:39:58

标签: java android navigation-drawer expandablelistview

  

我必须使用expandablelist创建导航抽屉。我有一个   错误。

     

错误:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.tene.trainingapp, PID: 28183
    java.lang.IllegalArgumentException: No drawer view found with gravity LEFT
        at android.support.v4.widget.DrawerLayout.openDrawer(DrawerLayout.java:1736)
        at android.support.v4.widget.DrawerLayout.openDrawer(DrawerLayout.java:1722)
        at android.support.v7.app.ActionBarDrawerToggle.toggle(ActionBarDrawerToggle.java:287)
        at android.support.v7.app.ActionBarDrawerToggle.onOptionsItemSelected(ActionBarDrawerToggle.java:275)
        at com.tene.trainingapp.MainActivity.onOptionsItemSelected(MainActivity.java:182)
        at android.app.Activity.onMenuItemSelected(Activity.java:3543)
        at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:436)
        at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:196)
        at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
        at android.support.v7.widget.ToolbarWidgetWrapper$1.onClick(ToolbarWidgetWrapper.java:188)
        at android.view.View.performClick(View.java:6608)
        at android.view.View.performClickInternal(View.java:6585)
        at android.view.View.access$3100(View.java:782)
        at android.view.View$PerformClick.run(View.java:25945)
        at android.os.Handler.handleCallback(Handler.java:874)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:198)
        at android.app.ActivityThread.main(ActivityThread.java:6729)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

MainActivity.java

import android.content.res.Configuration;
import android.support.annotation.Nullable;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListAdapter;
import android.widget.ExpandableListView;

import com.tene.trainingapp.Adapter.CustomExpandableListAdapater;
import com.tene.trainingapp.Helper.FragmentNavigationManager;
import com.tene.trainingapp.Interface.NavigationManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;
    private String mActivityTitle;
    private String[] items;

    private ExpandableListView expandableListView;
    private ExpandableListAdapter adapter;
    private List<String> lstTitle;
    private Map<String, List<String>> lstChild;
    private NavigationManager navigationManager;

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

        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        mActivityTitle = getTitle().toString();
        expandableListView = (ExpandableListView)findViewById(R.id.navList);
        navigationManager = FragmentNavigationManager.getmInstance(this);

        initItems();

        View listHeaderView = getLayoutInflater().inflate(R.layout.nav_header, null, false);
        expandableListView.addHeaderView(listHeaderView);

        genData();

        addDrawersItem();
        setUpDrawer();

        if (savedInstanceState == null){
            selectFirstitemAsDefault();


            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setHomeButtonEnabled(true);
            getSupportActionBar().setTitle("abhishek");
        }

    }

    @Override
    protected void onPostCreate(@Nullable Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    private void selectFirstitemAsDefault() {
        if (navigationManager != null){
            String firstItem = lstTitle.get(0);
            navigationManager.showFragment(firstItem);
            getSupportActionBar().setTitle(firstItem);
        }
    }

    private void setUpDrawer() {
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close)
        {
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                //getSupportActionBar().setTitle("Abhishek");
                invalidateOptionsMenu();
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                // getSupportActionBar().setTitle(mActivityTitle);
                invalidateOptionsMenu();
            }
        };

        mDrawerToggle.setDrawerIndicatorEnabled(true);
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    private void addDrawersItem() {
        adapter = new CustomExpandableListAdapater(this, lstTitle,lstChild);
        expandableListView.setAdapter(adapter);

        expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
            @Override
            public void onGroupExpand(int groupPosition) {
                getSupportActionBar().setTitle(lstTitle.get(groupPosition).toString());

            }
        });

        expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
            @Override
            public void onGroupCollapse(int groupPosition) {
                getSupportActionBar().setTitle("abhishek");
            }
        });

        expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {

                String selectedItem = ((List)(lstChild.get(lstTitle.get(groupPosition)))).get(childPosition).toString();

                getSupportActionBar().setTitle(selectedItem);

                if (items[0].equals(lstTitle.get(groupPosition)))
                    navigationManager.showFragment(selectedItem);
                else
                    throw new IllegalArgumentException("Not Supported Fragment");

                mDrawerLayout.closeDrawer(GravityCompat.START);

                return false;
            }
        });
    }

    private void genData() {
        List<String> title = Arrays.asList("Android Programming", "Xamrin Programming", "ios Programming");
        List<String> childItem = Arrays.asList("Biginner", "Intermediate", "Advanced", "Professional");

        lstChild = new TreeMap<>();
        lstChild.put(title.get(0), childItem);
        lstChild.put(title.get(1), childItem);
        lstChild.put(title.get(2), childItem);

        lstTitle = new ArrayList<>(lstChild.keySet());

    }

    private void initItems() {
        items= new  String[]{"Android Programming", "Xamrin Programming", "ios Programming"};

    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (mDrawerToggle.onOptionsItemSelected(item))
            return true;

        return super.onOptionsItemSelected(item);
    }
}

NavigationManager界面

public interface NavigationManager {

    void showFragment(String title);
}

FragmentNavigationManager.java

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import com.tene.trainingapp.BuildConfig;
import com.tene.trainingapp.Fragment.FragmentContent;
import com.tene.trainingapp.Interface.NavigationManager;
import com.tene.trainingapp.MainActivity;
import com.tene.trainingapp.R;

public class FragmentNavigationManager implements NavigationManager {

    public static FragmentNavigationManager mInstance;

    private FragmentManager mfragmentManager;
    private MainActivity mainActivity;

    public static FragmentNavigationManager getmInstance(MainActivity mainActivity){
        if (mInstance == null)
            mInstance = new FragmentNavigationManager();
        mInstance.configure(mainActivity);
        return mInstance;
    }

    private void configure(MainActivity mainActivity) {
        mainActivity = mainActivity;
        mfragmentManager =mainActivity.getSupportFragmentManager();
    }

    @Override
    public void showFragment(String title) {
        showFragment(FragmentContent.newInstance(title),false);
    }

    private void showFragment(FragmentContent fragmentContent, boolean b) {
        FragmentManager fragmentManager = mfragmentManager;
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.container, fragmentContent);

        fragmentTransaction.addToBackStack(null);

        if (b || !BuildConfig.DEBUG)
            fragmentTransaction.commitAllowingStateLoss();
        else
            fragmentTransaction.commit();

        fragmentManager.executePendingTransactions();
    }
}
  

FragmentContent.java:它阻止导航的片段内容   抽屉。

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.tene.trainingapp.R;


public class FragmentContent extends Fragment {

    private static final String KEY_TITLE = "Content";

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

    public static FragmentContent newInstance(String param1) {
        FragmentContent fragment = new FragmentContent();
        Bundle args = new Bundle();
        args.putString(KEY_TITLE, param1);
        fragment.setArguments(args);
        return fragment;
    }

    @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
        return inflater.inflate(R.layout.fragment_fragment_content, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        String title = getArguments().getString(KEY_TITLE);
        ((TextView)view.findViewById(R.id.title)).setText(title);
    }
}
  

CustomExpandableList.java:它描述了扩展列表

import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;

import com.tene.trainingapp.R;

import java.util.List;
import java.util.Map;

public class CustomExpandableListAdapater extends BaseExpandableListAdapter {

    private Context context;
    private List<String> listTitle;
    private Map<String, List<String>> listItem;

    public CustomExpandableListAdapater(Context context, List<String> listTitle, Map<String, List<String>> listItem) {
        this.context = context;
        this.listTitle = listTitle;
        this.listItem = listItem;
    }

    @Override
    public int getGroupCount() {
        return listTitle.size();
    }

    @Override
    public int getChildrenCount(int groupPosition) {
        return listItem.size();
    }

    @Override
    public Object getGroup(int groupPosition) {
        return listTitle.get(groupPosition);
    }

    @Override
    public Object getChild(int groupPosition, int childPosition) {
        return listItem.get(listTitle.get(groupPosition)).get(childPosition);
    }

    @Override
    public long getGroupId(int groupPosition) {
        return groupPosition;
    }

    @Override
    public long getChildId(int groupPosition, int childPosition) {
        return childPosition;
    }

    @Override
    public boolean hasStableIds() {
        return false;
    }

    @Override
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
        String title = (String)getGroup(groupPosition);

        if (convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.list_group, null);

        }
        TextView txtTitle = convertView.findViewById(R.id.listTitle);
        txtTitle.setTypeface(null, Typeface.BOLD);
        txtTitle.setText(title);
        return convertView;
    }

    @Override
    public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {

        String title = (String)getChild(groupPosition, childPosition);

        if (convertView == null){
            convertView = LayoutInflater.from(context).inflate(R.layout.list_item, null);

        }
        TextView txtChild = convertView.findViewById(R.id.expandableListItem);
        txtChild.setText(title);
        return convertView;
    }

    @Override
    public boolean isChildSelectable(int groupPosition, int childPosition) {
        return true;
    }
}
  

activity_main.xml:这是主要活动

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/drawer_layout"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/activity_controller"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

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

        </FrameLayout>

        <ExpandableListView
            android:id="@+id/navList"
            android:layout_width="235dp"
            android:layout_height="match_parent"
            android:layout_gravity="left|start"
            android:background="@android:color/white"
            android:divider="@color/dividerColor"
            android:dividerHeight="0.5dp"
            android:indicatorLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
            >

        </ExpandableListView>

    </LinearLayout>
</android.support.v4.widget.DrawerLayout>
  

list_group.xml:保留组列表

<?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="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/listTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:paddingLeft="?android:attr/expandableListPreferredItemIndicatorLeft"
        android:textColor="@color/list_group_title" />

</LinearLayout>
  

list_item.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="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/expandableListItem"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:paddingTop="10dp"
        android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
        android:paddingRight="?android:attr/expandableListPreferredItemPaddingLeft"
        android:textColor="@color/list_item_title"
        />

</LinearLayout>
  

nav_header.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="wrap_content"
    android:orientation="vertical"
    android:background="@drawable/main_header_selector">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:weightSum="1"
        android:layout_margin="10dp">

        <ImageView
            android:id="@+id/avatar"
            android:layout_width="70dp"
            android:layout_height="70dp"
            android:src="@drawable/ic_account_circle_white_24dp"
            />

        <TextView
            android:id="@+id/balance"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:gravity="right|end"
            android:paddingTop="10dp"
            android:text="Balance : 1000"
            android:textColor="@android:color/white"
            android:textSize="16sp"
            />

    </LinearLayout>

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="left|start"
        android:paddingLeft="10dp"
        android:layout_marginBottom="10dp"
        android:text="Abhishek Singh"
        android:textColor="@android:color/white"
        android:textSize="20sp"
        />

</LinearLayout>

0 个答案:

没有答案