2

我有一个 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 在当前界面中显示?

4

2 回答 2

1

如果您不想在所有布局中添加包含标签,

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

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);
    }

}
于 2012-11-15T09:16:54.433 回答
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>
于 2012-11-15T08:50:48.130 回答