我想從 to 發送資料MainActivity,Fragment但我不想在向片段進行事務時傳遞引數中的資料,如下所示:
val bundle = Bundle()
bundle.putString("name", name)
val fragment = BlankFragment(this)
fragment.arguments = bundle
supportFragmentManager.beginTransaction().replace(R.id.fragmentView, fragment).commit()
我想將資料從 傳遞activity到fragment使用interface. 我可以使用介面將資料從片段發送到活動,反之亦然。
uj5u.com熱心網友回復:
你有一個片段的實體fragment,所以只要它有一個name你可以說的屬性fragment.name = "name"。
請注意,當應用程式被殺死后被系統重新啟動時,系統將嘗試通過使用空建構式呼叫它來恢復片段。所以你不能有一個有 arguments 的建構式name,如果你設定它,你也不會得到 a fragment.name = "name"。使用捆綁包可確保片段在重新啟動后獲取其引數。
uj5u.com熱心網友回復:
我希望這可以解決您的問題
將片段添加到 Activity
val interfaceCall:FetchDataInterface = DataFragment.newInstance("data")
interfaceCall.getData("data from interface")
supportFragmentManager.beginTransaction()
.replace(R.id.frame, DataFragment.newInstance("data"))
.commit()
片段類
class DataFragment : Fragment(),MainActivity.FetchDataInterface {
// TODO: Rename and change types of parameters
private var param1: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
param1 = it.getString(DATA)
Log.e("checkParam", " : $param1")
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?,
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_data, container, false)
}
companion object {
// TODO: Rename and change types and number of parameters
@JvmStatic
fun newInstance(value: String) =
DataFragment().apply {
arguments = Bundle().apply {
putString(DATA, value)
}
}
}
override fun getData(value: String) {
Log.e("checkParam", " interface: $value")
}
}
界面
interface FetchDataInterface{
fun getData(value:String)
}
uj5u.com熱心網友回復:
試試這個一次
在活動中......
TextEditorDialogFragment textEditorDialogFragment =
TextEditorDialogFragment.show(this, text, colorCode);
在片段中......
public class TextEditorDialogFragment extends DialogFragment {
public static final String TAG = TextEditorDialogFragment.class.getSimpleName();
String inputText;
int colorCode;
public static TextEditorDialogFragment show(@NonNull AppCompatActivity appCompatActivity, @NonNull String inputText_, @ColorInt int colorCode_) {
inputText =inputText_;
colorCode=colorCode_;
TextEditorDialogFragment fragment = new TextEditorDialogFragment();
fragment.show(appCompatActivity.getSupportFragmentManager(), TAG);
return fragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.add_text_dialog, container, false);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/518137.html
標籤:爪哇安卓科特林安卓片段
上一篇:表格未定義問題?
