gpt4 book ai didi

java - Android Activity 变黑然后崩溃

转载 作者:行者123 更新时间:2023-12-02 06:00:03 25 4
gpt4 key购买 nike

我最近开始开发应用程序,并且得到了我的第一份工作。这是一个简单的应用程序,带有 Logo 和链接到网站的按钮。每次我运行它时,它都会崩溃,我很困惑为什么,因为它是如此简单的程序。我花了很多时间在SO上寻找类似的问题,但无济于事。我还浏览了 eclipse 并消除了任何编译器警告。有谁知道可能出了什么问题吗?

错误消息:

我不断地把事情删减到应用程序最简单的功能上。它仍然行不通。这是我的 .java 和主要 Activity 。 (这是一个单一 Activity 和一类应用程序)

//necessary imports are omitted.  I get no errors for imports

public class FullscreenActivity extends Activity {

Button button = (Button) findViewById(R.id.button1);

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
goToUrl("http://switchemup.com");
}
});

}

private void goToUrl(String url) {
Uri uriUrl = Uri.parse(url);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(launchBrowser);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.fullscreen, menu);
return true;
}
}
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".FullscreenActivity" >

<ImageView
android:id="@+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_centerHorizontal="true"
android:src="@drawable/switchuplogo" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="94dp"
android:text="View Website" />

</RelativeLayout>

最佳答案

此行 Button button = (Button) findViewById(R.id.button1); 应该会创建一个错误,这应该会导致您的应用程序崩溃。您设置一个变量,其中包含应位于 onCreate 方法中的方法。

试试这个:

// init your variable only
Button button;

// Then in onCreate, as you already did:
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// set findViewById method only here
button = (Button) findViewById(R.id.button1);
// ...
}

请告诉我这是否有帮助。

关于java - Android Activity 变黑然后崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22751663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com