在一个片段上使用列表视图选择的项目在另一个片段上显示文本

use listview selected item on one fragment to display text on other fragment

我有两个片段,一个带有列表视图,另一个带有文本视图,我希望当一个项目被选中时,它的文本用于在另一个片段的文本视图上设置文本并显示另一个片段。

所以我像这样在列表视图 (lv) 上设置了一个 onItemClickListener;

lv.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v1,
                    int pos, long arg3) {



String hh =  lv.getItemAtPosition(pos).toString().toLowerCase();


    int resd = getResources().getIdentifier(hh, "raw", getPackageName());
    InputStream isd = getResources().openRawResource(resd); 
    BufferedReader brd = new BufferedReader(new InputStreamReader(isd));
    String lined; 
    String entireFiled = "";

    try {
        while((lined = brd.readLine()) != null) { 
            entireFiled += (lined + "\n"); 
        }
    }

    catch (Exception e) {
        Toast.makeText(getApplicationContext(),"Error reading file!",Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }

     TextView output1= (TextView) findViewById(R.id.fp);    
    output1.setText(entireFiled);


        Family frag5 = new Family();
        FragmentManager fm = getSupportFragmentManager();       
        FragmentTransaction ft = fm.beginTransaction().replace(R.id.fl, frag5).addToBackStack(null);    
        ft.commit();

            }
        });

另一个片段叫做Family,它的textview是output1。当我 运行 它时,我在 textview 行得到空异常。那我该怎么做呢?谢谢

您无法访问另一个片段 textview,例如 that.For 将一个片段与另一个片段通信尝试使用 Handler

或者在您的情况下,您可以尝试在单击按钮时使用共享 Preference.Save 第一个片段中的数据。当家庭片段出现时,只需从共享首选项中检索数据并将其显示在家庭片段的文本视图中。

您需要使用 setArgument

Family frag5 = new Family();
Bundle args = new Bundle();
args.putString("text", entireFiled);
frag5 .setArguments(args);

获取 Family Fragment OnCreateView 方法中的值

TextView output1= (TextView) findViewById(R.id.fp);  
String text =  getArguments().getString("text", "");
output1.setText(text);