下面是我的應用程式的一些代碼。我需要幫助的部分requireActivity()在 SettingFragment.java 中:
主活動.java
...
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
}
public void iniciarIntent3() { //this method is called by a button in activity_main.xml
Intent intent = new Intent(this, Settings.class);
startActivityForResult(intent, 1);
}
}
設定.java
...
public class Settings extends AppCompatActivity implements SettingsFragment.SendToActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState == null) {
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.settings, new SettingsFragment())
.commit();
}
}
@Override
public void onAttachFragment(Fragment fragment) {
if (fragment instanceof SettingsFragment) {
SettingsFragment settingsFragment = (SettingsFragment) fragment;
settingsFragment.setSendToActivity(this);
}
}
public void send(int result) {
...
}
}
設定片段.java
public class SettingsFragment extends PreferenceFragmentCompat {
SendToActivity callback;
public void setSendToActivity (SendToActivity callback) {
this.callback = callback;
}
public interface SendToActivity {
void send(int result);
}
if (editTextPreference != null) {
editTextPreference.setOnBindEditTextListener(new
EditTextPreference.OnBindEditTextListener() {
@Override
public void onBindEditText(@NonNull EditText editText) {
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
editText.setText("");
editText.setBackground(ContextCompat.getDrawable(requireActivity()
.getApplicationContext(), R.drawable.fondo_edittextpreference));
}
});
}
...
}
我只想確保requireActivity()在 SettingsFragment 類中不會拋出 nullpointerexeption。你能幫我查一下嗎?
uj5u.com熱心網友回復:
而不是requireActivity().getApplicationContext()您可以執行以下任一操作
editText.setBackground(ContextCompat.getDrawable(editText.getContext(), R.drawable.fondo_edittextpreference))editText.setBackgroundResource(R.drawable.fondo_edittextpreference)
uj5u.com熱心網友回復:
需要活動()
如果 Activity 由于任何原因為 null,則可以拋出 null。我相信如果用戶存在應用程式或完全停止它等,則可以為 null。或者在您所在的背景關系中從未創建過
做一個空檢查
Activity activity = requireActivity()
if (activity != null)
editText.setBackground(ContextCompat.getDrawable(activity
.getApplicationContext(), R.drawable.fondo_edittextpreference));
else
//handle here when the activity is null
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/310826.html
上一篇:最有效的演算法和BigO符號
下一篇:Android使用Intent保存和寫入文本檔案,得到IOException“Nocontentprovider”
