接通AppCompatActivity不显示 [英] Switch on AppCompatActivity not showing

查看:201
本文介绍了接通AppCompatActivity不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想添加一个切换部件在我的动作条但是当我尝试实现它没有关系'T显示或如果这样做,我的 ActionBart 标题自败。
我所做的是:

I'm trying to add a Switch widget on my ActionBar but when I try to implement it it doesn't show or if it does, my ActionBart title dissapears. What I've done is :

我创建了一个布局切换

?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >
    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switchAB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        />
</RelativeLayout>

然后在我的 menu_main.xml 我添加了这一点:

<item
    android:id="@+id/switchId"
    android:title=""
    app:showAsAction="ifRoom"
    android:actionLayout="@layout/swipe_wifi"
    />

我已经改变了机器人应用因为帮助是这样说的。

I've changed android to app because on help says so

然后在我的ActivityMain onCreateOptionsMenu()如果添加了此做一个快速的测试

Then on my ActivityMain onCreateOptionsMenu() if added this to make a fast test

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);

    switchAB = (Switch)menu.findItem(R.id.switchId)
            .getActionView().findViewById(R.id.switchAB);

    switchAB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                                     boolean isChecked) {
            if (isChecked) {
                Toast.makeText(getApplication(), "ON", Toast.LENGTH_SHORT)
                        .show();
            } else {
                Toast.makeText(getApplication(), "OFF", Toast.LENGTH_SHORT)
                        .show();
            }
        }
    });
    return true;
}

但它给我一个 NPE 在这个车道

 switchAB = (Switch)menu.findItem(R.id.switchId)
        //NPE-->    .getActionView().findViewById(R.id.switchAB);

我应该改变的东西在我的code?

Shall I change something on my code?

推荐答案

尝试使用应用:actionLayout 太:

<item
    android:id="@+id/switchId"
    android:title=""
    app:showAsAction="ifRoom"
    app:actionLayout="@layout/swipe_wifi"
    />

应该也注意到,你在铸造视图 android.widget.Switch ,而在你的布局,你有一个 android.support .v7.widget.SwitchCompat (这是一个不错的选择,因为切换在API14加入)。

It should be noted also that you are casting the view to android.widget.Switch, while in your layout you have a android.support.v7.widget.SwitchCompat (and that is a good choice, since Switch was added in API14).

这篇关于接通AppCompatActivity不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆