我有一个简单活动的代码,一旦用户单击“主页”按钮,便可以返回到主要活动。

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_greetings);

        // Set up onclicklistener for homeIcon imageview to go to back one activity
        ImageView homeIcon = (ImageView) findViewById(R.id.home_icon);

        homeIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }


这是单个活动的Java文件,问候。我需要此主页按钮+用于许多其他活动的功能,但我不想复制和粘贴。我应该制作另一个Java类,并在其中实现函数吗?我试过了,但是找不到viewbybyid。

最佳答案

没有您的代码,很难理解为什么无法通过id查找,但是我可以提供这种方式:

HomeButtonActivity.java

public class HomeButtonActivity extends AppCompatActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        Button home_button = (Button) findViewById(R.id.home_button);
        home_button.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                Toast.makeText(HomeButtonActivity.this, "Replace with your own action", Toast.LENGTH_SHORT).show();
            }
        });
    }
}


Activity1.java

public class Activity1 extends HomeButtonActivity
{
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity1);

        super.onCreate(savedInstanceState);
    }
}


activity1.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.myapplication.HomeButtonActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />
    <include layout="@layout/home_button" />

</android.support.design.widget.CoordinatorLayout>


home_button.xml

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/home_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center"
    android:text="home button"/>

08-20 03:15