![](/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.