Now i would like to add button dynamically in FingerPaint api demos. But the problem is that i ain't familiar with creating layo开发者_运维百科ut dynamically in java file. does somebody know how can i implement this class to add buttons in title bar? Any code samples would be appreciate.
Explanation:
1) Get a reference to the layout container where to insert the dynamic gui component. If the container was created dynamically, you already have a reference to it. If it comes from a xml layout, you can get a reference with findViewById
.
2) Create a dynamic component. You need to pass a context to the constructor: Use this
.
3) Set the created component properties.
4) Use container.addView(component)
to add the component dynamically to the container.
Step by step demo:
1) Use the project assistant to create a new Android project with default options, package test.test
, and a Main
activity.
2) Edit the res/layout/main.xml
file as follows.
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/layoutId" > </LinearLayout> </LinearLayout>
3) Edit the src/test.test/Main.java
file as follows.
package test.test; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.Toast; public class Main extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); addDynamicButton(); } /** * Adds a dynamic button. */ private void addDynamicButton() { // creates a button dynamically Button btn = new Button(this); // sets button properties btn.setText("I'm dynamic. Please click me."); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Toast toast = Toast.makeText(Main.this, "Yo!", Toast.LENGTH_LONG); toast.show(); } }); // retrieve a reference to the container layout LinearLayout container = (LinearLayout)findViewById(R.id.layoutId); // adds dynamic button to the GUI container.addView(btn); } }
4) Compile and run as an Android application. Now you know how it works and you can use this technique to add any kind of component to any layout container.
精彩评论