简体   繁体   English

如何将两个参数从片段传递到活动

[英]How I can pass two parameters from a fragment to an activity

Hello how can I pass two parameters from a fragment to an activity? 您好,如何将两个参数从片段传递到活动? I tried to do this but I can't. 我试图这样做,但我做不到。 I got only the ref in the TextView editRef but the TextView et_login is empty 我只有TextView editRef中的引用,但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 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);
}

Carefully check you are using the same keys for the intents. 仔细检查您是否对意图使用了相同的键

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

Is not the same as 与...不同

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

What you've shown in ViewResult.java should work with what you have in onItemClick assuming map.get() isn't returning you null . 假设map.get()不返回null ,则ViewResult.java显示的内容应与onItemClick map.get()

It should be mentioned though, that using the Activity intent is not how you give parameters to Fragments. 应当指出的是,使用Activity意图并不是您为Fragments赋予参数的方式。 Please see Best practice for instantiating a new Android Fragment . 请参阅实例化新Android Fragment的最佳做法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM