如何将按钮连接到Android Studio的主要活动?
问题描述:
我认为我的问题很简单,但我不知道如何解决它。如何将按钮连接到Android Studio的主要活动?
我为这个类做了一个java类(test_class)和xml
文件。在xml
文件中,我在test_class中正确地创建了一个按钮和它的工作,但我必须在MainActivity
中使用它。 我做了这个按钮公开并成为这个类的对象,但按钮为空。我也试图让按钮从主要活动
Button btn = (Button) findViewById(R.id.logButton)
但它也为空。
我该如何解决这个问题?
在此先感谢!
答
试试这个
Main_activity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button= (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "This is my Toast message!",
Toast.LENGTH_LONG).show();
}
});
}
}
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<TextView android:text="Hello World!" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
- 清洁工程
- 编译和运行。
发布您的代码在这里先 –
的观点并没有在积极布局发现或没有布局集('setContentView') – Zoe
而不是让一个新的Java类,去活动,并选择清空活动 – CharlieNorris