我有一个简单 Activity 的代码,一旦用户单击主页按钮即可返回主 Activity 。
@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();
}
});
}
这是一个用于单个 Activity “greetings”的 java 文件。我想要这个主页按钮+用于许多其他 Activity 的功能,但我不想复制和粘贴。我应该创建另一个java类,并实现其中的函数吗?我试过了,但找不到viewbyid。
最佳答案
没有你的代码真的很难理解为什么你不能通过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"/>
关于java - 如何实现 java 方法以将 Activity 返回到 mainActivity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44104351/