i am new to android, i want to add fragment button like in activity, but i can't add it where do i add it (findViewById is not coming out when i try to add it anywhere)
private ImageView walleticon;
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
public static SatisFragment newInstance(String param1, String param2) {
SatisFragment fragment = new SatisFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_satis, container, false);
}
public SatisFragment(){
}
}```
CodePudding user response:
In fragments the view is accessed in a different way.
In an Activity you use, setContentView(R.layout.activity_main);
This allows the use of straight calls to findViewById(R.id.button);
In a Fragment findViewById
only exists at the individual view level.
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_satis, container, false);
Button button = view.findViewById(R.id.button); //<-- Here is your button
return view;
}
CodePudding user response:
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
ImageView walleticon = (ImageView) getView().findViewById(R.id.wallet);
// or (ImageView) view.findViewById(R.id.foo);
walleticon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getActivity(), "hey", Toast.LENGTH_SHORT).show();
}
});
}```