簡體   English   中英

如何按需擴展 android 中的對話(例如單擊按鈕)

[英]How to expand a dialogue in android on demand (e.g. a button click)

我是 android 和 kotlin 的新手,正在開發我的第一個應用程序,這將是一個庫應用程序。 在應用程序中,我希望與適合一個屏幕的一些基本視圖(例如創建數據庫條目)進行對話,但我希望對話可以按需擴展,例如單擊按鈕,因為應該存儲其他數據。

我需要的與我的 android 智能手機的內置對話框“添加新聯系人”非常相似。 首先,對話框不可滾動並在一個屏幕上顯示最重要的字段,但通過按下“添加更多字段”按鈕,對話框變為可滾動(縱向兩個屏幕的高度)並顯示其他字段以保存聯系人數據。

我希望我能夠描述我在尋找什么。

我的第一個想法是使用一個片段(簡單約束布局),當用戶按下“添加更多字段”按鈕並從第一個片段中檢索已經輸入的信息時,它將被一個不同的片段(ScrollView)替換,但我想知道這是否是最佳實踐。

你能給我一些關於這個對話是如何編程是現實的基本建議嗎?

非常感謝!

創建一個擴展對話框 class 的 class。

class AddToPlaylist(
context: Context
) : Dialog(context) {
private var playlists: List<PlaylistEntity>? = null

fun setDialogPlaylists(_playlists: List<PlaylistEntity>) {
    playlists = _playlists
}


var recyclerView: RecyclerView? = null
var adapter: PlaylistDialogAdapter? = null

var selectedPlaylistId = -1


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.add_to_playlist_dialog)


    recyclerView = findViewById(R.id.recyclerViewPlaylists)

    adapter = PlaylistDialogAdapter(context)
    recyclerView?.adapter = adapter
    recyclerView?.layoutManager = LinearLayoutManager(context)

    adapter?.playlistClickCallback = fun(id: Int) {
        selectedPlaylistId = id
        dismiss()
    }

    adapter?.setPlayLists(playlists!!)
}

在此對話框中,我正在使用回收站視圖,因為我將顯示播放列表列表。 接下來,我的對話框有一個 xml 文件。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="12dp"
android:background="@color/backgroundColor"
android:orientation="vertical">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/choose_playlist"
    android:textColor="@color/textPrimary"
    android:textSize="@dimen/small_text" />


<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recyclerViewPlaylists"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:scrollbarStyle="outsideOverlay"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    tools:listitem="@layout/single_playlist_item" />

xml

現在我的對話框 class 已准備就緒,我只需要創建一個需要使用它的實例並調用 show 方法。

addToPlaylistDialog = AddToPlaylist(activity as Context)
addToPlaylistDialog.show()

還可以在對話框關閉后使用解除偵聽器來編寫您想要的代碼。

addToPlaylistDialog.setOnDismissListener {
        val playlistId: Int = addToPlaylistDialog.selectedPlaylistId
        Log.i("PLAYLISTSONGS", "Dismiss Listener called with playlistId=$playlistId")
    }

這應該足以滿足您的需要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM