![](/img/trans.png)
[英]Java and programming newbie. What am I doing wrong? (Method, Parameters)
[英]Android: i am a newbie. I declared a button in java file but i didnt see it in xml-file and on an emulator
我尝试运行《 Beginning Android Games》一书中的第一个示例(作者:Mario Zechner,Apress.com):我将此代码复制到了我的项目(MainActivity.java文件)中:
HelloWorldActivity.java
package com.helloworld;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener {
Button button;
int touchCount;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
button = new Button(this);
button.setText( "Touch me!" );
button.setOnClickListener(this);
setContentView(button);
}
public void onClick(View v) {
touchCount++;
button.setText("Touched me " + touchCount + " time(s)");
}
}
但是当我运行了这个简单的应用程序时,我没有在模拟器上看到任何按钮(我只看到了“ Android”标签。我尝试了“ project-> clean ..”:没有结果。(和“ project- ->自动构建(。),我需要在哪里声明和描述此按钮?但是,我遵循了本书中描述的所有步骤,最后,我从布局文件夹中删除了xml文件。
谢谢。 _ __ _ __ _ __ _ __ _ __ _ _ 编辑:添加了xml文件 _ __ _ __ _ ____
res->布局-> 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"
tools:context=".MainActivity" >
</RelativeLayout>
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.firstbuttontest2"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="4"
android:targetSdkVersion="11" />
<application
android:allowBackup="true"
android:debuggable="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.firstbuttontest2.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
试试这个可能对您有帮助。
将按钮添加到特定的布局。 像这样
LinearLayout linearLayout=(LinearLayout)findViewById(R.id.linearLayout);
linearLayout.addView(button);
我知道有一个addContentView方法,它可能比setContentView要多。
尝试
setContentView(R.layout.activity_main)
然后
button = (Button) findviewbyid(R.id.Button1);
这可以解决您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.