2012-02-24 50 views
1

我的應用程序包含許多對話窗口。它已經到了源頭似乎壓倒一切的地步。我正在尋找有關分離Dialog源的最佳方法的意見。我對Java比較陌生,所以我假設我可以將它們放在一個單獨的類中。但是,在Android中完成此操作的確切方式暗示我。願有人指出我正確的方向?如何在應用程序中組織Android對話框源代碼?

+1

我認爲,如果你指定你的問題有點多,這將有助於。您的應用中有多少項活動?對話是每個特定於一個活動,還是有一個可能從不同的活動打開的對話框? – Cephron 2012-02-24 03:55:47

+0

所有對話框窗口都屬於一個活動,並且它們不能在其外部訪問。我只是尋找一種聰明的方式來以便捷的方式封裝所有的對話框窗口。任何幫助將是偉大的,謝謝! – mas 2012-02-24 05:18:34

回答

1

您可以通過擴展對話創建對話如下 1.爲customDialog創建Layout.xml 創建一個包含視圖的新佈局。在這個例子中,我使用了edittext和button。

<?xml version="1.0" encoding="utf-8"?> 

<EditText android:id="@+id/EditText01" android:layout_height="wrap_content" android:text="Enter your name" android:layout_width="250dip"></EditText> 

<Button android:id="@+id/Button01" android:layout_width="wrap_content" 
    android:layout_height="wrap_content" android:text="click"></Button> 

  1. 創建自定義對話框類。 a。 b。創建一個類擴展對話框類 b。創建一個事件處理程序接口作爲成員 c。在onCreate方法中使用自定義佈局。

    public class MyCustomDialog extends Dialog { 
    
    public interface ReadyListener { 
        public void ready(String name); 
    } 
    
    private String name; 
    private ReadyListener readyListener; 
    EditText etName; 
    
    public MyCustomDialog(Context context, String name, 
         ReadyListener readyListener) { 
        super(context); 
        this.name = name; 
        this.readyListener = readyListener; 
    } 
    
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.mycustomdialog); 
        setTitle("Enter your Name "); 
        Button buttonOK = (Button) findViewById(R.id.Button01); 
        buttonOK.setOnClickListener(new OKListener()); 
        etName = (EditText) findViewById(R.id.EditText01); 
    } 
    
    private class OKListener implements android.view.View.OnClickListener { 
        @Override 
        public void onClick(View v) { 
         readyListener.ready(String.valueOf(etName.getText())); 
         MyCustomDialog.this.dismiss(); 
        } 
    } 
    

    }

  2. 創建MainActivity貫徹CustomDialog

    公共類MainActivity延伸活動{ /**調用在首次創建時的活性。 */ @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); MyCustomDialog myDialog = new MyCustomDialog(this,「」, new OnReadyListener()); myDialog.show(); } 私有類OnReadyListener實現MyCustomDialog.ReadyListener { @覆蓋 公共無效就緒(字符串名稱){ Toast.makeText(MainActivity.this,名稱,Toast.LENGTH_LONG).show(); }} }

相關問題