Android按钮单击不会在片段中注册

时间:2016-07-24 03:19:01

标签: java android

public class HeadlinesFragment extends Fragment implements View.OnClickListener{
View view;
Button button;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    view = inflater.inflate(R.layout.headlines_view, container, false);
    button = (Button)view.findViewById(R.id.button);
    button.setOnClickListener(this);
    return view;
}

@Override
public void onClick(View v){
    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    Fragment fragment2 = new ArticleFragment();
    fragmentTransaction.replace(R.id.fragment_container, fragment2);
    fragmentTransaction.addToBackStack(null);
    fragmentTransaction.commit();
}

单击按钮时onClick方法无法运行,我似乎无法弄明白。

1 个答案:

答案 0 :(得分:0)

@Override
public void onClick(View v){
if (if (R.id.R.id.button== v.getId()) {
 //....


}            
}

//必须使用接口

将以下代码添加到活动中
FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        Fragment fragment2 = new ArticleFragment();
        fragmentTransaction.replace(R.id.fragment_container, fragment2);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();

如果你知道怎么做,我可以在聊天时给你看。