如何在解除方法后保存BottomDialogSheetFragment的状态

问题描述 投票:0回答:1

在BottomSheetDialogFragment中,我在导航视图中有一个可扩展的列表视图。点击任何组项目后,我希望更改所选的位置背景。我实现了一个方法来处理点击并更改适配器内的drawable后,它工作正常。但是,在选择列表项后,它会更改主活动中的片段,然后调用dismiss方法,这会导致抽屉失去与所选位置相关的状态。再次打开抽屉后,它将背景设置为第0个索引。

以下是我的BottomSheet对话框的代码:

class BottomNavigationDrawerFragment : BottomSheetDialogFragment() {

private lateinit var rootView : View
private lateinit var callback: Callback


internal var expandableListView: ExpandableListView? = null
internal var adapter: ExpandableAdapter? = null
internal var titleList: List<String> ? = null

val data: LinkedHashMap<String, List<String>?>
    get() {
        val listData = LinkedHashMap<String, List<String>?>()

        val list = ArrayList<String>()
        list.add("aaaaaaaa")
        list.add("bbbbb")
        list.add("ccccccccccc")

        listData.put("Home",null)
        listData.put("Search",list)
        listData.put("Contact Us",null)

        return listData
    }



fun fragment(cid : Int) {
    var cat_frag = SubFragment()
    val manager = activity!!.supportFragmentManager
    val transaction = manager.beginTransaction()
    transaction.replace(R.id.frame_lay, cat_frag)
    transaction.addToBackStack(null)
    transaction.commit()
    return
}


fun register(list:ExpandableAdapter?,position: Int){
    list?.onClickCallBack(position)
}


}
interface Callback{
    fun onClickCallBack(position :  Int)
}
override fun getTheme(): Int = R.style.BottomSheetDialogTheme

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = BottomSheetDialog(requireContext(), theme)

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {

    rootView = inflater.inflate(R.layout.fragment_bottomsheet, container, false)



    expandableListView = rootView.findViewById(R.id.expandableListView)
    if (expandableListView != null) {
        val listData = data
        titleList = ArrayList(listData.keys)
        adapter = ExpandableAdapter(activity!!, titleList as ArrayList<String>, listData)
        expandableListView!!.setAdapter(adapter)
        expandableListView!!.setOnGroupExpandListener { groupPosition ->
            this.register(adapter,groupPosition)
            when(groupPosition){
                0 -> {

                    val textFragment = fragment1()
                    val manager = activity!!.supportFragmentManager
                    val transaction = manager.beginTransaction()
                    transaction.replace(R.id.frame_lay, textFragment)
                    transaction.addToBackStack(null)
                    transaction.commit()
                    [email protected]()



                }
                2 ->{

                }
            }


            //Toast.makeText(activity!!, (titleList as ArrayList<String>)[groupPosition] + " List Expanded.", Toast.LENGTH_SHORT).show()
        }

        expandableListView!!.setOnGroupCollapseListener { groupPosition ->
            when(groupPosition){
                0 -> {
                    val textFragment = fragment1()
                    val manager = activity!!.supportFragmentManager
                    val transaction = manager.beginTransaction()
                    transaction.replace(R.id.frame_lay, textFragment)
                    transaction.addToBackStack(null
                    transaction.commit()
                    [email protected]()

                }
                2 ->{

                }
            }
        }

        expandableListView!!.setOnChildClickListener { parent, v, groupPosition, childPosition, id ->
           // Toast.makeText(activity!!, "Clicked: " + (titleList as ArrayList<String>)[groupPosition] + " -> " + listData[(titleList as ArrayList<String>)[groupPosition]]!!.get(childPosition), Toast.LENGTH_SHORT).show()

            when(childPosition){
                0 ->{
                    this.register(adapter,2)
                    fragment(1)
                    [email protected]()
                }
                1 ->{
                    this.register(adapter,2)
                    fragment(2)
                    [email protected]()
                }
                2 ->{
                    fragment(3)
                    [email protected]()
                }


            }
            false
        }
    }



    return rootView
}



/*
override fun getTheme(): Int = R.style.BottomSheetDialogTheme

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = BottomSheetDialog(requireContext(), theme)  */

override fun onActivityCreated(savedInstanceState: Bundle?) {
    super.onActivityCreated(savedInstanceState)


}

以下是我的可扩展列表视图适配器:

class ExpandableAdapter internal constructor(private val context: 
Context, private val titleList: List<String>, private val dataList: 
LinkedHashMap<String, List<String>?>) : 
BaseExpandableListAdapter(),BottomNavigationDrawerFragment.Callback {

var selected_position = 0

override fun getChild(listPosition: Int, expandedListPosition: Int): Any {
   return this.dataList[this.titleList[listPosition]]!![expandedListPosition]
   //return this.dataList.get(this.titleList.get(listPosition))!!.get(expandedListPosition)
}

override fun getChildId(listPosition: Int, expandedListPosition: Int): Long {
    return expandedListPosition.toLong()
}

override fun getChildView(listPosition: Int, expandedListPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup): View {
    var convertView = convertView
    val expandedListText = getChild(listPosition, expandedListPosition) as String
    if (convertView == null) {
        val layoutInflater = this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        convertView = layoutInflater.inflate(R.layout.child_view, null)
    }
    val image = convertView!!.findViewById<ImageView>(R.id.image)
    val text = convertView!!.findViewById<TextView>(R.id.item_text)

    if(listPosition == 1){
        text.setText(expandedListText)
    }
    image.setImageResource(R.drawable.fresh)

    return convertView
}

override fun getChildrenCount(listPosition: Int): Int {
    //Log.d("nnnnnnnnnnnnnnnnnnnnn",this.dataList[this.titleList[listPosition]]!!.size.toString())
    if(listPosition == 1){
        return this.dataList[this.titleList[listPosition]]!!.size
    }
    else{
        return 0
    }

}

override fun getGroup(listPosition: Int): Any {
    return this.titleList[listPosition]
}

override fun onClickCallBack(position: Int) {
    this.selected_position =position
}
override fun getGroupCount(): Int {
    return this.titleList.size
}

override fun getGroupId(listPosition: Int): Long {
    return listPosition.toLong()
}


override fun getGroupView(listPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup): View {
    var convertView = convertView
    val listTitle = getGroup(listPosition) as String
    if (convertView == null) {
        val layoutInflater = this.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        convertView = layoutInflater.inflate(R.layout.parent_view, null)
    }
    val listTitleTextView = convertView!!.findViewById<TextView>(R.id.item_text)
    val image_left = convertView!!.findViewById<ImageView>(R.id.image_left)
    val image_right = convertView!!.findViewById<ImageView>(R.id.image_right)
    listTitleTextView.setTypeface(null, Typeface.BOLD)
    listTitleTextView.setText(listTitle)

    val layout = convertView!!.findViewById<RelativeLayout>(R.id.main_layout)
    if(listPosition == selected_position){
        layout.setBackgroundColor(context.resources.getColor(R.color.colorPrimaryDark))
    }
    else{
        layout.setBackgroundColor(context.resources.getColor(R.color.white))
    }


    return convertView
}

override fun hasStableIds(): Boolean {
    return false
}

override fun isChildSelectable(listPosition: Int, expandedListPosition: Int): Boolean {
    return true
}

}

感谢您的帮助!

android
1个回答
0
投票

要保留底部工作表对话框片段状态,您可以按照以下方式进行操作,我创建了一个简单的示例供任何人理解:

首先创建一个名为的xml文件

fragment_bottomsheet

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_margin="20dp"
        android:background="@android:color/holo_red_dark"
        android:orientation="vertical">

        <TextView
            android:id="@+id/tv_old_value"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textColor="@android:color/white"
            android:background="@android:color/holo_green_dark"
            android:layout_margin="10dp"
            android:layout_alignParentBottom="true"
            android:paddingBottom="10dp"
            android:paddingTop="10dp"
            android:text="0" />

    </RelativeLayout>

</RelativeLayout>

然后创建名为的BottomSheetDialogFragment

BottomSheetFragment

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.BottomSheetDialogFragment;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

public class BottomSheetFragment extends BottomSheetDialogFragment {

    BottomSheetDialog dialog;
    Integer myOldValue = 0;
    TextView tvOldValue;

    public static BottomSheetFragment newInstance() {
        BottomSheetFragment fragment = new BottomSheetFragment();
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void setupDialog(Dialog dialog, int style) {
        View contentView = View.inflate(getContext(), R.layout.fragment_bottomsheet, null);
        dialog.setContentView(contentView);
        tvOldValue = contentView.findViewById(R.id.tv_old_value);
        tvOldValue.setText(String.valueOf(myOldValue));
        ((View) contentView.getParent()).setBackgroundColor(getResources().getColor(android.R.color.transparent));
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                BottomSheetDialog d = (BottomSheetDialog) dialog;
                FrameLayout bottomSheet = (FrameLayout) d.findViewById(android.support.design.R.id.design_bottom_sheet);
                tvOldValue.setText(String.valueOf(myOldValue));
            }
        });
        return dialog;
    }

    @Override
    public BottomSheetDialog getDialog() {
        return dialog;
    }

    public void setDialog(BottomSheetDialog dialog) {
        this.dialog = dialog;
    }

    public Integer getMyOldValue() {
        return myOldValue;
    }

    public void setMyOldValue(Integer myOldValue) {
        this.myOldValue = myOldValue;
    }
}

然后创建MainActivity并将该bottomsheetdialogfragment对象作为全局对象,不要销毁它们,但尝试隐藏并显示如下对话框:

我的知识

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    Button btnShow;
    BottomSheetFragment bottomSheetDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnShow = findViewById(R.id.btnShow);
        bottomSheetDialog = BottomSheetFragment.newInstance();
        bottomSheetDialog.show(getSupportFragmentManager(), "Bottom Sheet Dialog Fragment");

        btnShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                bottomSheetDialog.setMyOldValue(bottomSheetDialog.getMyOldValue() + 1);
                bottomSheetDialog.getDialog().show();     
            }
        });
    }
}

观看此示例后,您可以看到BottomSheetFragment中有myOldValue,每当对话框出现在具有更新值的屏幕中时,都会打印。所以这样我们就可以保留底片的状态而不会破坏它。希望它能帮到大家!

© www.soinside.com 2019 - 2024. All rights reserved.