2012-11-25 85 views
0

我不完全理解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时遇到的主要问题 - 出于某种原因,我无法更新虚拟视图。为什么?

回答

3

对我来说,这只是一种查找视图的方法,当我无法调用findViewById 方法时。

这是不正确。所述LayoutInflater被用于膨胀(构建)从所提供的XML布局文件的图的层次结构。有了您的第二代码片段构建从布局文件(R.layout.main)视图层次结构,找到从充气鉴于TextView并设置文本就可以了。问题是这个膨胀的视图没有附加到Activity的Visibile UI。你可以看到的变化,例如,如果您再次调用setContentView这个时候给它充气视图。这会让你的Activity的内容是新充气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)); 
setContentView(main); 
+0

感谢。是的,我知道我错了,这就是我问这个问题的原因。那么,如果不使用setContentView方法,就不可能使用LayoutInflater更新视图? –

+0

@VitaliiKorsakov是的,这是不可能的。 'LayoutInflater'将使用'inflate'方法创建新的视图,所以你没有“连接”(或者如果你喜欢的话可以引用)到已经存在于'Activity'布局中的旧视图。 – Luksprog

相关问题