2016-04-26 19 views
0

所以我想在我的Activity中創建一個小的彈出選項菜單。我已經有了這個代碼,顯示菜單使開關按鈕(它位於AlertDialog中)在狀態更改時執行某些操作

public void ShowOptionsDialog() 
    { 
     Android.Support.V7.App.AlertDialog.Builder optionDialog = new Android.Support.V7.App.AlertDialog.Builder(this); 
     optionDialog.SetTitle("Optionen");    
     optionDialog.SetView(Resource.Layout.Options); 
     optionDialog.Show();    
    } 

Resource.Layout.Options包含以下內容:

<?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:gravity="center"> 
    <android.support.v7.widget.SwitchCompat 
     android:id="@+id/previewSwitch" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:checked="true" 
     android:hint="Preview der Dokumente anzeigen"/> 
</LinearLayout> 

究竟是如何做的,我告訴應用程序做一些事情時按下開關時(開關)?

回答

2

您可以設置在SwitchCompat和行爲上的任何變化的事件處理程序,在用戶進行:

注:V7開關不包含Android.Resource.Id.Custom,因此將返回null從FindViewById,所以在這裏我們創造我們自己的FrameLayout

protected void ShowOptionsDialog() 
{ 
    Android.Support.V7.App.AlertDialog.Builder optionDialog = new Android.Support.V7.App.AlertDialog.Builder(this); 
    optionDialog.SetTitle("Optionen"); 
    // Android.Resource.Id.Custom does not exist within v7 alertdialog 
    var frameLayout = new FrameLayout (optionDialog.Context); 
    optionDialog.SetView(frameLayout); 
    Android.Support.V7.App.AlertDialog alert = optionDialog.Create(); 
    var myView = alert.LayoutInflater.Inflate (Resource.Layout.Options, frameLayout); 
    var mySwitch = myView.FindViewById<Android.Support.V7.Widget.SwitchCompat> (Resource.Id.previewSwitch); 
    mySwitch.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { 
     System.Diagnostics.Debug.WriteLine(e.IsChecked); 
    }; 
    alert.Show(); 
} 

enter image description here

注: Android的文檔狀態做FOLL由於向交換機添加自定義視圖,問題出在SwitchCompat,該視圖不存在。

FrameLayout fl = (FrameLayout) findViewById(android.R.id.custom); 
fl.addView(myView, new LayoutParams(MATCH_PARENT, WRAP_CONTENT)); 

http://developer.android.com/reference/android/app/AlertDialog.html

+0

您快速。 ;-) –

+0

已經嘗試過類似你的建議是什麼,當我用你的代碼中,我得到了同樣的錯誤了一句:「System.NullReferenceException:對象不設置到對象的實例」 但我不明白爲什麼。 .. – fbueckle

+0

我現在得到這個錯誤: Java.Lang.NullPointerException:試圖調用空對象引用的接口方法'int java.lang.CharSequence.length()' :/ – fbueckle

-1

你需要讓你的交換機參考。一個簡單的方法就是在代碼中創建交換視圖。這會將您的代碼更改爲類似的內容:

public void ShowOptionsDialog() 
{ 
    var switchView = new Android.Support.V7.Widget.SwitchCompat(this); 
    switchView.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { //Do stuff depending on state }; 

    Android.Support.V7.App.AlertDialog.Builder optionDialog = new Android.Support.V7.App.AlertDialog.Builder(this); 
    optionDialog.SetTitle("Optionen");    
    optionDialog.SetView(switchCompat); 
    optionDialog.Show();    
} 
相關問題