在Inflate之后无法更改TextView

时间:2016-06-18 19:21:27

标签: android layout-inflater

我正在尝试编辑膨胀的TextView文本视图的文本

    ViewGroup parent = (ViewGroup) findViewById(R.id.activity_1);
    View view = LayoutInflater.from(getApplication()).inflate(R.layout.activity_2, parent, false);
    TextView textView = (TextView) view.findViewById(R.id.textView);
    textView.setText("Hello");

但是,即使在膨胀后textView不为null,任何以编程方式更改它的尝试都会失败。我不能setText或完全影响它。

activity_2.xml:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/listviewlayout"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
    </TextView>

</LinearLayout>

SimpleCursorAdapter会使视图本身膨胀,因此忽略了更改。可以从适配器内部访问视图,而无需通过以下方式扩展视图:

listAdapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

    public boolean setViewValue(View view, Cursor cursor, int column) {

        if (view.getId() == R.id.textView) {
            TextView textView = (TextView) view;
            textView.setText("Hello!");
            # Alternatively get cursor text like so where 2 is the cursor column that has the text:
            # textView.setText(cursor.getString(2));
            return true;
        }
        return false;
    }
});

1 个答案:

答案 0 :(得分:0)

尝试使用父上下文,如下所示:

View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.activity_2, parent, false);