我正在尝试为ImageButton设置操作。当DialgoFragment被调用并显示在屏幕上时,我想预示按钮并获得一个操作。当我将我的操作放入下面的代码中时,它不起作用。我敢肯定这不是正确的做法。
我将此类用作片段:
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;
}
在这个activity_dialog布局中,我有一个图像按钮:
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/image_button"
android: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");
由于您之前添加过v
,它可以正常工作,没有任何错误:
View v = inflater.inflate(R.layout.activity_dialog, container, false);
ImageButton mImageButton = (ImageButton) v.findViewById(R.id.image_button);