如何正确更改Fragments中的元素

时间:2015-01-30 18:23:13

标签: java android android-fragments wear-os layout-inflater

我的应用程序中有两个页面(片段),每个页面都有自己的交互。长按任一页面都应该将颜色方案切换为黑白,然后再返回。这是使用从任一页面调用的单独java类来完成的。从第二页运行时,这非常有效,但从第一页开始运行时,第二页不会更改。这是我的一些代码,简化了长度:

第1页:

    firstView = inflater.inflate(R.layout.page1, container, false);
    secondView = inflater.inflate(R.layout.page2, container);

//A bunch of code and then....

    element1.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            pm = sharedPreferences.getBoolean("pm", false);
            if (pm) {
                performance.PerfModeOff();
                pm = false;
                sharedPreferences.edit().putBoolean("pm", pm).apply();
            } else {
                performance.PerfModeOn(mContext);
                pm = true;
                sharedPreferences.edit().putBoolean("pm", pm).apply();
            }
            return true;
        }
    });

第2页:

        secondView= inflater.inflate(R.layout.page2, container, false);
    firstView = inflater.inflate(R.layout.page1, container);

//A bunch of code and then...

element2.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View view) {
            pm = sharedPreferences.getBoolean("pm", false);
            if (pm) {
                performance.PerfModeOff();
                pm = false;
                sharedPreferences.edit().putBoolean("pm", pm).apply();
            } else {
                performance.PerfModeOn(mContext);
                pm = true;
                sharedPreferences.edit().putBoolean("pm", pm).apply();
            }
            return true;
        }
    });

改变颜色的课程:

public Performance(View firstView, View secondView,LayoutInflater inflater, ViewGroup container) {
    mfirstView = inflater.inflate(R.layout.page1, container,false);
    msecondView = inflater.inflate(R.layout.page2, container,true);

    uparrow= (ImageView) firstView.findViewById(R.id.UpArrow);
//**A lot of lines like above 

    public void PerfModeOn(Context context) {

mfirstView.setBackgroundColor(Color.BLACK);
msecondView.setBackgroundColor(Color.BLACK);

uparrow.setBackgroundTintList(ColorStateList.valueOf(context.getResources().getColor(R.color.DarkTint)));

//** More lines to change colors

public void PerfModeOff() {
//**Lines to change colors back

当然,如果您需要查看更多代码,请告诉我们。我该怎么做才能解决这个问题?谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

您的第二个视图永远不会更改,因为PerfModeOn()天真地调用mfirstView.setBackgroundColor(Color.BLACK);。您需要传递哪个视图来设置背景,因此它设置了正确的背景。

换句话说,您的第一个视图将只会更改视图,因为您在设置背景时有多明确。

另一种选择是:

public void perfModeOn(Context context, View viewToSetBackgroundOf) {
    viewToSetBackgroundOf.setBackgroundColor(Color.BLACK);
    ...
}

更好的方法是实现两个视图都使用的OnLongClickListener。然后,您可以在onLongClick()方法中点击哪个视图。然后是一个简单的if语句,单击哪个视图,并设置相反视图的背景。这将消除您的冗余代码和一些不需要的方法。