android app变量需要是本地的,但无法访问它

时间:2014-04-24 08:44:51

标签: java android variables global-variables

我有一个非常奇怪的问题,我使用Inflation复制布局x次,我设置了一个值并修改它(递增或递减)现在一切都很好,问题是变量是全局的,当我在递增时现在,每次通货膨胀都是当地人,因为我希望他在每次通货膨胀时减少。当我尝试递减或增加时,我会收到奇怪的错误。

代码如下:

    package com.example.instances_temperature;

import com.example.instances_temperature.R;
//import com.example.instances_temperature.Tabel.RptUpdater;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class Tabel extends ActionBarActivity {

    int i;

    int value; // Ignore this, this is the number that is taked from mainactivity for Inflation
    //int counter=20; // counter default value for start = 20

    static int REP_DELAY = 50; // Constant value for long click update
    private Handler repeatUpdateHandler = new Handler();
    private boolean mAutoIncrement = false;
    private boolean mAutoDecrement = false;
    public class yourActivity{
        int counter = 20;

        @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tabel);
        Intent intentObject = getIntent();
        value = intentObject.getIntExtra("max", 0);
        LinearLayout layout = (LinearLayout)findViewById(R.id.container2);


        for(i=1;i<=value;i++)
        {
            LayoutInflater layoutinflate = null; 
            layoutinflate = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
            final View rowview = layoutinflate.inflate( R.layout.inflation_layout, null);

            Button add,sub;
            final TextView display;
            final TextView showup;


            add = (Button) rowview.findViewById(R.id.plus);
            sub = (Button) rowview.findViewById(R.id.minus);
            display = (TextView) rowview.findViewById(R.id.showtemp);
            showup = (TextView) rowview.findViewById(R.id.showvalue);




            showup.setText(" "+counter+"°C ");
            display.setText(""+counter+"°C");
            add.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
            if(counter<35){
                counter++;
                display.setText( "" + counter+"°C ");
                showup.setText(" "+counter+"°C ");
                }
            else{
                Context context = getApplicationContext();
                CharSequence text = "Maximum value is 35°C!";
                int duration = Toast.LENGTH_SHORT;
                final Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                toast.setGravity(Gravity.TOP, 0, 100);
                }
            }
        });

        sub.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {

            if(counter>10){
                counter--;
                display.setText( "" + counter+"°C");
                showup.setText(" "+counter+"°C ");
                }
            else{
                Context context = getApplicationContext();
                CharSequence text = "Minimum value is 10°C!";
                int duration = Toast.LENGTH_SHORT;
                final Toast toast = Toast.makeText(context, text, duration);
                toast.show();
                toast.setGravity(Gravity.BOTTOM, 0, 50);
            }
            }

        });
        add.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                mAutoIncrement = true;
                repeatUpdateHandler.post(new RptUpdater() );
                return false;
            }
        });
        add.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL) && mAutoIncrement )
                    mAutoIncrement = false;
                    return false;
            }
        });
        sub.setOnLongClickListener(new View.OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                mAutoDecrement = true;
                repeatUpdateHandler.post(new RptUpdater() );
                return false;
            }
        });
        sub.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // TODO Auto-generated method stub
                if( (event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL) && mAutoDecrement )
                    mAutoDecrement = false;
                    return false;
            }
        });



            layout.addView(rowview);
        }



        //showvalue.setText(String.valueOf(getIntent().getExtras().getInt("max")));


        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.tabel, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_tabel,
                    container, false);
            return rootView;
        }
    }

    /*protected void onSaveInstanceState(Bundle savedInstance) {
           super.onSaveInstanceState(savedInstance); 
           savedInstance.putInt("myCounter",counter); 
           }*/

    class RptUpdater implements Runnable {
        public void run() {
            if( mAutoIncrement && counter < 35){
                //increment();
                if(counter<35)
                {
                counter++;
                display.setText( "" + counter+"°C");
                showup.setText(" "+counter+"°C ");
                }
                else
                {
                    Context context = getApplicationContext();
                    CharSequence text = "Maximum value is 35°C!";
                    int duration = Toast.LENGTH_SHORT;
                    final Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                    toast.setGravity(Gravity.TOP, 0, 100);
                }
                repeatUpdateHandler.postDelayed( new RptUpdater(), REP_DELAY );
            } 
            else

                if( mAutoDecrement && counter > 10){
               // decrement();
                    if(counter>10)
                    {
                    counter--;
                    display.setText( "" + counter+"°C");
                    showup.setText(" "+counter+"°C ");
                    repeatUpdateHandler.postDelayed( new RptUpdater(), REP_DELAY );
                    }
                    else
                    {
                        Context context = getApplicationContext();
                        CharSequence text = "Minimum value is 10°C!";
                        int duration = Toast.LENGTH_SHORT;
                        final Toast toast = Toast.makeText(context, text, duration);
                        toast.show();
                        toast.setGravity(Gravity.BOTTOM, 0, 50);
                    }
                }

        }
    }
    }

}

我在这部分编码错误:

                        if(counter<35)
                        {
                        counter++;
                        display.setText( "" + counter+"°C");
                        showup.setText(" "+counter+"°C ");
                        }

当我尝试反对++时,我得到:

Description Resource    Path    Location    Type
The final local variable counter cannot be assigned, since it is defined in an enclosing type   Tabel.java  /Instances_temperature/src/com/example/instances_temperature    line 71 Java Problem

我还有3个递减或递增,这只是一个例子,如果我解决这个问题我也可以解决另一个问题。如果需要所有代码我会发布它。我认为这不是关于研究,我有尝试了一些解决方案,但没有任何改进,是关于程序的逻辑。

感谢您的时间。

3 个答案:

答案 0 :(得分:1)

final int counter = 20;

从内部类中,您可以访问外部类的变量。您可以使用counter.But,因为您已经将其声明为final,所以无法更改/递增它。

public class yourActivity{
   int counter = 20;

   protected void onCreate(Bundle savedInstanceState){
    //your Logic
   }

   class RptUpdater implements Runnable{
   //counter logic
   }

}

答案 1 :(得分:1)

而不是

final int counter = 20;

使用

int counter = 20;

那就是它。声明为final的变量以后不能修改。这是一个常数。

关于封闭类型的错误消息是误导。

答案 2 :(得分:1)

这就是java中存在关键字final的原因。变量是最终的,即它的值不能改变。如果必须更改值,请不要将变量标记为final。

使用final关键字声明变量意味着无法更改其值。最终变量就像常量。

尝试以下代码: -

        int counter = 20;// initialize counter value globally 
        protected void onCreate(Bundle savedInstanceState) {


        class RptUpdater implements Runnable {
            public void run() {
                if( mAutoIncrement && counter < 35){
                    //increment();
                    if(counter<35)
                    {
                    counter++;
                    display.setText( "" + counter+"°C");
                    showup.setText(" "+counter+"°C ");
                    }