我有一个文本视图,它在除 onCreateDialog 方法之外的所有片段和 MainActivity 中都是空的。 所以...我想在另一种方法中使用它,但我无法接收它,因为它为空... 并且似乎 onCreateDialog 方法运行一次。 getView 方法为调用 findViewById 方法返回空值。 还有什么方式存在? 这是我的代码:
public class AmanatDialog extends DialogFragment implements AmanatAdapter.OnDeleteBookAmanat {
private TextView centerTextAmanatDialog;
@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
View view = LayoutInflater.from(getContext()).inflate(R.layout.amanat , null , false);
builder.setView(view);
centerTextAmanatDialog = view.findViewById(R.id.center_text_amanat_dialog);
recyclerView = view.findViewById(R.id.rv_amanat);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext() , RecyclerView.VERTICAL , false));
recyclerView.setAdapter(amanatAdapter);
EditText addBook = view.findViewById(R.id.et_amanat_addBook);
MaterialButton btnSave = view.findViewById(R.id.btn_amanat_add_book);
btnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if(addBook.length() > 0){
onSendBookAmanatId.onSendBookId(Integer.parseInt(addBook.getText().toString()));
centerTextAmanatDialog.setText("");
}
else{
Toast.makeText(getContext() , "فیلد آیدی نمی تواند خالی باشد",Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
return builder.create();
}
我能做什么?
这是我的 amanat 布局
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="9dp">
<TextView
android:id="@+id/center_text_amanat_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="این کاربر هیچ کتابی امانت نگرفته است"
android:fontFamily="@font/primary_regular"
android:layout_gravity="center"/>
</FrameLayout>
我想访问这个方法......(这个方法在顶部的 AmanatDialog 类中)
public void getBooksAmanat(Contact contact , ContacsDao contacsDao) throws
JSONException {
this.contacsDao = contacsDao;
this.contact = contact;
String json = contacsDao.getBooksAmanat(contact.getId());
if(json != null){
JSONArray jsonArray = new JSONArray(json);
List<Book> books = new ArrayList<>();
for(int i = 0 ; i < jsonArray.length() ; i++){
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
Book book = new Book();
book.setId(jsonObject1.getInt("id"));
book.setName(jsonObject1.getString("name"));
book.setAuthor(jsonObject1.getString("author"));
books.add(book);
}
amanatAdapter.setBooks(books);
centerTextAmanatDialog.setText("");
}
else{
centerTextAmanatDialog.setText("این کاربر هنوز کتابی امانت نگرفته است");
}
}
答案 0 :(得分:0)
也许您需要在 view.
之前删除 findViewById
试试这个
centerTextAmanatDialog = findViewById(R.id.center_text_amanat_dialog);