如何从DialogFragment中的TextView获取文本到MainActivity,或者当DialogFragment中的Button单击时如何在MainActivity中创建事件。请求帮助我,我在下面尝试过这样的方法:但是它无法正常工作是问题。
public class MainActivity extends AppCompatActivity {
Button b; Button b2; String name;
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
name = data.getStringExtra("name").toString();
Toast.makeText(MainActivity.this,name+ "", Toast.LENGTH_LONG).show();}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b=(Button)findViewById(R.id.b);
b=(Button)findViewById(R.id.b);
b2=(Button)findViewById(R.id.b2);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b2.setText(name);}});}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mainmenu, menu);
return true;}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
FragmentManager manager = getFragmentManager();
fragment afr = new fragment();
afr.setTargetFragment(afr, 1);
afr.show(manager, "dialog");
return true;}}
class fragment extends DialogFragment {
View v; Intent intent; EditText t1; Button b1; String name;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment, container, false);
t1=(EditText) v.findViewById(R.id.t1);
b1=(Button) v.findViewById(R.id.b1);
intent = new Intent();
int resultCode = 1;
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
getDialog().dismiss();
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
name=t1.getText().toString();
intent.putExtra("name", name);
fragment.this.dismiss();
}}); return v;}}
答案 0 :(得分:0)
您可以使用界面。 在片段中声明接口并在MainActivity中实现它。
https://developer.android.com/training/basics/fragments/communicating.html
在DialogFragment中声明
public IDialogCallback {
void onTextWritted(String text);
void onDialogBtnClick()
}
然后在对话框中声明字段:
OnDialogCallback mCallback
随后:
@Override
public void onAttach(Context context) {
super.onAttach(context);
mCallback = (ITailLiftCallback) context;
}
现在,您可以在DialogFragment中调用mCallback.onTextWritted()
或mCallback.onDialogBtnClick
。在第一种情况下,您可以从TextView中放置文本,然后将其放在按钮的OnClickListener中。
然后制作MainActivity implements IDialogCallback
就可以了! :)