要实现在Android底部显示按钮,并使其始终保持在屏幕底部,可以使用BottomSheetBehavior
来实现。
首先,在布局文件中,将按钮放置在一个CoordinatorLayout
中,并将app:layout_behavior
属性设置为@string/bottom_sheet_behavior
,如下所示:
接下来,在代码中,你需要初始化并设置BottomSheetBehavior
,以确保按钮始终显示在屏幕底部。具体代码如下:
import com.google.android.material.bottomsheet.BottomSheetBehavior;
public class MainActivity extends AppCompatActivity {
private BottomSheetBehavior bottomSheetBehavior;
private Button bottomButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bottomButton = findViewById(R.id.bottomButton);
bottomSheetBehavior = BottomSheetBehavior.from(bottomButton);
bottomSheetBehavior.setPeekHeight(bottomButton.getHeight());
bottomSheetBehavior.setHideable(false);
bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
}
}
以上代码中,通过BottomSheetBehavior.from()
方法从按钮获取BottomSheetBehavior
实例。然后,使用setPeekHeight()
方法设置按钮的最小高度,确保它始终可见。setHideable(false)
方法禁用了隐藏按钮的功能。最后,使用setState()
方法将按钮的初始状态设置为BottomSheetBehavior.STATE_COLLAPSED
,以便它始终保持显示状态。
这样,按钮就会始终显示在屏幕底部,并且无法被隐藏。