我是Android的新手,我使用Flexible Fragment遇到了这个问题。 我有一个名为mainActivity和Fragment的活动,名为RegisteractivityFragment。
我在主要活动中加载片段但是当我点击片段按钮时应用程序关闭。 这是我的registerActivityFragment.java的一些部分
public class RegisterActivityFragment extends Fragment {
public interface OnButtonsClicked {
public void onRegisterClicked();
public void onNextTimeclicked();
}
OnButtonsClicked buttonClickListener ;
//some codes
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception.
try {
buttonClickListener = (OnButtonsClicked) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnButtonsClicked Functions");
}
}
public void clickRegister(View view)
{
buttonClickListener.onRegisterClicked();
}
public void clickNextTime(View view)
{
buttonClickListener.onNextTimeclicked();
}
}
这是我的MainActivity.java
public class MainActivity extends ActionBarActivity implements RegisterActivityFragment.OnButtonsClicked {
RegisterActivityFragment registerFragment= new RegisterActivityFragment();
@Override
public void onCreate(Bundle savedInstanceState){
//adding Fragment to activity
}
//implementing the interface
@Override
public void onRegisterClicked() {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(MainActivity.this,"asd",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
@Override
public void onNextTimeclicked() {
Toast toast = Toast.makeText(MainActivity.this,"asd",Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER,0,0);
toast.show();
}
}
答案 0 :(得分:0)
你必须覆盖RegisterActivityFragment类中的onCreateView方法来设置像这样的onClickListner
private Button foo; // as globle var
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_rssitem_detail,
container, false);
foo = view.findViewByid(R.id.foo); // button id
foo.setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
OnButtonsClicked.onRegisterClicked();
}
});
return view;
}
您的问题是在xml文件中设置属性OnClick =“clickRegister”并在片段中定义方法 实际上你必须在MainActivity中定义它而不是Fragment
所以解决问题的第二种方法是将2方法移动到MainActivity:
public void clickRegister(View view)
{
buttonClickListener.onRegisterClicked();
}
public void clickNextTime(View view)
{
buttonClickListener.onNextTimeclicked();
}
}