我正在使用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;
}
}
activity_main.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>
答案 0 :(得分:1)
xml文件中的用户选择器:
<强> button_selector.xml 强>
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/btn_hover" android:state_pressed="true"></item>
<item android:drawable="@drawable/btn_hover" android:state_focused="true"></item>
<item android:drawable="@drawable/btn" android:state_enabled="true" android:state_focused="false" android:state_pressed="false"></item>
<item android:drawable="@drawable/btn_hover" android:state_enabled="false"></item>
</selector>
layout.xml
<Button
android:id="@+id/btnOk"
android:background="@drawable/button_selector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_margin="5dp"
android:text="@string/yes" />