0

在我的应用程序中,我想在一个独特的位置添加一个按钮,在所有活动中执行相同的功能,因此我没有向所有活动添加相同的代码,而是考虑制作一个基本活动,就是这样。

mport android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;
 public abstract class DefaultActivity extends Activity{

ImageButton b;
@Override
public void onCreate(Bundle bundle)
{
    super.onCreate(bundle);
    setContentView(R.layout.default_activity);
    b = (ImageButton)findViewById(R.id.imageButton1);
    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Toast.makeText(getApplicationContext(), "ana fel base activity", Toast.LENGTH_LONG).show();
        }
    });
}

}

但是尽管我让其他活动扩展了DefaultActivity ,但该按钮并未出现在其他活动中。那么有没有办法做到这一点呢?非常感谢。

PS:我不想使用actionBar。

4

1 回答 1

0

如果您的其他活动setContentView(...)与其他布局一起调用,那么将显示这些布局。如果这些布局没有您的ImageButton,那么您将不会ImageButton在屏幕上显示(布局不会通过调用setContentView()theActivity和它的超类实现来“嵌套”)。一种解决方案是在您的其他布局中使用该<include>标签,并拥有另一个仅包含 ImageButton 的布局文件,如下所示:

res/layout/image_button.xml

<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    ...
/>

资源/布局/activity_main

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

    <!-- more views ... -->

    <include android:layout="@layout/image_button" />
</LinearLayout>
于 2013-04-28T00:41:22.937 回答