我正在使用该setBackgroundDrawable
方法更改 Activity 上按钮的背景。onClickListener 也有一个 Intent 来打开一个新的 Activity。但是,当我通过点击物理后退按钮返回到过去的 Activity 时,分配给它的 onClickListener 按钮仍然设置了 onClick 背景。如果我使用操作栏中的后退按钮返回到上一个活动,它可以正常工作。我尝试使用选择器 XML,但 Android Studio 给了我渲染错误,并且在我编译时它不会加载。
这是 MainActivity.java:
package com.jordandebarth.supercalculator;
import android.app.ActionBar;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class MainActivity extends Activity {
ImageButton pythag;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#33b5e5")));
final ImageButton pythag = (ImageButton) findViewById(R.id.pythag_button);
pythag.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
pythag.setBackgroundResource(R.drawable.pythag_button_selector);
Intent pythagIntent = new Intent(MainActivity.this, PythagoreanActivity.class);
startActivity(pythagIntent);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
活动主.xml:
<RelativeLayout 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"
android:background="#e5e5e5"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ImageButton
android:layout_width="fill_parent"
android:background="@drawable/pythag_button"
android:layout_height="wrap_content"
android:id="@+id/pythag_button"
android:focusable="true"/>
</RelativeLayout>