DialogFragment에 인수 전달
에 일부 변수를 전달해야 DialogFragment
하므로 작업을 수행 할 수 있습니다. 이클립스는 내가 사용해야한다고 제안한다.
Fragment#setArguments(Bundle)
그러나이 기능을 사용하는 방법을 모르겠습니다. 변수를 대화 상자에 전달하는 데 어떻게 사용할 수 있습니까?
사용 newInstance
public static MyDialogFragment newInstance(int num) {
MyDialogFragment f = new MyDialogFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
그리고 Args를 이렇게 얻으십시오
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments().getInt("num");
...
}
http://developer.android.com/reference/android/app/DialogFragment.html 에서 전체 예제를
참조하십시오.
내 목록보기에서 값을 보내곤했습니다.
보내는 방법
mListview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Favorite clickedObj = (Favorite) parent.getItemAtPosition(position);
Bundle args = new Bundle();
args.putString("tar_name", clickedObj.getNameTarife());
args.putString("fav_name", clickedObj.getName());
FragmentManager fragmentManager = getSupportFragmentManager();
TarifeDetayPopup userPopUp = new TarifeDetayPopup();
userPopUp.setArguments(args);
userPopUp.show(fragmentManager, "sam");
return false;
}
});
DialogFragment의 onCreate () 메소드 내부 에서 수신하는 방법
Bundle mArgs = getArguments();
String nameTrife = mArgs.getString("tar_name");
String nameFav = mArgs.getString("fav_name");
String name = "";
// 코 틀린 업로드
val fm = supportFragmentManager
val dialogFragment = AddProgFargmentDialog() // my custom FargmentDialog
var args: Bundle? = null
args?.putString("title", model.title);
dialogFragment.setArguments(args)
dialogFragment.show(fm, "Sample Fragment")
// 받기
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (getArguments() != null) {
val mArgs = arguments
var myDay= mArgs.getString("title")
}
}
JafarKhQ가 지적했듯이 Fragments를 사용하는 일반적인 방법으로 생성자의 매개 변수를 전달하지 말고을 사용해야합니다 Bundle
.
Fragment
클래스 에 내장 된 메소드 는 setArguments(Bundle)
and getArguments()
입니다.
기본적으로 모든 Parcelable
항목이 포함 된 번들을 설정하여 보내십시오.
차례로 조각이 해당 항목을 가져 와서 onCreate
마술처럼 만듭니다.
DialogFragment
링크에 표시된 방식은 하나의 특정 유형의 데이터가있는 여러 개의 나타나는 조각 에서이 작업을 수행하는 한 가지 방법이었으며 대부분 잘 작동하지만 수동으로 수행 할 수도 있습니다.
따라서 조각 / 활동에서 대화 조각으로 값을 전달하는 두 가지 방법이 있습니다.
make setter 메소드를 사용하여 대화 상자 단편 오브젝트를 작성하고 값 / 인수를 전달하십시오.
번들을 통해 값 / 인수를 전달하십시오.
방법 1 :
// Fragment or Activity
@Override
public void onClick(View v) {
DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
dialog.setValue(header, body);
dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");
}
// your dialog fragment
public class MyDialogFragment extends DialogFragment {
String header;
String body;
public void setValue(String header, String body) {
this.header = header;
this.body = body;
}
// use above variable into your dialog fragment
}
참고 :-이것은 최선의 방법이 아닙니다
방법 2 :
// Fragment or Activity
@Override
public void onClick(View v) {
DialogFragmentWithSetter dialog = new DialogFragmentWithSetter();
Bundle bundle = new Bundle();
bundle.putString("header", "Header");
bundle.putString("body", "Body");
dialog.setArguments(bundle);
dialog.show(getSupportFragmentManager(), "DialogFragmentWithSetter");
}
// your dialog fragment
public class MyDialogFragment extends DialogFragment {
String header;
String body;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
header = getArguments().getString("header","");
body = getArguments().getString("body","");
}
}
// use above variable into your dialog fragment
}
참고 :-이것이 가장 좋은 방법입니다.
제 경우에는 위의 코드 중 어느 것도 bundle-operate
작동 하지 않습니다 . 여기 내 결정이 있습니다 (적절한 코드인지 아닌지는 모르겠지만 제 경우에는 효과가 있습니다).
public class DialogMessageType extends DialogFragment {
private static String bodyText;
public static DialogMessageType addSomeString(String temp){
DialogMessageType f = new DialogMessageType();
bodyText = temp;
return f;
};
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final String[] choiseArray = {"sms", "email"};
String title = "Send text via:";
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(title).setItems(choiseArray, itemClickListener);
builder.setCancelable(true);
return builder.create();
}
DialogInterface.OnClickListener itemClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
prepareToSendCoordsViaSMS(bodyText);
dialog.dismiss();
break;
case 1:
prepareToSendCoordsViaEmail(bodyText);
dialog.dismiss();
break;
default:
break;
}
}
};
[...]
}
public class SendObjectActivity extends FragmentActivity {
[...]
DialogMessageType dialogMessageType = DialogMessageType.addSomeString(stringToSend);
dialogMessageType.show(getSupportFragmentManager(),"dialogMessageType");
[...]
}
Just that i want to show how to do what do said @JafarKhQ in Kotlin for those who use kotlin that might help them and save theme time too:
so you have to create a companion objet to create new newInstance function
you can set the paremter of the function whatever you want. using
val args = Bundle()
you can set your args.
You can now use args.putSomthing
to add you args which u give as a prameter in your newInstance function. putString(key:String,str:String)
to add string for example and so on
Now to get the argument you can use arguments.getSomthing(Key:String)
=> like arguments.getString("1")
here is a full example
class IntervModifFragment : DialogFragment(), ModContract.View
{
companion object {
fun newInstance( plom:String,type:String,position: Int):IntervModifFragment {
val fragment =IntervModifFragment()
val args = Bundle()
args.putString( "1",plom)
args.putString("2",type)
args.putInt("3",position)
fragment.arguments = args
return fragment
}
}
...
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fillSpinerPlom(view,arguments.getString("1"))
fillSpinerType(view, arguments.getString("2"))
confirmer_virme.setOnClickListener({on_confirmClick( arguments.getInt("3"))})
val dateSetListener = object : DatePickerDialog.OnDateSetListener {
override fun onDateSet(view: DatePicker, year: Int, monthOfYear: Int,
dayOfMonth: Int) {
val datep= DateT(year,monthOfYear,dayOfMonth)
updateDateInView(datep.date)
}
}
}
...
}
Now how to create your dialog you can do somthing like this in another class
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
like this for example
class InterListAdapter(private val context: Context, linkedList: LinkedList<InterItem> ) : RecyclerView.Adapter<InterListAdapter.ViewHolder>()
{
...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
...
holder.btn_update!!.setOnClickListener {
val dialog = IntervModifFragment.newInstance(ListInter.list[position].plom,ListInter.list[position].type,position)
val ft = (context as AppCompatActivity).supportFragmentManager.beginTransaction()
dialog.show(ft, ContentValues.TAG)
}
...
}
..
}
참고URL : https://stackoverflow.com/questions/15459209/passing-argument-to-dialogfragment
'IT story' 카테고리의 다른 글
SQL을 사용하여 데이터베이스 테이블의 열 이름을 바꾸려면 어떻게합니까? (0) | 2020.08.04 |
---|---|
컴파일 타임에 #define의 값을 어떻게 표시합니까? (0) | 2020.08.04 |
내용 편집 가능한 추가 방지 (0) | 2020.08.04 |
위조 방지 토큰 문제 (MVC 5) (0) | 2020.08.04 |
버전이없는 버전의 Subversion 자동 제거 (0) | 2020.08.04 |