单击“按钮”并更改另一个按钮的背景颜色

时间:2015-12-24 21:13:55

标签: java android class button android-studio

我在Android Studio中制作应用。在我的一个活动中,有一堆按钮,当你点击一个按钮时,会出现一个PopupWindow类,它上面有4个不同颜色的按钮。

我遇到的问题:一旦PopupWindow出现,我希望用户选择4个按钮中的一个,并根据他们选择的一种颜色,首次点击活动的原始按钮将改变其背景颜色到弹出窗口中选择的那个。

POP UP CODE:

Observable.timer(long, TimeUnit)

主要活动代码:

public class Pop extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.popupwindow);

    DisplayMetrics dm = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(dm);

    int width = dm.widthPixels;
    int height = dm.heightPixels;

    getWindow().setLayout((int)(width*.7), (int)(height*.7));

   final Button color1Button = (Button) findViewById(R.id.redbutton);
    color1Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果我理解你的目标,一种可能的方法是使用SharedPreferences和Extras。

共享首选项文件是本地存储在设备文件系统中的文件。它允许您将信息存储为键值对,即使退出应用程序,信息仍保留在那里。它主要用于存储特定于应用程序的设置。这样,您可以永久保存用户选择的每个按钮的颜色。

额外用于在使用Intent从另一个人启动Activity时在Activites之间传输信息。

您需要将此添加到MainActivity onCreate()

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences sharedPref = getSharedPreferences(
                "MY_PREFS", Context.MODE_PRIVATE);

        ...
}

按钮初始化和处理按键的代码(例如button2):

//-1 is a default value in case no color was selected yet for the particular button
int button2Color = sharedPref.getInt("button2Color", -1);
Button button2 = (Button) findViewById(R.id.button2);
if (button2Color != -1) {
      button2.setBackgroundColor(button2Color);
}
button2.setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
           Intent i = new Intent(LambertsLaneSection1Activity.this, Pop.class);
           //2 here identifies your button, because it is button2
           i.putExtra("buttonPressed",2)
           startActivity(i);
     }
});

在您的PopUp中:

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.popupwindow);

    //here you get which button was pressed as an Extra
    int buttonPressed = getIntent().getExtras().getInt("buttonPressed");
    SharedPreferences sharedPref = getSharedPreferences(
                "MY_PREFS", Context.MODE_PRIVATE);
    ...

    final Button color1Button = (Button) findViewById(R.id.redbutton);
    color1Button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             sharedPref.edit().putInt("button"+buttonPressed+"Color", Color.RED).apply();
        }
    }
}