繁体   English   中英

如何以编程方式设置视图的LayoutParams?

[英]How can I set the LayoutParams of an View Programmatically?

您从http://code.google.com/p/mobile-anarchy-widgets/wiki/JoystickView知道此JoystickView吗? 好吧,我试图实现它。 没问题。 我无法更改其大小,因为我以编程方式添加了它。 我以某种方式找到了更改大小的方法,但是现在它卡在了左上角,我发现三个小时的所有内容都使我在我创建或被拒绝的LayoutParams参数上出现了NullPointerException异常,因为它不可铸造或其他首先。

public class GameActivity extends Activity implements JoystickMovedListener{

private GraphicsHolder mGraphicsHolder;
private String TAG = "GameActivity";

/*
 * creates a new GraphicsHolder and sets it its ContentView
 * the GraphicsThread is being included in the GraphicsHolder
 */
@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    Log.d(TAG, "created");

    FrameLayout gameScreen = new FrameLayout(this);

    mGraphicsHolder = new GraphicsHolder(this);

    JoystickView Joystick = new JoystickView(this);


    // I need to set the Gravity HERE


    Joystick.setLayoutParams(new RelativeLayout.MarginLayoutParams(500,500));

    gameScreen.addView(mGraphicsHolder);
    gameScreen.addView(Joystick);

    setContentView(gameScreen);
}
}

现在这是我的问题:您能以编程方式设置此视图的重力吗?

你可以试试这个

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(500,500);
params.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

Joystick.setLayoutParams(params);

尝试将重心设置为FrameLayout并使用ViewGroup.LayoutParams设置Joystick LayoutParams:

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT);
params.gravity = Gravity.CENTER;
gameScreen.setLayoutParams(params);

Joystick.setLayoutParams(new ViewGroup.LayoutParams(500,500));

尝试这个。

FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) Joystick.getLayoutParams();
params.gravity = Gravity.TOP;// desired gravity

Joystick.setLayoutParams(params);

不要更改您的代码,只需在setContentView(gameScreen);之后添加此代码setContentView(gameScreen); 希望它能工作

好吧,我找到了答案,但这是一种完全不同的方法,因为以上内容或我在其他地方发现的内容都不适合我。

我在onCreate方法中做了以下更改:

    mGraphicsHolder = new GraphicsHolder(this);

    LayoutInflater inflate = (LayoutInflater)
            getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    setContentView(mGraphicsHolder);

    getWindow().addContentView(inflate.inflate(
        R.layout.controllayout, null), new ViewGroup.LayoutParams(
        ViewGroup.LayoutParams.FILL_PARENT, 
        ViewGroup.LayoutParams.FILL_PARENT));

    Joystick = (JoystickView) getWindow().findViewById(R.id.joystickView1);
    Joystick.setOnJostickMovedListener(this);

现在,我将操纵杆安装在XML布局上,但是它实际上可以工作(至少在我没有其他工作的情况下),并且可以很容易地对Layout等进行更改。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM