android:如何在单击按钮时更改布局? [英] android: how to change layout on button click?
本文介绍了android:如何在单击按钮时更改布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须按照代码点击按钮选择布局.
I have to following code for selecting layout on button click.
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
switch (v.getId()) {
case R.id.DownloadView:
// doStuff
setContentView(R.layout.main);
break;
case R.id.AppView:
// doStuff
setContentView(R.layout.app);
break;
}
}
};
findViewById(R.id.DownloadView).setOnClickListener(handler);
findViewById(R.id.AppView).setOnClickListener(handler);
当我点击AppView"按钮时,布局会发生变化,但是当我点击DownloadView"按钮时,没有任何反应.
When I click the "AppView" button, the layout changes, but when I click the "DownloadView "button, nothing happens.
此链接 表示我必须开始一项新活动.
This link says that I have to start a new activity.
但是我不知道如何使用那里的代码来启动新的活动,是否会添加一个新文件?
But I don't know how to use the code there of intent to start new activity, will a new file be added?
我有关于新活动的代码:
package com.example.engagiasync;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class AppView extends Activity implements OnClickListener{
@Override
public void onCreate(Bundle savedInstanceState){
setContentView(R.layout.app);
TextView tv = (TextView) this.findViewById(R.id.thetext);
tv.setText("App View yo!?
");
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
但它不起作用,它强制关闭,logcat 说:
推荐答案
Button btnDownload = (Button) findViewById(R.id.DownloadView);
Button btnApp = (Button) findViewById(R.id.AppView);
btnDownload.setOnClickListener(handler);
btnApp.setOnClickListener(handler);
View.OnClickListener handler = new View.OnClickListener(){
public void onClick(View v) {
if(v==btnDownload){
// doStuff
Intent intentMain = new Intent(CurrentActivity.this ,
SecondActivity.class);
CurrentActivity.this.startActivity(intentMain);
Log.i("Content "," Main layout ");
}
if(v==btnApp){
// doStuff
Intent intentApp = new Intent(CurrentActivity.this,
ThirdActivity.class);
CurrentActivity.this.startActivity(intentApp);
Log.i("Content "," App layout ");
}
}
};
注意:然后你应该像这样在清单 .xml 文件中声明你的所有活动:
Note : and then you should declare all your activities in the manifest .xml file like this :
<activity android:name=".SecondActivity" ></activity>
<activity android:name=".ThirdActivity" ></activity>
EDIT : 更新这部分代码 :) :
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);// Add THIS LINE
setContentView(R.layout.app);
TextView tv = (TextView) this.findViewById(R.id.thetext);
tv.setText("App View yo!?
");
}
注意:检查这个(断开的链接)关于如何在活动之间切换的教程.
这篇关于android:如何在单击按钮时更改布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文