user1433872
user1433872

Reputation: 36

adding components to an existing xml file programmatically

i have a layout that is already defined in XML. I want to add a ListView to it that displays variable data from a saved file.

The data is not fixed in size and existing data can be edited by the user so, im not sure you can store it in res.

Due to my lack of knowledge i feel programmatically creating layout components are more advantageous(listview) while other components are better done through the xml files.

Is there a way where you can use both xml and java to create a layout? Thanks.

Upvotes: 0

Views: 1227

Answers (2)

Swayam
Swayam

Reputation: 16354

You actually do not need to dynamically create the ListView.

You can have the ListView defined in a static manner in your xml file. In your java code, you need to attach the adapter to that ListView and your list would automatically have as many items as there are in the adapter.

I think you may need to go through a few basic examples of ListView to fully understand what I am trying to say.

Check this link out for a step by step tutorial on ListView: http://www.mkyong.com/android/android-listview-example/

And as your question is actually about adding elements to the xml dynamically (you don't need to do this to achieve what you are trying to do with the ListView. I am answering just for the purpose of your knowledge), this is how you do it :

        TextView textView = new TextView(YourClass.this);

        textView.setLayoutParams(....); // specify the Layout Parameters

        textView.setPadding(60, 10, 0, 10);
        textView.setTextAppearance(getBaseContext(), R.style.TitleTextStyle);

If you want to create multiple items inside any layout, see the following sample code which adds an Image and a TextView inside a dynamically created LinearLayout.

    LinearLayout ll = new LinearLayout(this);
    ll.setOrientation(1);
    ImageView iv1 = new ImageView(this);
    iv1.setImageResource(R.drawable.control);
    TextView txtTab1 = new TextView(this);
    txtTab1.setText("BLah Blah BLAh");
    txtTab1.setPadding(8, 9, 8, 9);
    txtTab1.setTextColor(Color.parseColor("#8B4513"));
    txtTab1.setTextSize(30);
    txtTab1.setBackgroundResource(R.drawable.control);
    txtTab1.setGravity(Gravity.CENTER_HORIZONTAL);

    ll.addView(iv1,0);
    ll.addView(txtTab1,1);

Upvotes: 1

FoamyGuy
FoamyGuy

Reputation: 46856

you should still put the ListView into your xml file. You make it dynamic by defining an Adapter in java and loading up with whatever data you want.

Adding the ListView to the XML does not remove the ability for you to fill it with dynamic data.

Upvotes: 1

Related Questions