java操作按钮安卓
我有一个floatActionButton,希望在各个活动中重用它,所以我不需要在每个活动上调用onclick方法
目前我有这样的想法:
助手
public class FloatButtonToolbar extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.d("ENTERED","GOTIT");
Intent i = new Intent(FloatButtonToolbar.this,CameraCapture.class);
startActivity(i);
}
});
}
}
主xml(我想重用的那一个)
<?xml version="1.0" encoding="utf-8"?>
<安卓.support.design.widget.CoordinatorLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
tools:context="com.example.afcosta.inesctec.pt.安卓.Helpers.FloatButtonToolbar">
<安卓.support.design.widget.AppBarLayout
安卓:layout_width="match_parent"
安卓:layout_height="wrap_content"
安卓:theme="@style/AppTheme.AppBarOverlay">
<安卓.support.v7.widget.Toolbar
安卓:id="@+id/toolbar"
安卓:layout_width="match_parent"
安卓:layout_height="?attr/actionBarSize"
安卓:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
</安卓.support.design.widget.AppBarLayout>
<安卓.support.design.widget.FloatingActionButton
安卓:id="@+id/fab"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_gravity="bottom|end"
安卓:layout_margin="@dimen/fab_margin"
app:srcCompat="@安卓:drawable/ic_dialog_email" />
</安卓.support.design.widget.CoordinatorLayout>
现在在我的活动xml中,我有这样一个:
<?xml version="1.0" encoding="utf-8"?>
<安卓.support.constraint.ConstraintLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"
安卓:fitsSystemWindows="true"
xmlns:app="http://schemas.安卓.com/apk/res-auto"
xmlns:tools="http://schemas.安卓.com/tools"
安卓:layout_width="match_parent"
安卓:layout_height="match_parent"
tools:context="com.example.afcosta.inesctec.pt.安卓.FamilyLibrary"
安卓:paddingTop="6dp">
<安卓.support.design.widget.FloatingActionButton
安卓:id="@+id/fab"
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:layout_gravity="bottom|end"
安卓:layout_margin="@dimen/fab_margin"
app:srcCompat="@安卓:drawable/ic_menu_camera"
app:backgroundTint="#f1c40f"
tools:layout_constraintRight_creator="1"
tools:layout_constraintBottom_creator="1"
app:layout_constraintBottom_toBottomOf="parent"
安卓:layout_marginEnd="37dp"
app:layout_constraintRight_toRightOf="parent"
安卓:layout_marginBottom="33dp" />
在上面的第一个例子中,我有onclick监听器,但它不工作,它不进入onclick,日志永远不会显示:S
有什么建议吗
# 1 楼答案
视图本身不能跨活动使用,但片段可以跨活动使用。因此,在安卓系统中,如果你要求某些视图或视图组可以跨活动访问,那么你可以制作这些视图组的片段,然后跨活动使用它们。因此,在本例中,您可以创建一个包含fab的片段,然后在每个活动布局中为片段保留右下角,并在创建活动时将片段放在那里
有关片段的更多信息,请参考以下参考资料:-
{a1}
{a2}