LinearLayout@422725b0 不是滑动抽屉

2024-04-16

嗨,我对此快疯了。

有几个问题,但似乎没有一个能解决我的问题。 当我尝试设置抽屉布局样式时,我收到错误。

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">

<!-- As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions. -->
<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<LinearLayout
    android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent" 
    android:gravity="start"
    >

    <TextView
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:text="test"
        android:background="@drawable/black"
        android:textColor="#94A1A1"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"  
        android:layout_weight="1"      
    />  

    <ListView
        android:id="@+id/left_drawer_child"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#323232"
        android:layout_weight="1"
    />

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

和爪哇

/*
 * Copyright 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.drawertest;

import java.util.Locale;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * This example illustrates a common usage of the DrawerLayout widget
 * in the Android support library.
 * <p/>
 * <p>When a navigation (left) drawer is present, the host activity should detect presses of
 * the action bar's Up affordance as a signal to open and close the navigation drawer. The
 * ActionBarDrawerToggle facilitates this behavior.
 * Items within the drawer should fall into one of two categories:</p>
 * <p/>
 * <ul>
 * <li><strong>View switches</strong>. A view switch follows the same basic policies as
 * list or tab navigation in that a view switch does not create navigation history.
 * This pattern should only be used at the root activity of a task, leaving some form
 * of Up navigation active for activities further down the navigation hierarchy.</li>
 * <li><strong>Selective Up</strong>. The drawer allows the user to choose an alternate
 * parent for Up navigation. This allows a user to jump across an app's navigation
 * hierarchy at will. The application should treat this as it treats Up navigation from
 * a different task, replacing the current task stack using TaskStackBuilder or similar.
 * This is the only form of navigation drawer that should be used outside of the root
 * activity of a task.</li>
 * </ul>
 * <p/>
 * <p>Right side drawers should be used for actions, not navigation. This follows the pattern
 * established by the Action Bar that navigation should be to the left and actions to the right.
 * An action should be an operation performed on the current contents of the window,
 * for example enabling or disabling a data overlay on top of the current content.</p>
 */


public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private LinearLayout linearLayout;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;
    public TextView title;
    public int theme = 1;
    public int theme2 = 1;
    public Drawable background = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(theme == 1){
       setTheme(R.style.CustomActionBarTheme);
        } else {
            setTheme(R.style.CustomActionBarBlueTheme);
        }
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer_child);
        linearLayout = (LinearLayout)findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                getActionBar().setBackgroundDrawable(background);
            }

            public void onDrawerOpened(View drawerView) {
               // getActionBar().setTitle(mDrawerTitle);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()

            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }

    }

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

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(linearLayout);
        menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         // The action bar home/up action should open or close the drawer.
         // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {

            return true;
        }
        // Handle action buttons
        switch(item.getItemId()) {
        case R.id.action_websearch:
            // create intent to perform web search for this planet
            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
            intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
            // catch event that there's no activity to handle intent
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            updatebackground(view,position);
            selectItem(position);
        }
    }
    private void updatebackground(View view,int position) {
        // update the main content by replacing fragments
        int right = view.getPaddingRight();
        int left = view.getPaddingLeft();
        int top = view.getPaddingTop();
        int bottom = view.getPaddingBottom();
        switch(position) {
        case 0 : 
                 view.setBackgroundResource(R.drawable.redbackground);
                 background = getResources().getDrawable(R.drawable.red);

        break;
        case 1 : view.setBackgroundResource(R.drawable.bluebackground);
                 background = getResources().getDrawable(R.drawable.blue);

        break;
        case 2 : view.setBackgroundResource(R.drawable.brownbackground);
                 background = getResources().getDrawable(R.drawable.brown);

        break;
        case 3 : view.setBackgroundResource(R.drawable.greenbackground);
        background = getResources().getDrawable(R.drawable.green);

        break;
        case 4 : view.setBackgroundResource(R.drawable.orangebackground);
        background = getResources().getDrawable(R.drawable.orange);

        break;
        case 5 : view.setBackgroundResource(R.drawable.purplebackground);
        background = getResources().getDrawable(R.drawable.purple);

        break;
        case 6 : view.setBackgroundResource(R.drawable.pinkbackground);
        background = getResources().getDrawable(R.drawable.pink);

        break;
        case 7 : view.setBackgroundResource(R.drawable.yellowbackground);
        background = getResources().getDrawable(R.drawable.yellow);

        break;
        default: view.setBackgroundResource(R.drawable.blackbackground);
        background = getResources().getDrawable(R.drawable.black);


        }
        view.setPadding(left, top, right, bottom);
        getActionBar().setBackgroundDrawable(background);
    }
    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(linearLayout);

    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
        if(theme == 1){
            theme =2;
        }else {
            theme =1;
        }

    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Fragment that appears in the "content_frame", shows a planet
     */
    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);
            String planet = getResources().getStringArray(R.array.planets_array)[i];

            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                            "drawable", getActivity().getPackageName());
            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;
        }
    }
}

我得到的错误是

11-27 00:56:56.545: E/AndroidRuntime(10000): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.drawertest/com.example.drawertest.MainActivity}: java.lang.IllegalArgumentException: View android.widget.LinearLayout@422725b0 is not a sliding drawer

任何帮助将非常感谢提前


视图必须具有 Gravity.LEFT 或 Gravity.RIGHT 才能被识别为滑动抽屉。您可以更换

android:gravity="start"

with

android:gravity="left"

或者,按照上面的建议替换

isDrawerOpen(linearLayout) 

with

isDrawerOpen(Gravity.LEFT)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

LinearLayout@422725b0 不是滑动抽屉 的相关文章

  • 检索子值 -firebase-

    System out println ref child email protected cdn cgi l email protection child email 我正在尝试获取 child 的值 但我始终获取该值的 URL 当我尝试使
  • 按钮未显示在屏幕上

    我创建了一个应用程序 其中显示带有图像和文本的列表视图 我在页面末尾添加按钮 但这没有显示在屏幕上 我是 Android 新手 我该如何解决这个问题 这是我的 UI XML 代码
  • React Native Android 发布 apk 是调试,而不是发布

    我有一个现有的 Android 应用程序 我已根据以下内容将 React Native v0 30 活动添加到项目中docs http facebook github io react native releases next docs i
  • 为什么按钮上的 maxWidth 不起作用以及如何解决它?

    我的布局上有两个按钮 在大屏幕设备 平板电脑 上我想限制它们的宽度 这样它们看起来就不会很荒谬 我希望使用 maxWidth 属性 但它显然在我的场景中没有任何作用 这是布局定义 按钮使用布局的整个宽度 忽略 maxWidth 中的任何值
  • 获取可以共享数据的应用程序列表

    此代码显示默认共享对话框 Intent sharingIntent new Intent Intent ACTION SEND sharingIntent setType text html sharingIntent putExtra a
  • 从多个选项卡中的编辑文本字段获取文本

    我正在尝试创建一个使用选项卡作为输入表单的 Android 应用程序 基本上 我希望对其进行设置 以便用户可以在一个选项卡上输入一些信息 然后提交该信息 或者转到另一个选项卡并输入更多信息 然后从两个选项卡提交信息 我正在使用操作栏和片段来
  • AnalyticsService 未在应用程序清单中注册 - 错误

    我正在尝试使用 sdk 中提供的以下文档向 Android 应用程序实施谷歌分析服务 https developers google com analytics devguides collection android v4 https d
  • 没有调用addToBackStack,片段仍然添加到backstack,为什么?

    我正在制作我的片段更换器助手类 但我遇到了一些问题 我称之为FragmentChanger 它有一个fragmentContainer 这是一个ViewGroup 其中包含我想展示的所有片段 我已经做了我自己的replace Fragmen
  • Google 移动广告和 Kindle Fire

    我最近用 Google 移动广告替换了 AdMob 库 对此我有一个疑问 广告会出现在 Amazon Kindle Fire 设备上吗 我问这个是因为我知道 Google 移动广告依赖于 Google Play 服务 所以我有点困惑 Goo
  • 如何从android获取应用程序安装时间

    我尝试了一些方法 但没有成功 请帮助我 PackageManager pm context getPackageManager ApplicationInfo appInfo pm getApplicationInfo app packag
  • Android GCM 服务器的 API 密钥

    我有点困惑我应该为 GCM 服务器使用哪个 API 密钥 在文档中它说使用 android api 密钥 这对我不起作用并且总是给出未经授权的 http developer android com google gcm gs html ht
  • 在 AppAuth-Android 中注销

    我有一个用JAVA开发的Android应用程序 对于这个应用程序 我使用的是身份服务器4 https github com IdentityServer IdentityServer4作为我的 STS 一切正常 但我找不到任何注销的实现Ap
  • Ionic Facebook Api 无效密钥哈希

    我无法让我的应用程序允许 Facebook 登录 每次用户尝试登录 Facebook 并使用他们的 FB 验证我的应用程序时 都会出现以下错误 无效的密钥哈希 它们的密钥哈希 xxxxxxxxxx 与任何存储的密钥哈希不匹配 配置您的应用程
  • 使用嵌套的 hashmap 参数发送 volley 请求

    我正在使用 android volley 框架向我的服务器发送 jsonobject 请求 get 请求工作正常 现在我想发送一个带有请求参数的 post 请求 该请求参数是嵌套的 hashmap 我重写 getparams 方法 但它期望
  • 在 Android 布局 xml 文件中使用字符串格式参数 [重复]

    这个问题在这里已经有答案了 我在 String xml 文件中定义了一个使用格式参数的字符串 即
  • android:layout_alignParentBottom 在没有显式布局高度作为 ListView 中的行的情况下使用时会被忽略

    当我使用RelativeLayout与任一fill parent or wrap content作为高度和一个指定的元素 android layout alignParentBottom true 它被忽略并在顶部对齐 设置高度Relati
  • 在状态栏下方显示DialogFragment内容

    我试图显示高度和宽度均具有 match parent 的 DialogFragment 但碰巧在顶部 DialogFragment 显示在 StatusBar 下方 DialogFragment 正在应用一些默认值来填充底部 右侧 左侧和顶
  • 通过powershell运行ADB命令

    所以我尝试通过 powershell 脚本运行一些 ADB 命令 这是我正在尝试做的一个简单示例 adb shell echo in adb shell su root echo you are now root ls cd data da
  • 具有矢量可绘制的 ImageView 的 Resources$NotFoundException

    我遇到了崩溃 Resources NotFoundException用于在活动创建时绘制的矢量 21 日前崩溃 安卓工作室2 1 支持库24 0 0 Gradle插件2 1 0 目标SDK 23 最小SDK 15 buildTools版本
  • 异步更新后更新Android Listview

    我正在将 HTTP 调用从同步调用转换为异步调用 由于连接在后台运行 因此当我最初设置列表适配器时 数据不存在 如何在 HTTP 调用后更新列表适配器 我尝试了一些方法 例如在数据发送回之前不设置适配器并再次设置适配器 但没有任何效果 这是

随机推荐