开发者

Android and XML Layout

Is it possible to use Java code to write to the开发者_Python百科 main.xml file? I want to make some changes to the layout but have it based from values received from Java?


Yes you can. Read more about YOURLAYOUT.LayoutParams

http://developer.android.com/reference/android/widget/LinearLayout.LayoutParams.html Use the addRule() and specify what you need to your layout object. Change the values before you do setContentView();

Something like:

 RelativeLayout rl = new RelativeLayout(this);
       RelativeLayout.LayoutParams rlp= new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
       rlp.addRule(RelativeLayout.VISIBLE); //set the rules and parameters before you do setLayoutParams();
       rl.setLayoutParams(rlp);  
       setContentView(rl);

Or if you want to make changes on the actual layout from the xml then you do the inflating

  LayoutInflater inflater = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View v = inflater.inflate(R.layout.main, null);
    RelativeLayout rl = (RelativeLayout)v.findViewById(R.id.relativeLayout1);
    RelativeLayout.LayoutParams rlp= new RelativeLayout.LayoutParams(new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT));
    rlp.addRule(RelativeLayout.VISIBLE);
    rl.setLayoutParams(new LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT));   
    setContentView(rl);


You can't actually change any xml layout file from within the application. Once packaged, the layout files are read-only. What you can do (and I think this is what Nikola is suggesting) is use the api to either define your layout using code or modify the layout once it has been inflated from xml.

If you want to calculate or retrieve some data that defines your layout, and then remember the data for the next time the app runs, you can use one of the data storage methods that Android offers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜