【问题标题】:How I can pass two parameters from a fragment to an activity如何将片段中的两个参数传递给活动
【发布时间】:2016-06-01 04:04:43
【问题描述】:

您好,如何将片段中的两个参数传递给活动?我试图这样做,但我做不到。 我只得到了 TextView editRef 中的 ref,但 TextView et_login 是空的

public class ResultFragmentC  extends Fragment implements ListView.OnItemClickListener {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootview = inflater.inflate(R.layout.fragment_result, container, false);
        et_login = (TextView) rootview.findViewById(R.id.et_login);
        Intent intent = getActivity().getIntent();
        String log = intent.getStringExtra("login");
        et_login.setText(log);
......

}
......

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity().getApplicationContext(), ViewResult.class);
            HashMap<String, String> map = (HashMap) parent.getItemAtPosition(position);
            String tid = map.get("ref");
            intent.putExtra("ref", tid);
            String tid2 = map.get("log");
            intent.putExtra("log", tid2);
            startActivity(intent);
        }

ViewResult.java

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_result);
        Intent intent = getIntent();
        layout=(LinearLayout) findViewById(R.id.layout);
        String ref2 = intent.getStringExtra("ref");
        et_login = (TextView) findViewById(R.id.et_login);
        String log = intent.getStringExtra("log");
        et_login.setText(log);
        editRef = (TextView) findViewById(R.id.editRef);
        editRef.setText(ref2);
}

【问题讨论】:

  • 这应该可以了,你确定你放的时候log不为空或者null吗?
  • 检查我的这个答案stackoverflow.com/a/36467198/3073945
  • @cricket_007 是两个。对不起
  • @cyroxis 是的,它不是空的
  • 我有一个登录表单。所以我想在所有片段和活动中显示登录。在第一个片段中,我有一个带有登录名的列表视图,但是当我单击列表视图时,活动中没有显示登录名

标签: android


【解决方案1】:

仔细检查您对意图使用相同的键

Intent intent = getActivity().getIntent();
String log = intent.getStringExtra("login");

不一样
Intent intent = getIntent();
String log = intent.getStringExtra("log");

假设map.get() 没有返回您null,您在ViewResult.java 中显示的内容应该与您在onItemClick 中的内容一起使用。

但应该提到的是,使用 Activity Intent 并不是为 Fragment 提供参数的方式。请参阅Best practice for instantiating a new Android Fragment

【讨论】:

  • 我有一个登录表单。所以我想在所有片段和活动中显示登录。在第一个片段中,我有一个带有登录名的列表视图,但是当我单击列表视图时,活动中没有显示登录名
  • 好吧,就像我说的那样,ViewResult.java 应该可以工作并显示数据,除非您最终将 null 放入 intent.putExtra("log", tid2);
  • 另外,fragment_result.xmlview_result.xml 实际上是一样的吗?他们都有@+id/et_login?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多