【问题标题】:use listview selected item on one fragment to display text on other fragment在一个片段上使用 listview 选定项目在另一个片段上显示文本
【发布时间】:2015-12-30 11:02:02
【问题描述】:

我有两个碎片一个带有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 行得到空异常。那么我该怎么做呢?谢谢

【问题讨论】:

标签: android listview android-fragments android-listview


【解决方案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);

【讨论】:

    【解决方案2】:

    你不能像那样访问另一个片段文本视图。为了将一个片段与另一个片段通信,请尝试使用Handler

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-09
    • 2019-10-23
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多