-6

我正在拼命地尝试从扩展 ImageView 的 Activity 类(我正在修改标准 ImageView 的类)传递一个 int。这似乎相当困难。到目前为止,我已经尝试过:

  • 通过 SharedPreference 传递它,语法错误(无应用程序上下文)
  • 将其作为意图传递(不能在扩展 ImageView 中 getIntent()
  • 将其作为对象传递(getApplication() 处的语法错误)

我想知道是否有任何可能的方法将 Activity 类中的 int 传递给扩展 ImageView 的类。我没有上面列出的解决方案的代码,但我已经从 Activity 到 Activity 尝试了它们。有没有办法通过这个int?

4

1 回答 1

2

我想您在代码中的某处初始化这个“扩展 ImageView”类并用它来膨胀布局?IE:

CustomImageView myImageView = new CustomImageView();
[...]
yourRootView.addView(myImageView);

如果是这样,您可以在初始化时传递 int :

CustomImageView myImageView = new CustomImageView(yourInt);

与您的 CustomImageView.class 在 cunstructor 中捕获它:

public CustomImageView(int yourInt) {
    Log.i("Hello", "This is the int your were looking for" + yourInt);

另一种方法是在您的 CustomImageView.class 中设置一个 setter/getter

private yourInt;

public void setInt(int yourInt) {
    this.yourInt = yourInt;
}

然后,您可以从您的活动中执行以下操作:

CustomImageView myImageView = new CustomImageView();
myImageView.setInt(yourInt);

抱歉,如果这不能回答您的问题,您提供的信息很少,所以我不得不猜测(*编辑,我找不到“评论”按钮来...评论)

编辑

您的活动课程:

class MyActivtiy extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_someactivity);

        MyImageView myImageView = new MyImageView(2); // 2 is our Example Integer

        //**Alternative** - Needs setInger(int someInt) in ImageView class (see below)
        myImageView.setInteger(4);
    }
}

你的 ImageView 类

class MyImageView extends ImageView {

    Int anInteger;

    public MyImageView(int anInteger) {
         Log.i("Hello", "The integer is: " + anInteger);
         // Above line will show in Logcat as "The integer is: 2
         this.anInteger = anInteger;
         // Above line will set anInteger so you can use it in other methods
    }

    public void printIntToLogCat() {
        Log.i("Hello", "You can use the integer here, it is: "  + anInteger);
        // Above line in logcat: "You can [...], it is: 2"
    }

    //**Alternative**
    public void setInteger(int someInt) {
       this.anInteger = someInt;  // With above example this will set anInteger to 4
       printIntToLogCat();
       // Above Line will print: "You can[...], it is: 4"
    }
}
于 2012-11-07T16:45:08.603 回答