java如何为自定义布局中的按钮实现ClickListener以在片段对话框中使用
我正在尝试设置ImageButton的操作。当DialgoFragment被调用并显示在屏幕上时,我想按下按钮并获得一个操作。当我把我的动作放在下面代码的onClick中时,它不起作用。我肯定那不是正确的做法
我使用这个类作为片段:
public class GeneralDialogFragment extends DialogFragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout to use as dialog or embedded fragment
View v = inflater.inflate(R.layout.activity_dialog, container, false);
ImageButton mImageButton = (ImageButton) v.findViewById(R.id.image_button);
mImageButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
String name = "";
SharedPreferences prefs = getActivity().getSharedPreferences("MY_PREFS_NAME", Context.MODE_PRIVATE);
String yourmessage = prefs.getString("msg", null);
if (yourmessage != null) {
name = prefs.getString("msg", "No name defined");//"No name defined" is the default value.
}
ScrollTextView txt = (ScrollTextView) v.findViewById(R.id.scroll_text);
txt.setText(name);
txt.setTextSize(220);
txt.startScroll();
}
});
return v;
}
在这个活动对话框布局中,我有一个ImageButton:
<ImageButton
安卓:layout_width="wrap_content"
安卓:layout_height="wrap_content"
安卓:id="@+id/image_button"
安卓:src="@drawable/ic_image_500px"/>
编辑:现在动作在上面的类中。错误实际上在操作中。我有按下此发送按钮的主要活动:
public void send(View view){
EditText mEditText = (EditText)findViewById(R.id.text_msg);
String MESSAGE = mEditText.getText().toString();
SharedPreferences.Editor editor = getSharedPreferences("MY_PREFS_NAME", MODE_PRIVATE).edit();
editor.putString("msg", MESSAGE );
editor.commit();
Intent intent = new Intent(this, MessageActivity.class );
startActivity(intent);
}
它调用MessageActivity,我在其中调用GeneralDialogFragment类,该类显示带有以下代码的ImageButton:
DialogFragment mDialog = new GeneralDialogFragment();
mDialog.show(getSupportFragmentManager(), "Dialog TAG");
# 1 楼答案
因为
v
是您之前添加的,所以它可以正常工作,没有任何错误: