我在home_fragment.xml
中添加了一个浮动共享按钮。但我不知道从哪里开始如何为该共享按钮添加功能。请帮忙。
这是片段java文件的代码,我尝试过编码,但是我失败了,如果有人能提供帮助,我会很高兴。
public class HomeFragment extends Fragment {
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home, null);
}
}
单击按钮时,可以使用View.OnClickListener调用回调方法。有关更多信息,请参阅https://developer.android.com/reference/android/view/View.OnClickListener。
就像@kAliert已经回答的那样,你必须得到一个View firstand的实例,有很多类似的问题和答案可能有所帮助。
对任何样式或语法错误提前道歉
以下是如何在片段中执行此操作的示例:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View homeFragmentView= inflater.inflate(R.layout.fragment_home, container, false);
FloatingActionButton animationDetailShare= homeFragmentView.findViewById(R.id.animation_detail_share);
btnCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//The logic for the button
}
});
return homeFragmentView;
}
获取视图实例并找到按钮。这并不难,我猜它已经回答了很多次。
public class HomeFragment extends Fragment {
Button share_bt;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView= inflater.inflate(fragment_home, container, false);
FloatingActionButton share_bt= rootView.findViewById(R.id.share_bt);
share_bt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
String shareBody = "hu" ;
String shareSub = "mk";
myIntent.putExtra(Intent.EXTRA_SUBJECT,shareBody);
myIntent.putExtra(Intent.EXTRA_TEXT,shareSub);
startActivity(Intent.createChooser(myIntent, "Share Using"));
}
});
return rootView;
}
}