主要活动
import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void button(View v)
{
FragmentManager fragmentManager=getFragmentManager();
frag1 f1=new frag1();
f1.show(fragmentManager,"TAG");
}
}
片段
import android.app.DialogFragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class frag1 extends DialogFragment implements View.OnClickListener{
Button button;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.frag1,container,false);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
button= (Button) getActivity().findViewById(R.id.button);
button.setOnClickListener((View.OnClickListener) getActivity());
}
@Override
public void onClick(View v) {
Toast.makeText(getActivity(),"working",Toast.LENGTH_LONG).show();
}
}
这是一个简单对话框的代码。
这是我从中学到的link。如果我只是通过调用按钮创建对话框,它完全正常。
答案 0 :(得分:0)
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup
container, @Nullable Bundle savedInstanceState) {
View view =inflater.inflate(R.layout.frag1,container,false);
button= (Button) View.findViewById(R.id.button);
button..setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Toast.makeText(getActivity(),"working",Toast.LENGTH_LONG).show();
}
});
return view;
}
答案 1 :(得分:0)
从
更改您的行button.setOnClickListener((View.OnClickListener) getActivity());
到
button.setOnClickListener(this);
另外,使用
getSupportFragmentManager() to instead of getFragmentManager()
并导入
import android.support.v4.app.FragmentManager;