我不完全理解LayoutInflater功能,虽然我在我的项目中使用它。对于我来说,只是为了找到视图时,我不能叫findViewById法的方式进行。但有时它不会像我所期望的那样工作。什么等同于在Android中使用LayoutInflater的findViewById?
我有这个非常简单的布局(main.xml中)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/layout">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, MyActivity"
android:id="@+id/txt"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change text"
android:id="@+id/btn"/>
</LinearLayout>
我要的很简单 - 只需按下按钮时,将里面的TextView文本。一切正常,像这样
public class MyActivity extends Activity implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
TextView txt = (TextView) findViewById(R.id.txt);
double random = Math.random();
txt.setText(String.valueOf(random));
}
}
但我想知道这将是等效采用LayoutInflater?我试过这个,但没有成功,TextView并没有改变它的值
@Override
public void onClick(View view) {
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View main = inflater.inflate(R.layout.main, null);
TextView txt = (TextView) main.findViewById(R.id.txt);
double random = Math.random();
txt.setText(String.valueOf(random));
}
但是当调试时我可以看到每个变量填充正确的值。我的意思是TXT变量实际上包含TextView的哪个值的“Hello World,MyActivity”,经过的setText方法它包含了一些随机数,但我看不出这种变化对UI。这是我在项目中面对LayoutInflater时遇到的主要问题 - 出于某种原因,我无法更新虚拟视图。为什么?
感谢。是的,我知道我错了,这就是我问这个问题的原因。那么,如果不使用setContentView方法,就不可能使用LayoutInflater更新视图? –
@VitaliiKorsakov是的,这是不可能的。 'LayoutInflater'将使用'inflate'方法创建新的视图,所以你没有“连接”(或者如果你喜欢的话可以引用)到已经存在于'Activity'布局中的旧视图。 – Luksprog