Tuan Dinh
Tuan Dinh

Reputation: 11

Button on FragmentActivity not working

Today I try create a project with fragment activity. I have a MainActivity extent FragmentActivity. MainActvity has layout.

activity_main.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button1" />

    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="2dip"
        android:background="#000" />

    <FrameLayout
        android:id="@+id/frame_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </FrameLayout>

</LinearLayout>

Layout have 2 buttons, and a FrameLayout for replace Fragment in here. In MainActivity onCreate I insert a fragment.

MainAcivity.java

public class MainActivity extends FragmentActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        ((Button) findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Log.e("Button", "click--------------");
            }
        );
        getSupportFragmentManager().beginTransaction().replace(R.id.frame_layout, fragment).addToBackStack(null).commit();
    }
}

When I insert a fragment into R.id.frame_layout then I try touch button1 but it not response. I can't see it in logcat

Please help me! Thanks

Upvotes: 1

Views: 1224

Answers (2)

mmoghrabi
mmoghrabi

Reputation: 1291

in fragments use this :

your XML :

  <Button
            android:id="@+id/btnLogin"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:onClick="yourmethod"
            android:text="Login" />

your code :

  public void yourmethod(View v){
    //dosomthing 
 }

Upvotes: 1

Basim Sherif
Basim Sherif

Reputation: 5440

Change your code to,

    Button btn = (Button) getActivity().findViewById(
                R.id.button1);

btn.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                      Log.e("Button", "click--------------");

            }
        });

Upvotes: 0

Related Questions