在我的应用程序中,我有一些片段。在它们的布局中,我放置了一些元素,但是找不到如何初始化以下元素。我也知道这种方式:
element = view.findViewById(R.id.element);
但是我有一些函数需要初始化以下元素:
public class Received extends Fragment {
private OnFragmentInteractionListener mListener;
@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_received, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
received();
}
public void received() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://my_server/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
String access_token = "token";
final APIService mAPIService = retrofit.create(APIService.class);
mAPIService.getInMess("Bearer "+access_token,0, 1).enqueue(new Callback<ListOfMess>() {
@Override
public void onResponse(@NonNull Call<ListOfMess> call, @NonNull Response<ListOfMess> response) {
if (response.isSuccessful()) {
}
}
@Override
public void onFailure(@NonNull Call<ListOfMess> call, @NonNull Throwable t) {
}
});
}
/*private String getTokenFromShared(){
return getSharedPreferences(Constants.SP_NAME, MODE_PRIVATE).getString(Constants.SP_ACCESS_TOKEN, "");
}*/
public void fillList()
{
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
我必须在函数中初始化我的元素,我尝试了 view.findviewbyid ,只有 findViewbyId ,但是没有任何效果,android studio找不到这些元素。希望您能解决以下问题。
答案 0 :(得分:0)
在Fragments中,您需要使用onCreateView方法初始化视图,就像这样:
View element;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_observations_list, container, false);
element = view.findViewById(R.id.element);
return view;
}