0

尽管我在项目中使用了 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 时遇到的主要问题——由于某种原因,我无法更新膨胀的视图。为什么?

4

1 回答 1

3

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

这是不正确的。LayoutInflater用于从提供的 xml 布局文件膨胀(构建)视图层次结构。使用您的第二个代码片段,您从布局文件(R.layout.main)构建视图层次结构,TextView从该膨胀视图中找到并在其上设置文本。问题是这个膨胀的视图没有附加到Activity. 您可以看到更改,例如,如果您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);
于 2012-11-25T09:48:38.970 回答