我正在学习在Android工作室中用java编写一个界面但由于某种原因,我的应用程序总是说"不幸的是myApp已经停止工作"或类似的东西
这就是我所拥有的:
package com.name.javainterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout myLayout = new RelativeLayout(this);
Button redButton = new Button(this);
myLayout.addView(redButton);
setContentView(R.layout.myLayout);
setContentView(R.layout.activity_main);
/*Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
为什么我的布局导致我的应用停止运行? 当我插入手机并运行应用程序时,它不会播放并说“错误:无法找到符号变量myLayout"这没有任何意义,因为我在调用它之前做了布局,所以为什么它不知道myLayout是什么?
答案 0 :(得分:0)
不要以编程方式添加默认视图,如button,textview,edittext等,直到需要它为止。您还多次声明了setContentView()。 另外,生成错误:“找不到符号变量myLayout”,因为您尚未在布局目录中创建名为“myLayout.xml”的布局文件。这是固定代码:
MainActivity.java:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button redButton=(Button) findViewById(R.id.button_red);
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<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">
<Button
android:id="@+id/button_red"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am red button"/>
</RelativeLayout>
另外,看看你的编程风格,似乎你是android新手。所以请观看这些教程:https://www.youtube.com/watch?v=hzrGAZnMOMQ&list=PL1q3ROAofjeOUwh7lPBnGbg__DUodwLN7