Android库组件

时间:2013-01-18 04:29:28

标签: android user-interface components

我正在尝试创建一个可重用的组件来滑动其内容。

以下是组件的代码:

package com.example.components;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.LinearLayout;

public class SlideRightNLeft extends LinearLayout{



private LinearLayout.LayoutParams params1;
private LinearLayout.LayoutParams params2;


public SlideRightNLeft(Context context) {
    super(context);
}

public SlideRightNLeft(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public SlideRightNLeft(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}



public void slideRight(){
    int x = 0;

    while(x < 300) {

        try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        params1 = new LinearLayout.LayoutParams(this.getChildAt(0).getWidth(), this.getChildAt(0).getHeight());
        params1.setMargins(300 - x, 1, 1, 1);

        params2 = new LinearLayout.LayoutParams(this.getChildAt(0).getWidth(), this.getChildAt(0).getHeight());
        params2.setMargins(x, 1, 1, 1);

        this.getChildAt(0).setLayoutParams(params1);

        this.getChildAt(1).setLayoutParams(params2);

        x++;
        this.invalidate();

    }
}


}

不幸的是它不会滑动。我可以假设我必须使用runOnUiThread实际看到它滑动,但它需要一个活动,而且我在组件中,我无法访问它。

1 个答案:

答案 0 :(得分:1)

您可以使用传递给构造函数的Context来访问runOnUiThread方法。

((Activity)context).runOnUiThread(new Runnable(){

});
相关问题