Android 在活动的片段中查找按钮
好吧,我觉得这个问题应该在某个地方得到答案,但是我找到的所有答案都不能解决我的问题 我从eclipse菜单创建了一个新的android活动,它添加了一个使用片段xml布局的新活动。xml中有一个EditText和一个按钮,单击按钮时,我想对EditText中的字符串执行以下操作:Android 在活动的片段中查找按钮,android,android-fragments,Android,Android Fragments,好吧,我觉得这个问题应该在某个地方得到答案,但是我找到的所有答案都不能解决我的问题 我从eclipse菜单创建了一个新的android活动,它添加了一个使用片段xml布局的新活动。xml中有一个EditText和一个按钮,单击按钮时,我想对EditText中的字符串执行以下操作: Button b = (Button)findViewById(R.id.syncButton)); b.setOnClickListener(new OnClickListener() {
Button b = (Button)findViewById(R.id.syncButton));
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
EditText e = (EditText)(findViewById(R.id.syncCode));
Log.d("You entered", e.getText().toString());
}
});
如果我将代码放在onCreate中,我会得到一个NullpointerException,因为视图尚未创建。我见过使用ActivityCreated方法的解决方案,但由于我使用的是类Activity的对象,因此不存在这样的方法。在生命周期中,我可以将代码放在哪里,以确保视图已膨胀?将其放在片段中:
private Button mButton;
private EditText mEditText;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mButton = (Button) findViewById(R.id.sync_button));
mEditText = (EditText) findViewById(R.id.sync_code);
mButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "You entered: " + mEditText.getText());
}
});
return rootView;
}
我相信响应包含活动的事件会减少片段的重用,如果可能的话,您应该使片段尽可能原子化和自包含,这样您就可以在多个活动中使用它们 无论如何,请使用onCreateView事件。大概是这样的:
rootView = inflater.inflate(R.layout.fragment_sms, container, false);
txtBody = (TextView) rootView.findViewById(R.id.txtContrl);
您还可以使用片段的.isAdded方法,确保在访问其子级之前已将添加到活动中。但是,如果可能的话,再次尝试将逻辑封装在片段内部。getView.findViewById不起作用吗?或者内部onCreateView使用此视图=充气机.充气机.layout.details,容器,false;返回视图;然后使用view.findViewById?等等,我很困惑,你是想从你的片段中获取字符串还是从你的活动片段中获取字符串?你的片段应该处理它自己的UI和相关的小部件,如按钮。如果您需要活动在单击按钮时执行某些操作,那么您应该通过活动实现的接口使用回调方法;据我所知,您正试图从活动中管理片段内部,即使它应该管理自己。您的代码应该放在片段的onCreateView方法中,如有必要,它应该按照@Squonk描述的方式与活动进行通信。