Android:如果我将Switch OnClickListener放在FragmentActivity上,我的应用程序将无法运行

时间:2014-11-20 10:23:28

标签: java android eclipse button android-fragmentactivity

我是Android编程的初学者。请帮我解决这个问题。

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);
        }
    });
}

此代码无法运行。

2 个答案:

答案 0 :(得分:3)

试试这种方式

 @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);
     }
  });
}

答案 1 :(得分:0)

你必须运行

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);

        }
    });

调用setContentView之后,必须在xml中将此按钮声明为setContentView

的参数