【问题标题】:How to pass data to an activity from a fragment?如何将数据从片段传递给活动?
【发布时间】:2019-10-05 05:26:10
【问题描述】:

我想将数据从片段发送到活动,但我当前的代码不起作用。

    TextView mTituloTv=view.findViewById(R.id.titulo_producto_regis);
    TextView mSubTituloTv=view.findViewById(R.id.subtitulo_producto_regis);
    TextView mPrecioTv=view.findViewById(R.id.precio_producto_regis);
    TextView mDescripcionTv=view.findViewById(R.id.descripcion_producto_regis);

    String mTitulo=mTituloTv.getText().toString();
    String mSubTitulo=mSubTituloTv.getText().toString();
    String mPrecio=mPrecioTv.getText().toString();
    String mDescripcion=mDescripcionTv.getText().toString();

    Intent intent=new Intent(getContext(),Producto_Detallado.class);

    intent.putExtra("mtitulo",mTitulo); 
    intent.putExtra("mdescripcion",mDescripcion); 
    intent.putExtra("msubtitulo",mSubTitulo); 
    intent.putExtra("mprecio",mPrecio);

    startActivity(intent);

【问题讨论】:

标签: java android android-activity fragment


【解决方案1】:

您可以使用接口将数据从片段发送到活动。您可以在片段中创建接口和方法: 就像这是你的界面代码-

interface YourInterface {
fun sendData(data:YourDataMODEL)
}

这是你的方法——在片段中创建你的接口的全局对象

private var listener : YourInterface? = null

fun setListener(yourInterface : YourInterface){
this.listener = yourInterface
}

在你想要的地方调用你的接口对象 - listener.sendData(yourModel)

当您在活动中初始化片段时,然后使用片段对象调用此方法-

val fragment = YourFragment()
fragment.setListener(this)

现在您可以像这样在 Activity 中实现此接口方法:

@override
fun sendData(data : YourDataMODEL){
// Do Something here
}

我觉得这对你有帮助

【讨论】:

  • 标记重复,答案已经在 Stackoverflow 上
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多