Okhelp.cz

Recepty, články, nápady, programování. Dříve dum-zahrada, finance, internet a know-how.okhelp.cz Pro lepší výsledky hledání používejte i diakritiku.

Create Button and TextView dynamically - Android sample



public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        LinearLayout layout = (LinearLayout) findViewById(R.id.layout);
            TextView textView = new TextView(this);
            textView.setText("Text View ");
            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            layout.addView(textView, p);

            Button buttonView = new Button(this);
            buttonView.setText("Button");
            buttonView.setOnClickListener(mThisButtonListener);
            layout.addView(buttonView, p);
        
    }
    private OnClickListener mThisButtonListener = new OnClickListener() {
        public void onClick(View v) {
            Toast.makeText(MainActivity.this, "Hello !",
                    Toast.LENGTH_LONG).show();
        }
    };
}

397LW NO topic_id



Další témata ....(Topics)


206

java.lang.NullPointerException: println needs a message | java-lang-nullpointerexception-println-needs-a-message


Problemi is in e.getMessage() what can return null and Log.e (String tag, String msg) will throws an new exception !!!!
Problem and solution:

      	try {
      		int [] i = {1};
      		int z = i[5];
      	} catch (ArrayIndexOutOfBoundsException e) {
      		String s = e.toString(); // s == java.lang.ArrayIndexOutOfBoundsException
                // try to testing String s for null value
      		if(s != null)
      		 Log.e("bla", s);
      		else 
      		 Log.e("bla", "My error text 1");
      		
      		String s2 = e.getMessage(); // s2 == null !!!!!!!
                // you need to testing String s2 for null value , or you get FATAL EXCEPTION: main
                // and application will be crashed
       		String s2 = e.getMessage(); // s2 == null !!!!!!!
      		if(s2 != null)
      		 Log.e("bla2", e.getMessage());
      		else 
      		 Log.e("bla2", "My error text 2");
     		
                // this is OK
      		e.printStackTrace();
      	}


LogCat:

E/bla(855): java.lang.ArrayIndexOutOfBoundsException

 E/bla2(855): My error text 2

 W/System.err(855): java.lang.ArrayIndexOutOfBoundsException
 W/System.err(855): 	at cz.okhelp.motion._MotionActivity.onTouchEvent(_MotionActivity.java:54)
 W/System.err(855): 	at android.app.Activity.dispatchTouchEvent(Activity.java:2099)
 W/System.err(855): 	at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1675)
 W/System.err(855): 	at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2194)
 W/System.err(855): 	at android.view.ViewRoot.handleMessage(ViewRoot.java:1878)
 W/System.err(855): 	at android.os.Handler.dispatchMessage(Handler.java:99)
 W/System.err(855): 	at android.os.Looper.loop(Looper.java:123)
 W/System.err(855): 	at android.app.ActivityThread.main(ActivityThread.java:3683)
 W/System.err(855): 	at java.lang.reflect.Method.invokeNative(Native Method)
 W/System.err(855): 	at java.lang.reflect.Method.invoke(Method.java:507)
 W/System.err(855): 	at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
 W/System.err(855): 	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
 W/System.err(855): 	at dalvik.system.NativeStart.main(Native Method)




Or you can using this code:

      	try {
      		int [] i = {1};
      		int z = i[5];
      	} catch (Exception e) {
      		
      		
      		StringBuilder sb = new  StringBuilder().append(e.getClass().getSimpleName()); 
          if  (e.getMessage() != null) { 
              sb.append("

"); sb.append(e.getMessage()); } Log.e("err", sb.toString()); // E/err(336): ArrayIndexOutOfBoundsException // this code write out all message Log.e("myError", "methodName", e); } // E/myError(371): methodName // E/myError(371): java.lang.ArrayIndexOutOfBoundsException // E/myError(371): at cz.okhelp.motion._MotionActivity.onTouchEvent(_MotionActivity.java:54) // E/myError(371): at android.app.Activity.dispatchTouchEvent(Activity.java:2099) // E/myError(371): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1675) // E/myError(371): at android.view.ViewRoot.deliverPointerEvent(ViewRoot.java:2194) // E/myError(371): at android.view.ViewRoot.handleMessage(ViewRoot.java:1878) // E/myError(371): at android.os.Handler.dispatchMessage(Handler.java:99) // E/myError(371): at android.os.Looper.loop(Looper.java:123) // E/myError(371): at android.app.ActivityThread.main(ActivityThread.java:3683) // E/myError(371): at java.lang.reflect.Method.invokeNative(Native Method) // E/myError(371): at java.lang.reflect.Method.invoke(Method.java:507) // E/myError(371): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839) // E/myError(371): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) // E/myError(371): at dalvik.system.NativeStart.main(Native Method)

137

Draw drawARGB() Android basic example | draw-drawargb-android-basic-example



public class MainActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(new SampleView(this));
	}

	private static class SampleView extends View {

		// CONSTRUCTOR
		public SampleView(Context context) {
			super(context);
			setFocusable(true);

		}
		@Override
		protected void onDraw(Canvas canvas) {
			//drawARGB (int a, int r, int g, int b)
//			a  alpha component (0..255) of the color to draw onto the canvas 
//			r  red component (0..255) 
//			g  green component (0..255)  
//			b  blue component (0..255)  

			canvas.drawARGB(255, 0, 255, 10); 
		}

	}
}


343

Android widget SearchView in onCreateOptionsMenu is null | android-widget-searchview-in-oncreateoptionsmenu-is-null


If your class extends AppCompatActivity
public class SearchableActivity extends AppCompatActivity


Check if linked appropriate library for:
import android.support.v4.view.MenuItemCompat;

import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

Check if you have to properly sett SearchView in menu xml for onCreateOptionsMenu menu_main.xml

<menu xmlns:android="//schemas.android.com/apk/res/android" xmlns:app="//schemas.android.com/apk/res-auto"
xmlns:tools="//schemas.android.com/tools"
tools:context=".SearchableActivity">
<item

  android:id="@+id/menu_search_my"

android:title="@string/menu_search"
android:icon="@drawable/ic_menu_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView"

/></menu>

Check your SearchableActivity onCreateOptionsMenu
   @TargetApi(Build.VERSION_CODES.HONEYCOMB) @SuppressLint("NewApi") @Override

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {

android.support.v7.widget.SearchView searchView = (android.support.v7.widget.SearchView)
MenuItemCompat.getActionView(menu.findItem(R.id.menu_search_my));
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
if(null!=searchManager ) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
}
searchView.setIconifiedByDefault(false);
}
return true;
}
361

Not visible layout changes on testing device | not-visible-layout-changes-on-testing-device


Delete - unistal app from testing device - emulator and try again RUN - DEBUGG your app.
323

Installation error: INSTALL_FAILED_CONTAINER_ERROR | installation-error-install_failed_container_error


1.) Try delete some apps from Android emulator (can from Eclipse DDMS perspective
- File Explorer tab - data/apps folder path )
2.) Try resize emulator internal storage or SD card storage to hight size
3.)Try add to AndroidManifest.xml android:installLocation="preferExternal"

<manifest xmlns:android="//schemas.android.com/apk/res/android"
    package="com.myweb.mypackage"
    android:installLocation="preferExternal"

4.) Try resize particion from Eclipse
Preferences,
select Android- Launch
Add "-partition-size 1024" into "Default emulator option” field.
Click "Apply” and use your emulator as usual


Editace: 2011-10-22 07:54:35
Počet článků v kategorii: 397
Url:create-button-dynamically-android-sample
Share
Share
Tweet