访问已更改片段中的视图

时间:2014-04-26 18:41:34

标签: android

我有一个活动包含一个片段,我称之为fragment1。我可以通过findViewById访问此片段的视图,并为其定义setOnClickListeneronClick方法。

完美无缺。现在我使用片段事务将fragment1更改为fragment2。我可以使用fragment2findViewById中定义视图,但是当我为它们定义setOnClickListeneronClick方法时,应用程序崩溃。 我该怎么办?

ActivityMain onCreate:

public class MainActivity extends Activity {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main); 

/**button change fragment**/
 Button change = (Button) findViewById(R.id.change);
    change.setOnClickListener(new OnClickListener() {
        @Override

        public void onClick(View v)
        {
           FragmentManager fragmentManager = getFragmentManager();
           FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
           final Fragment2 Fr2 = new Fragment2 (); 
           fragmentTransaction.replace(R.id.Fragment1,  Fr2);
           fragmentTransaction.addToBackStack(null);
           fragmentTransaction.commit();
            }
        });

/*** This button belongs to fragment1, and it works.**/
 Button Login = (Button) findViewById(R.id.SignInBtn);
    Login.setOnClickListener(new OnClickListener() {
        @Override

        public void onClick(View v)
        {
                  ....
            }
        });

/*** This button belongs to fragment2, and it's not working.**/

 Button Signup = (Button) findViewById(R.id.SignUpBtn);
    Signup .setOnClickListener(new OnClickListener() {
        @Override

        public void onClick(View v)
        {
                  ....
            }
        });

}

Fragment2 onCreateView:

public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    return inflater.inflate(R.layout.sign_up_form1_fragment,  container, false);
}

Fragment1 onCreateView:

public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    return inflater.inflate(R.layout.down_right_fragment,  container, false);
}

1 个答案:

答案 0 :(得分:1)

这不是你在片段上设置按钮onclicklistener的方法..你应该从每个片段上的oncreateView里面的inflater获取视图,然后从那里使用视图并使用View获取里面的按钮.. < / p>

示例:

    public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View view = inflater.inflate(R.layout.down_right_fragment,  container, false);



    Button Signup = (Button) view.findViewById(R.id.SignUpBtn);
    Signup .setOnClickListener(new OnClickListener() {
        @Override

        public void onClick(View v)
        {
                  ....
            }
        });
    return view;
}

与第一个片段

相同