在一个片段上使用listview选择的项目来显示其他片段上的文本

时间:2015-12-30 11:02:02

标签: android listview android-fragments android-listview

我有两个片段,一个带有listview,另一个带有textview,我想在选择一个项目时,它的文本用于在另一个片段的textview上设置文本并显示另一个片段。

所以我在listview(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行得到null异常。那怎么办呢?谢谢

2 个答案:

答案 0 :(得分:1)

您需要使用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);

答案 1 :(得分:0)

您无法访问其他片段textview。要将一个片段传递给另一个片段,请尝试使用Handler

或者在您的情况下,您可以尝试使用共享首选项。在按钮单击时保存第一个片段中的数据。当家庭片段刚刚从共享偏好中检索数据并在家庭片段的文本视图中显示它时。

相关问题