[英]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.