是否可以在Activity和Fragment中实现单独的按钮onclickListener?

时间:2017-10-21 07:57:34

标签: android android-fragments

我的MainActivity包含用于切换到不同片段的按钮。每个片段里面都有按钮。在片段中实现按钮onClickListener之前,onClickListener上的Activity按钮工作正常。我想知道这是不是Android不支持我的代码是不正确的。 任何指针都很受欢迎。谢谢。

片段代码:

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

    super.onCreate(savedInstanceState);
    v = inflater.inflate(fragment1, container, false);

    b2=(Button)v.findViewById(R.id.button2);
    b2.setOnClickListener(new View.OnClickListener()
    {
        public void onClick(View v){
            button2Clicked(v);
        }
    });
    return inflater.inflate(R.layout.fragment1, container, false);
 }
public void button2Clicked(View view){
   //do something
 }

活动代码:

public class MainActivity extends FragmentActivity {

private Button btnHealth;
private Button btnSetting;
private Button btnSleep;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //Init component
    btnHealth = (Button) findViewById(R.id.btnHealth);
    btnSleep = (Button) findViewById(R.id.btnSleep);
    btnSetting = (Button) findViewById(R.id.btnSetting);

    replaceFragment(1);

    btnHealth.setOnClickListener(new AdapterView.OnClickListener(){
        @Override
        //On click function
        public void onClick(View view) {
            replaceFragment(0);
        }
    });

    btnSleep.setOnClickListener(new AdapterView.OnClickListener(){
        @Override
        //On click function
        public void onClick(View view) {
            replaceFragment(1);
        }
    });

    btnSetting.setOnClickListener(new AdapterView.OnClickListener(){
        @Override
        //On click function
        public void onClick(View view) {
            replaceFragment(2);
        }
    });

}


//Create method replace fragment

private void replaceFragment(int pos) {
    Fragment fragment = null;
    switch (pos) {
        case 0:
            fragment = new Fragment1();
            break;
        case 1:
            fragment = new Fragment2();
            break;
        case 2:
            fragment = new Fragment3();
            break;
        default:
            fragment = new Fragment2();
            break;
    }

    if(null!=fragment) {
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.replace(R.id.main_content, fragment);
        transaction.addToBackStack(null);
        transaction.commit();
    }
}


}

1 个答案:

答案 0 :(得分:0)

有可能。如果要在Activity类中处理片段的OnClick事件,可以使用FragmentInteractionListener(接口)来完成。示例:Android - handle fragment onClick from activity