【发布时间】:2016-12-15 11:29:00
【问题描述】:
我已经创建了一个自定义类扩展对话框片段,并且当我想在主要活动中设置我的 onclicklistener 时,我现在使用布局来膨胀到这个对话框中,但是当我设置我的点击侦听器时它返回空点异常是我的主要活动和我的对话片段:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button cancelDialog = (Button) findViewById(R.id.cancelDialogButton);
View.OnClickListener listenerDialog = new View.OnClickListener() {
@Override
public void onClick(View v) {
}
};
//this is where i get the null point exception
cancelDialog.setOnClickListener( listenerDialog );
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ViewGroup Addition = (ViewGroup) findViewById(R.id.activity_addition);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
FragmentManager fm = getSupportFragmentManager();
DialogCards editNameDialogFragment = DialogCards.newInstance();
editNameDialogFragment.show(fm, "fragment_edit_name");
}
});
现在我的服装类扩展对话片段:
public class DialogCards extends DialogFragment {
public Dialog dialog;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
// request a window without the title
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
@Override
public void onResume() {
// Store access variables for window and blank point
Window window = getDialog().getWindow();
Point size = new Point();
// Store dimensions of the screen in `size`
Display display = window.getWindowManager().getDefaultDisplay();
display.getSize(size);
// Set the width of the dialog proportional to 75% of the screen width
window.setLayout((int) (size.x * 0.75), WindowManager.LayoutParams.WRAP_CONTENT + 20);
window.setGravity(Gravity.CENTER);
// Call super onResume after sizing
super.onResume();
}
public DialogCards() {
}
public static DialogCards newInstance() {
DialogCards frag = new DialogCards();
Bundle args = new Bundle();
frag.setArguments(args);
return frag;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.carddialog, container);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getDialog().getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}}
【问题讨论】:
-
你在哪里得到空指针?能否请您发布您的日志。
-
在我将点击监听器设置为我的按钮的那一行
-
你在主活动布局或卡片对话框布局中有那个按钮吗?
-
卡片对话框布局
-
如果您在卡片对话框布局中有该按钮,您将不会在导致崩溃的 mainactivity 中获得该按钮。 final Button cancelDialog = (Button) findViewById(R.id.cancelDialogButton); View.OnClickListener listenerDialog = new View.OnClickListener() { @Override public void onClick(View v) { } };将此代码移至 DialogFragment 类
标签: java android android-fragments onclicklistener dialogfragment