我是android studio的初学者。我被困在这一点,无法将数据从活动传递到对话框。我已经尝试了捆绑但是也没有工作因为它显示了NULL点异常。或者我猜我的方法是错误的。如果我能得到它会很棒一些帮助。
对话类
public class Mdlog extends DialogFragment
{
LayoutInflater inflater;
TextView sc1,sc2;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder=new AlertDialog.Builder(getActivity());
inflater=getActivity().getLayoutInflater();
View view=inflater.inflate(R.layout.layout_dialog,null);
Intent i=getActivity().getIntent();
sc1= (TextView) view.findViewById(R.id.score1);
sc2= (TextView) view.findViewById(R.id.score2);
sc1.setText(i.getStringExtra("sc1"));
sc2.setText(i.getStringExtra("sc2"));
builder.setView(view);
AlertDialog dialog=builder.create();
return dialog;
}}
MainActivity类
public class MainActivity extends AppCompatActivity {
int sc1=0;
int sc2=0;
TextView t;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t= (TextView) findViewById(R.id.timeleft);
new CountDownTimer(3000,1000)
{
@Override
public void onTick(long millisUntilFinished)
{
t.setText(""+millisUntilFinished/1000);
sc1+=1;
sc2+=2;
}
@Override
public void onFinish()
{
}
}.start();
Intent i=new Intent(this,Mdlog.class);
i.putExtra("sc1",sc1);
i.putExtra("sc2",sc2);
startActivity(i);
Mdlog dialog=new Mdlog();
dialog.show(getFragmentManager(),"sss");
}}
答案 0 :(得分:1)
删除整个,
Intent i=new Intent(this,Mdlog.class);
i.putExtra("sc1",sc1);
i.putExtra("sc2",sc2);
startActivity(i);
为bundle
设置arguments
以传递数据,然后设置为您的片段,
Bundle args = new Bundle();
args.putInt("sc1", sc1);
args.putInt("sc2", sc2);
Mdlog dialog=new Mdlog();
dialog.setArguments(args);
dialog.show(getFragmentManager(),"dialog");
使用
在对话框中获取数据Bundle args = getArguments();
int sc1 = args.getInt("sc1");
int sc2 = args.getInt("sc2");
答案 1 :(得分:0)
您应该使用静态方法创建片段。如果在DialogFragment中键入newIsntance
,Android Studio将生成一个newInstance静态方法。您可以将数据传递给该方法。例如:
public static DialogFragment newInstance(int value1, int value2) {
DownloadDialogFragment dialogFragment = new DownloadDialogFragment();
Bundle args = new Bundle();
args.putInt("args_value1", value1);
args.putInt("args_value2", value2);
dialogFragment.setArguments(args);
return dialogFragment;
}
您可以像onCreateDialog(Bundle savedInstanceState)
这样获取数据:
public Dialog onCreateDialog(Bundle savedInstanceState) {
int value1 = getArguments().getInt("args_value1");
int value2 = getArguments().getInt("args_value2");
}