如何在片段中设置文本?

时间:2014-02-08 18:01:11

标签: android android-fragments android-xml

我正在尝试将我的应用转换为片段与活动,以便更好地使用导航抽屉跟随Android设计指南。

我有一个带按钮的片段,按下时会执行此代码以启动新片段:

FragmentManager man=getFragmentManager();
        FragmentTransaction tran=man.beginTransaction();
        Fragment_one=new Fragment1();
        tran.add(R.id.main, Fragment_one);//tran.
        tran.addToBackStack(null);
        tran.commit();

它尝试加载的片段是:

public class BPTopBeers extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);

        String title = "Top Beers on Beer Portfolio";
        TextView topTitle = (TextView) findViewById(R.id.topTasteTitle);
        topTitle.setText(title);



        //construct url
        String url = "myURL";

        Log.d("myUrl", url);

        //async task goes here
        new GetYourTopTasteBeers(this).execute(url);

        // Inflate the layout for this fragment
        //todo: change to discover layout
        return inflater.inflate(R.layout.toptaste_layout, container, false);

    }



}

我在上面的代码中遇到错误:

TextView topTitle = (TextView) findViewById(R.id.topTasteTitle);

无法解析方法findviewbyid是错误

2 个答案:

答案 0 :(得分:3)

试试这个,你需要获得root视图并使用root视图使用findViewById。

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.toptaste_layout, container, false);

    // rest of the code
    TextView topTitle = (TextView) v.findViewById(R.id.topTasteTitle);

    return v;

}

答案 1 :(得分:0)

将onCreateView()更改为此 -

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
        View view = inflater.inflate(R.layout.toptaste_layout, container, false);
        SharedPreferences prefs =    PreferenceManager.getDefaultSharedPreferences(getActivity());
        String userName = prefs.getString("userName", null);
        String userID = prefs.getString("userID", null);

        String title = "Top Beers on Beer Portfolio";
        TextView topTitle = (TextView) view.findViewById(R.id.topTasteTitle);
        topTitle.setText(title);



        //construct url
        String url = "myURL";

        Log.d("myUrl", url);

        //async task goes here
        new GetYourTopTasteBeers(this).execute(url);

        // Inflate the layout for this fragment
        //todo: change to discover layout
        return view;

    }