片段中的Android setText不起作用

时间:2014-12-23 08:04:15

标签: android android-fragments

在这个示例代码中,我希望通过setText自定义消息,但这不起作用。

public class newCustomers extends Fragment {
    public newCustomers () {
    }
    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate ( R.layout.fragment_new_customers, container, false );
        final Date date = new Date();
        DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd");
        String currentDate = dateFormat.format ( date );
        String cDate1 = JalaliCalendar.g2j ( currentDate );

        View view = inflater.inflate(R.layout.fragment_new_customers, container, false);
        EditText name = (EditText) view.findViewById ( R.id.name );

        String string="this is a text";
        name.setText ( string );
        return rootView;
    }
    @Override
    public void onResume () {
        super.onResume ();
    }
}

我想知道为什么那些不能正常工作。所有演员和我的代码都是正确的

2 个答案:

答案 0 :(得分:1)

从代码中删除此行:

View view = inflater.inflate(R.layout.fragment_new_customers, container, false);

并在您的代码中进行此修改:

EditText name = (EditText) rootView.findViewById ( R.id.name );

答案 1 :(得分:0)

onCreateView方法的返回值更改为view而不是rootView

name.setText ( string );
return view;

因为您从EditText而不是view访问rootView