我只是想知道如何在我的页面上创建一个按钮,以便它可以转到我的应用程序的另一个页面。我是初学者,所以如果你能解释它是如何工作的,它会在哪里发挥作用,这将有很大的帮助。 PS我正在使用android studio,如果这有所不同,这是我目前在我的fragment_main.xml中的代码。我没有在.java
中输入任何代码
<TextView android:text="@string/hello_world"
android:id="@id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="@+id/firstbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/homebutton"
android:layout_below="@+id/text"/>
答案 0 :(得分:0)
您可以在Java中动态声明视图和对象,然后将按钮从片段传递到片段(或者将Activity传递给Activity,具体取决于您的应用)。
使用按钮声明相对布局,例如:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.RelativeLayout;
public class JavaLayoutActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button myButton = new Button(this);
RelativeLayout myLayout = new RelativeLayout(this);
myLayout.addView(myButton);
setContentView(myLayout);
}
这不会设置属性或任何东西,我只是将其用作概念证明。
XML使用户界面设计变得简单,因为您不必在代码中管理它,但这是一个例外情况。如果需要动态接口对象,则需要使用Java。
答案 1 :(得分:0)
不是动态创建视图,而是应该在活动中获取视图
ImageButton button = (ImageButton) findViewById(R.id.firstButton)
并将onClick侦听器分配给id
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// start new Activity here
}
});
您也可以在xml:
中执行此操作<ImageButton
android:id="@+id/firstbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/homebutton"
android:onClick="sendMessage"
android:layout_below="@+id/text"/>
使用这样的配置,你应该在activity中添加方法:
public void sendMessage(View view) {
// start another activity here
}
答案 2 :(得分:0)
Android中有两种可用的方法,您可以从一个Activity转到另一个Activity。
1。使用button.setOnClickListener()
在xml
文件中创建一个按钮。
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
现在为.class
文件中的按钮设置事件监听器
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//set the event you want to perform when button is clicked
//you can go to another activity in your app by creating Intent
Intent intent = new Intent(getApplicationContext, Activity2.class);
startActivity(intent);
}
});
2。使用<android:onClick="goNext">
将onClick
作为您在xml
文件中创建的按钮的属性。
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="goNext" />
现在,在您的.class
文件中,将该按钮的事件定义为
goNext() {
Intent intent = new Intent(getApplicationContext, Activity2.class);
startActivity(intent);
}