简体   繁体   中英

Android: My app won't run if I put Switch OnClickListener on a FragmentActivity

I'm a beginner at Android programming. Please help me with this issue.

Activity_main.xml

 <Button
     android:id="@+id/button1"
     android:layout_width="70dp"
     android:layout_height="20dp"
     android:layout_alignLeft="@+id/textView4"
     android:layout_below="@+id/imageView2"
     android:background="#2c3e50"
     android:enabled="false"
     android:minHeight="15dip"
     android:padding="3dp"
     android:text="Read More..."
     android:textColor="#fff"
     android:textColorHint="#fff"
     android:textSize="9sp" />

MainActivity.java

public class MainActivity extends FragmentActivity {
Button switchButton1 = (Button) findViewById(R.id.button1);
switchButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,Caraga_Agusan_del_norte.class);
            startActivity(intent);
        }
    });
}

This code won't run.

Try this way

 @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);

    Button switchButton1 = (Button) findViewById(R.id.button1);
    switchButton1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this,Caraga_Agusan_del_norte.class);
        startActivity(intent);
     }
  });
}

you have to run

Button switchButton1 = (Button) findViewById(R.id.button1);
switchButton1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this,Caraga_Agusan_del_norte.class);
            startActivity(intent);

        }
    });

after you have called setContentView , and the button has to be declared inside the xml you provide as parameter to setContentView

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM