我希望在睡眠10秒后更改主要活动的布局。我创建了两个xml文件以及activity_main.xml(linear.xml,relative.xml)。当我第一次按下按钮时调用该方法时,仅显示设置的最后一个布局。我希望显示线性布局(linear.xml),然后在10秒后它应该更改为相对布局(relative.xml)。 我尝试使用数组来存储布局,然后使用变量通过在setContentView()方法中传递变量来切换内容,但这不起作用(两个布局都没有加载)。 您能指定解决方案或实现此目的的方法吗? 谢谢
以下是MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void change(View v)
{
try
{
Thread.sleep(5000);
Toast.makeText(this,"linear layout",Toast.LENGTH_LONG).show();
setContentView(R.layout.linear);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
try
{
Thread.sleep(5000);
Toast.makeText(this,"relativelayout",Toast.LENGTH_LONG).show();
setContentView(R.layout.relative);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
以下是activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.androidcodes.layoutsapp.MainActivity">
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="170dp"
android:text="Button"
android:onClick="change"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
答案 0 :(得分:0)
尝试使用处理程序
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
viewLinear = getLayoutInflater().inflate(R.layout.layout1, null);
viewRelative = getLayoutInflater().inflate(R.layout.layout2, null);
this.handler = new Handler();
this.handler.postDelayed(runnable, 5000);
}//onCreate
private final Runnable runnable = new Runnable() {
public void run() {
setContentView(viewLinear);//update
this.handler.postDelayed(runnable, 5000);
}
};//runnable