[英]Force Close in the android app
嗨,大家好。
我想為Android制作一個簡單的應用程序,該應用程序將<< OnCheckedChangeListener >>用作android studio中的復選框。 我查看了與我的示例鏈接類似的問題,但在代碼中沒有發現任何問題。 這些是我的。 非常感謝。
這是我的MainActivity.java
package com.example.gna.myapplication;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class MainActivity extends Activity {
public CheckBox chbox=(CheckBox)findViewById(R.id.CH1);
public TextView txt1 =(TextView)findViewById(R.id.TXT1);
CompoundButton.OnCheckedChangeListener list=new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
txt1.setText("A New Era");
else
txt1.setText("MasterByte");
}
};
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
chbox.setOnCheckedChangeListener(list);
}
}
XML是:
activity_main.Xml,
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res /android" xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:id="@+id/rl">
<TextView android:text="MasterByte"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="40dp"
android:textColor="#F00FF0"
android:id="@+id/TXT1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="74dp" />
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Here"
android:id="@+id/CH1"
android:textSize="30dp"
android:layout_below="@+id/TXT1"
android:layout_alignRight="@+id/TXT1"
android:layout_alignEnd="@+id/TXT1"
android:layout_marginTop="55dp" />
</RelativeLayout>
好的。 我的問題是該應用程序無法啟動,並且顯示強制關閉錯誤。 我想使用異常類和[try(),catch(),finally()],但我不知道如何。 如果您知道該怎么做,那么我在等待:D對不起,我的英語不好!
移動初始化
public CheckBox chbox=(CheckBox)findViewById(R.id.CH1);
public TextView txt1 =(TextView)findViewById(R.id.TXT1);
在onCreate
和setContentView
之后。 您需要一個有效的Context
和要查找的內容,然后才能實際找到某些內容
我的問題是該應用程序無法啟動,並且顯示強制關閉錯誤。
您不能在Activity
生命周期結束之前使用findViewById 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.