关于LayoutInflater和inflate

时间:2012-11-15 08:48:00

标签: android

我有一个TextView组件。我想在每个Activity中显示TextView,并且不想在每个布局中编写此组件。

public class Test extends Activity {
     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.alarm);

        LayoutInflater flater = LayoutInflater.from(this);
         View view = flater.inflate(R.layout.toolbar_clearbalk, null);
         TextView text=(TextView)view.findViewById(R.id.now_time);

     }

now_time是我找到的组件。我怎么能让TextView在当前界面中显示?

2 个答案:

答案 0 :(得分:1)

您可以将此布局包含在<include>元素的任何其他布局文件中:

<?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:layout_width="match_parent"
    android:layout_height="match_parent" >

    <include layout="@layout/toolbar_clearbalk" />

    ...


</LinearLayout>

答案 1 :(得分:1)

如果您不想将include标记添加到所有布局中,

您可以使用抽象基类,然后从抽象类扩展您的所有新类

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

abstract class BaseActivity extends Activity {

    public View view;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        LayoutInflater flater = LayoutInflater.from(this);        
        view = flater.inflate(R.layout.toolbar_clearbalk, null);
        TextView text=(TextView)view.findViewById(R.id.now_time);
        text.setText("bla bla bla");        

    }   

}


import android.os.Bundle;
import android.widget.RelativeLayout;

    public class MainActivity1 extends BaseActivity 
{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout parent = (RelativeLayout) findViewById(R.id.container);
        parent.addView(view);
    }

}



import android.os.Bundle;
import android.widget.RelativeLayout;

public class MainActivity2 extends BaseActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout parent = (RelativeLayout) findViewById(R.id.container);
        parent.addView(view);
    }

}


import android.os.Bundle;
import android.widget.RelativeLayout;

public class MainActivity3 extends BaseActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout parent = (RelativeLayout) findViewById(R.id.container);
        parent.addView(view);
    }

}