Android-Eclipse忽略Java代码,仅从XML文件运行
我不熟悉Eclipse中的Android开发,出于某种原因,在尝试运行Java代码时,Eclipse忽略了它,只运行XML代码 以下是我迄今为止的Java代码:Android-Eclipse忽略Java代码,仅从XML文件运行,java,android,xml,Java,Android,Xml,我不熟悉Eclipse中的Android开发,出于某种原因,在尝试运行Java代码时,Eclipse忽略了它,只运行XML代码 以下是我迄今为止的Java代码: package com.example.boat; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.view.View; import android.widget.LinearLayout;
package com.example.boat;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView mainView = new ScrollView(this);
LinearLayout mainLayout = new LinearLayout(this);
LinearLayout results = new LinearLayout(this);
mainView.addView(mainLayout);
mainLayout.addView(results);
results.setVisibility(View.GONE);
TextView mhs = new TextView(this);
mhs.setText("Maximum hull speed:");
mainLayout.addView(mhs);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
以下是我的XML代码:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.boat"
android:versionCode="1"
android:versionName="1.0" android:installLocation="auto">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="18" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.ser421assignment4.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>
有人知道这里出了什么问题吗?我更喜欢使用Java,而不是XML。我不确定您认为什么东西没有运行,但这里唯一会发生的事情是,您的
活动\u main.XML
会因为这一行而膨胀
setContentView(R.layout.activity_main);
在此之前的所有Java代码只是创建视图
s,而不是使用setContentView()
添加到膨胀的视图
。调用setContentView()
后,将显示该内容。如果要在此版面上设置这些视图
,则需要在调用setContentView()
后进行设置,并且必须将它们添加到该版面
…而不仅仅是彼此
然而,在这种情况下,我认为没有必要动态地创建它们。只需将它们添加到您的活动\u main.xml
中,并将它们从onCreate()
中删除,这两个代码是完全不相关的。忽略它是什么意思?我的意思是,当我构建和运行我的项目时,我没有在Java代码中看到我的TextView,我注意到如果您在尝试运行应用程序时在Eclipse编辑器中显示XML页面,它会尝试运行XML页面而不是应用程序。确保java代码显示在窗口中。XML不是代码,它只是数据,你不能“运行”XML,就像我不能运行PDF一样。谢谢,这很有效。我只是用setContentView(mainView)