[Q] OnClickListener vs. android:OnClick - Android Q&A, Help & Troubleshooting

I'm looking at both a book and the beginning projects on developers.android.com and have a question. Google is utilizing the android:nClick to handle the click event which then points to a public method for execution....but the book is setting up click listeners by setting a View with the buttons ID and then executing the setOnClickListener. OnClickListenver has one method called OnClick which is then executed.
//book
public class MyGame extends Activity implements OnClickListener {
View continueButton = findViewById(R.id.continue_button);
continueButton.setOnClickListener(this);
View newButton = findViewById(R.id.new_button);
newButton.setOnClickListener(this);
View aboutButton = findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
View exitButton = findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
}
}
My question. Which is the better way to handle the Button Click? In looking at what google does in the XML, it seems a helluva lot cleaner....but curious on what the advantage is for the other way (and I cannot think of any). Search of the site didn't yield anything.

I dunno if the methods have advantages between them, however, I prefer the androidnClick method since the code looks clearer

You usually want to use the onClick method, as there is no benefit to implementing the OnClickListener (only more effort and possible performance loss).
If you want things like long clicks or other events, you will have to implement that (or define an inline listener), as there is no xml tag for those.
I think the OnClickListener is actually only there for consistency with these other classes

Related

[Q] Need some help with GLSurfaceView

sorry if this is in the wrong place please move if thats true!
`basically im trying to make a app with a dual layer background which scrolls at different speeds but makes up the same background: for example: running water with leafs floating past.....scrolling stars with debris floating by. water equals background1' leafs equals background2 (blended together) space with stars scrolling equals background1 some debris floating equals background2..thats what im doing but im stuck here. i have everything in place, i cannot figure this bit out, preferably if someone can help me with this can u put an example or the solution please...
To this point, you have created the AGame activity, but you now need something for it to display. Let’s create a new class named AGameView:
public class AGameView{
Now, modify this class to extend GLSurfaceView.
i have done this to this class....
import android.opengl.GLSurfaceView;
public class AGameView extends GLSurfaceView {
With the class that extends the GLSurfaceView created, you can add a reference to it in your AGame activity. In the previous chapter, you set the value for setContentView() in your (application) activity to a layout. As of right now, the setContentView() value for the AGame activity is not set, or it is set to a default main layout. However, you can set this value to a GLSurfaceView. Setting the AGame setContentView() to the AGameView that you just created will let you begin to work with and display OpenGL.
Open the AGame activity, and create an instance of the AGameView GLSurfaceView that you just created.
i also have this done this:
import android.app.Activity;
import android.os.Bundle;
public class AGame extends Activity {
private AGameView gameView;
@Override
public void onCreate(Bundle savedInstanceState) {
setContentView();
Now, instantiate the AGameView, and set the setContentView() to the new instance.
done this too..
import android.app.Activity;
import android.os.Bundle;
public class AGame extends Activity {
private AGameView gameView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameView = new AGameView(this);
setContentView(gameView);
have i missed something??????? thanks for any help col

[Q] Convert TimeZone to Text

Im trying to convert the results of timezone to text for use in textView. I am new ro android devloping, so i need some help.
Here is my current code:
Code:
TimeZone tz = TimeZone.getDefault();
TextView tv = new TextView(this);
tv.setText(tz);
but it gives me this error:
Code:
The method setText(CharSequence) in the type TextView is not applicable for the arguments (TimeZone)
.
I understand the error, but I do not know how to convert the Timezone to "Eastern Standard Time" or "Pacific Standard Time" or whatever the case may be.
remember im a noob.. so please make it easy and actually show me the code. (im also new to java)
Try this:
Code:
tv.setText(tz.getDisplayName());
Whenever you are stuck its always worth looking through the android reference for the classes you are working with. You'll almost always find a solution there
http://developer.android.com/reference/java/util/TimeZone.html
that fixed it.. Thank you so much!
Yeah but like i say I'm new at java and android. So i can't understand most of it.
alexander7567 said:
that fixed it.. Thank you so much!
Yeah but like i say I'm new at java and android. So i can't understand most of it.
Click to expand...
Click to collapse
No worries. Just continue making some practice apps. And you'll get better at it!
ok my next question is.. I want this to update every 30 seconds. I thought about using a Thread.sleep(10000);, but i realize this would not work because android would detect it being an infinite loop. So how could I create some kind of a thread i believe its called to poll the timezone every 10 seconds?
Where exactly are you trying to set the text view? Is it in a while loop?
no.. the textview simply shows the timezone. I live on the timezone line and i never know what time it really is.. So i was making a app and soon a widget that shows me what timezone I'm in. It's just a learning app for me.
So i need it to poll the timezone every 30 seconds and update the textview to the current time zone.
btw.. Looked at your app and i think its really neat that you can make a game like that.. Did you have to make all the graphics or what?
I am guessing you are making the text view in the onCreate method.
Do this:
Before your activity's onCreate method, make three class members like so
Code:
private TextView textView;
private TimeZone timeZone;
private Timer timer;
Then in the onCreate method do this:
Code:
timer = new Timer();
textView = new TextView(this);
timeZone = TimeZone.getDefault();
TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
textView.setText(timeZone.getDisplayName());
}
};
timer.schedule(timerTask, 0, 30000);
Then when you wish to stop the timer do this (in the onDestroy method maybe?)
Code:
timer.cancel();
I hope you are familiar with Java's Anonymous Inner Classes. If not, I'd highly recommend first reading and getting familiar with the various Java features and techniques before continuing Android.
---------- Post added at 02:51 AM ---------- Previous post was at 02:48 AM ----------
Thank you!
Yes I made all the graphics. Except for the coin . That was made by my cousin.
i did what u said, and then i put in textView.setTextColor(929) in the time to test and see if it is actually updating, and i found out it is never running the "task"... Know what could be going on?
Sorry about the old code. I did not test it before posting it.
Anyways I've tested the following code and it works fine for me. The timerTask is called every 30 seconds. You can verify this by looking at LogCat.
Code:
public class TestActivity extends Activity
{
private TimeZone timeZone;
private TextView textView;
private Timer timer;
private Handler handler;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
textView = new TextView(this);
timeZone = TimeZone.getDefault();
timer = new Timer();
handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
textView.setText(timeZone.getDisplayName());
}
};
TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
handler.sendEmptyMessage(0);
Log.d("TestActivity", "Timer Task Called");
}
};
timer.schedule(timerTask, 0, 30000);
setContentView(textView);
}
@Override
public void onDestroy()
{
super.onDestroy();
timer.cancel();
}
}
Let me know if this works for you
What you gave me works. Thank you! I have done a lot of googling on that but there is nothing more helpful than a personalized answer.
So i think i have one last question. when you used "setContentView(textView);", it sets the whole screen to that text. And i realize this is a really noob question. But i am also trying to display other things in this app. It hides everything else.
So here is my sad atempt to fix it::
Code:
package com.alexriggs.android.timezoneclock;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class TimeZoneClockActivity extends Activity
{
private TimeZone timeZone;
private TextView t;
private Timer timer;
private Handler handler;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
t=new TextView(this);
t=(TextView)findViewById(R.id.textView1);
timeZone = TimeZone.getDefault();
timer = new Timer();
handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
t.setText(timeZone.getDisplayName());
}
};
TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
handler.sendEmptyMessage(0);
Log.d("TimeZoneClock", "Timer Task Called");
}
};
timer.schedule(timerTask, 0, 30000);
}
@Override
public void onDestroy()
{
super.onDestroy();
timer.cancel();
}
}
I show no compiler errors, but when i run the app i get a force close. I run it in debug mode and the error is around "t.setText(timeZone.getDisplayName());". I have tried googling but i cant seem to find the answer.
Sorry to keep bugging you, but i learn best by doing and not reading.
are there hardcode in this?
Well when you want to load up a view from an xml file you must do this:
Code:
setContentView(R.layout.main);
Where R.layout.main is the resource id of the xml file you wish to load. Only after that you can get the TextView (or any other component that is a part of that xml) using findViewById. And you don't need to do textView = new TextView(this); cause the TextView is already created when using xml, just grab a reference to it using findViewById.
So your code should look like this:
Code:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // Or whatever your layout xml's name is
t=(TextView)findViewById(R.id.textView1);
timeZone = TimeZone.getDefault();
timer = new Timer();
// The rest remains the same
Try it and let me know.
---------- Post added at 12:18 AM ---------- Previous post was at 12:16 AM ----------
randommmm said:
are there hardcode in this?
Click to expand...
Click to collapse
Sorry, but I'm not sure I understand what you mean to ask.
wow.. That was so simple i now feel stupid lol.
Yes that fixed it. Thank you so much for your help.
Ok.. new question for that same program.. I am now attempting to create a widget for this that simply displays a text view that shows the timezone. My problem is it simply show 'Large Text". It is not updating the text view to the timezone. Here is my code in AppWidget.java.
Code:
package com.alexriggs.android.timezoneclock;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
public class AppWidget extends AppWidgetProvider {
private TimeZone timeZone;
private TextView t;
private Timer timer;
private Handler handler;
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
t=new TextView(context);
timeZone = TimeZone.getDefault();
timer = new Timer();
handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
t.setText(timeZone.getDisplayName());
}
};
TimerTask timerTask = new TimerTask()
{
@Override
public void run()
{
handler.sendEmptyMessage(0);
Log.d("TestActivity", "Timer Task Called");
}
};
timer.schedule(timerTask, 0, 30000);
}
}
BTW... Seems like this is the hardest language I have ever tried to learn.
I realize im missing setContentView(R.layout.widget), but everytime i set it i get "The method setContentView(int) is undefined for the type AppWidget". Could that be thte issue?
Hello again
I'm not really familiar with making widgets myself, so I cannot really say what you are doing wrong. I found a link to this tutorial on making a simple widget. I think you should try and follow it and see if you can get something out of it.
Let me know if it is helpful for you or not
http://www.vogella.com/articles/AndroidWidgets/article.html
It was a lot more helpful than most things out there.
But i still am not able to understand it the best.
What i am wanting to accomplish is simply make a text view widget that displays the timezone (I.E. EST, CST, PST) and make it refresh every 30 seconds.
It isn't very hard to do in a normal app, but a widget seems impossible to me.
Is there anyone that can help me with This?

[Q] How to get access to MediaController progressbar?

I currently have a mediacontroller that I am using to control a video in a videoview. I am trying to get access to the seekbar/progressbar and am having no luck. I found somethign on google that I thought would work, and it does in fact seem to return back an object, but when I try to assign my own listener to the click event or even just set the visibility of the seekbar to invisible, it doesnt do anything. Any ideas as to what I am doing wrong?
Code:
int topContainerId = getResources().getIdentifier("mediacontroller_progress", "id", "android");
SeekBar seekbar = (SeekBar) mMediaCont.findViewById(topContainerId);
seekbar.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
Log.d("In slider onclick", "WE HAVE LIFT OFF");
}
});

Need help with voice recognition application dev

I'm developing an augmentative communication application for use on Kindle Fire. I'm using Fire HD 6 as my test device. I'm working in Xamarin, C#.
I know there is a speech recognizer on the device as the microphone icon appears on the keyboard and I can use it to populate the search window. However, my andoid speech recognizer code is not working. I get the "recognizer not present" error. Here is the code that I'm working with:
public class VoiceRecognition : Activity
{
private static String TAG = "VoiceRecognition";
private const int VOICE_RECOGNITION_REQUEST_CODE = 1234;
private ListView mList;
public Handler mHandler;
private Spinner mSupportedLanguageView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
mHandler = new Handler();
SetContentView(Resource.Layout.Main);
Button speakButton = FindViewById<Button>(Resource.Id.btnRecord);
// Check to see if a recognition activity is present
PackageManager pm = PackageManager;
IList<ResolveInfo> activities = pm.QueryIntentActivities(new Intent(RecognizerIntent.ActionRecognizeSpeech), 0);
if (activities.Count != 0)
speakButton.Click += speakButton_Click;
else
{
speakButton.Enabled = false;
speakButton.Text = "Recognizer not present";
}
}
Click to expand...
Click to collapse
This code is obviously not going to work, but I don't know where to go from here. How can I access the voice recognizer on this device?
Thanks!

Several Easy Steps to Integrate the Fundamental Capability SDK of Video Editor Kit

The launch of HMS Core Video Editor Kit 6.2.0 has brought two notable highlights: various AI-empowered capabilities and flexible integration methods. One method is to integrate the fundamental capability SDK, which is described below.
Preparations​For details, please check the official document.
Code Development​Configuring a Video Editing Project
1. Set the authentication information for your app through an API key or access token.
Use the setAccessToken method to set an access token when the app is started. The access token needs to be set only once.
Code:
MediaApplication.getInstance().setAccessToken("your access token");
Use the setApiKey method to set an API key when the app is started. The API key needs to be set only once.
Code:
MediaApplication.getInstance().setApiKey("your ApiKey");
2. Set a License ID.
This ID is used to manage your usage quotas, so ensure that the ID is unique.
Code:
MediaApplication.getInstance().setLicenseId("License ID");
3. Initialize the running environment for HuaweiVideoEditor.
When creating a video editing project, first create a HuaweiVideoEditor object and initialize its running environment. When exiting a video editing project, release the HuaweiVideoEditor object.
Create a HuaweiVideoEditor object.
Code:
HuaweiVideoEditor editor = HuaweiVideoEditor.create(getApplicationContext());
Specify the position for the preview area.
This area renders video images, which is implemented by creating SurfaceView in the fundamental capability SDK. Ensure that the preview area position on your app is specified before creating this area.
Code:
<LinearLayout
android:id="@+id/video_content_layout"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="@color/video_edit_main_bg_color"
android:gravity="center"
android:orientation="vertical" />
// Specify the preview area position.
LinearLayout mSdkPreviewContainer = view.findViewById(R.id.video_content_layout);
// Set the layout of the preview area.
editor.setDisplay(mSdkPreviewContainer);
Initialize the running environment. If the license verification fails, LicenseException will be thrown.
After the HuaweiVideoEditor object is created, it has not occupied any system resource. You need to manually set the time for initializing the running environment of the object. Then, necessary threads and timers will be created in the fundamental capability SDK.
Code:
try {
editor.initEnvironment();
} catch (LicenseException error) {
SmartLog.e(TAG, "initEnvironment failed: " + error.getErrorMsg());
finish();
return;
}
4. Add a video or image.
Create a video lane and add a video or image to the lane using the file path.
Code:
// Obtain the HVETimeLine object.
HVETimeLine timeline = editor.getTimeLine();
// Create a video lane.
HVEVideoLane videoLane = timeline.appendVideoLane();
// Add a video to the end of the video lane.
HVEVideoAsset videoAsset = videoLane.appendVideoAsset("test.mp4");
// Add an image to the end of the video lane.
HVEImageAsset imageAsset = videoLane.appendImageAsset("test.jpg");
5. Add audio.
Create an audio lane and add audio to the lane using the file path.
Code:
// Create an audio lane.
HVEAudioLane audioLane = timeline.appendAudioLane();
// Add an audio asset to the end of the audio lane.
HVEAudioAsset audioAsset = audioLane.appendAudioAsset("test.mp3");
6. Add a sticker and text.
Create a sticker lane and add a sticker and text to the lane. A sticker needs to be added using its file path, while the text needs to be added by specifying its content.
Code:
// Create a sticker lane.
HVEStickerLane stickerLane = timeline.appendStickerLane();
// Add a sticker to the end of the lane.
HVEStickerAsset stickerAsset = stickerLane.appendStickerAsset("test.png");
// Add text to the end of the lane.
HVEWordAsset wordAsset = stickerLane.appendWord("Input text",0,3000);
7. Add a special effect.
Special effects are classified into the external special effect and embedded special effect.
Add an external special effect to an effect lane. This special effect can be applied to multiple assets, and its duration can be adjusted.
Code:
// Create an effect lane.
HVEEffectLane effectLane = timeline.appendEffectLane();
// Create a color adjustment effect with a duration of 3000 ms. Add it to the 0 ms playback position of the lane.
HVEEffect effect = effectLane.appendEffect(new HVEEffect.Options(HVEEffect.EFFECT_COLORADJUST, "", ""), 0, 3000);
Add an embedded special effect to an asset. Such a special effect can be applied to a single asset. The special effect's duration is the same as that of the asset and cannot be adjusted.
Code:
// Create an embedded special effect of color adjustment.
HVEEffect effect = videoAsset.appendEffectUniqueOfType(new HVEEffect.Options(HVEEffect.EFFECT_COLORADJUST, "", ""), ADJUST);
8. Play a timeline.
To play a timeline, specify its start time and end time. The timeline will play from its start time to end time at a fixed frame rate, and the image and sound in the preview will play simultaneously. You can obtain the playback progress, playback pause, payback completion, and playback failure via the registered callback.
Code:
// Register the playback progress callback.
editor.setPlayCallback(callback);
// Play the complete timeline.
editor.playTimeLine(timeline.getStartTime(), timeline.getEndTime());
9. Export a video.
After the editing is complete, export a new video using the assets in the timeline via the export API. Set the export callback to listen to the export progress, export completion, or export failure, and specify the frame rate, resolution, and path for the video to be exported.
Code:
// Path for the video to be exported.
String outputPath =
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ File.separator + Constant.LOCAL_VIDEO_SAVE_PATH
+ File.separator + VideoExportActivity.getTime() + ".mp4";
// Resolution for the video to be exported.
HVEVideoProperty videoProperty = new HVEVideoProperty(1920, 1080);
// Export the video.
HVEExportManager.exportVideo(targetEditor, callback, videoProperty, outputPath);
Managing Materials
After allocating materials, use APIs provided in the on-cloud material management module to query and download a specified material. For details, please refer to the description in the official document.
Integrating an AI-Empowered Capability
The fundamental capability SDK of Video Editor Kit provides multiple AI-empowered capabilities including AI filter, track person, moving picture, and AI color, for integration into your app. For more details, please refer to the instruction in this document.
AI Filter
Lets users flexibly customize and apply a filter to their imported videos and images.
Code:
// Create an AI algorithm engine for AI filter.
HVEExclusiveFilter filterEngine = new HVEExclusiveFilter();
// Initialize the engine.
mFilterEngine.initExclusiveFilterEngine(new HVEAIInitialCallback() {
@Override
public void onProgress(int progress) {
// Initialization progress.
}
@Override
public void onSuccess() {
// The initialization is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The initialization failed.
}
});
// Create an AI filter of the extract type from an image, by specifying the image bitmap and filter name.
// The filter ID is returned. Using the ID, you can query all information about the filter in the database.
String effectId = mFilterEngine.createExclusiveEffect(bitmap, "AI filter 01");
// Add the filter for the first 3000 ms segment of the effect lane.
effectLane.appendEffect(new HVEEffect.Options(
HVEEffect.CUSTOM_FILTER + mSelectName, effectId, ""), 0, 3000);
Color Hair
Changes the hair color of one or more persons detected in the imported image, in just a tap. The color strength is adjustable.
Code:
// Initialize the AI algorithm for the color hair effect.
asset.initHairDyeingEngine(new HVEAIInitialCallback() {
@Override
public void onProgress(int progress) {
// Initialization progress.
}
@Override
public void onSuccess() {
// The initialization is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The initialization failed.
}
});
// Add the color hair effect by specifying a color and the default strength.
asset.addHairDyeingEffect(new HVEAIProcessCallback() {
@Override
public void onProgress(int progress) {
// Handling progress.
}
@Override
public void onSuccess() {
// The handling is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The handling failed.
}
}, colorPath, defaultStrength);
// Remove the color hair effect.
asset.removeHairDyeingEffect();
Moving Picture
Animates one or more persons in the imported image, so that they smile, nod, or more.
Code:
// Add the moving picture effect.
asset.addFaceReenactAIEffect(new HVEAIProcessCallback() {
@Override
public void onProgress(int progress) {
// Handling progress.
}
@Override
public void onSuccess() {
// The handling is successful.
}
@Override
public void onError(int errorCode, String errorMessage) {
// The handling failed.
}
});
// Remove the moving picture effect.
asset.removeFaceReenactAIEffect();
This article presents just a few features of Video Editor Kit. For more, check here.
To learn more, please visit:
>> HUAWEI Developers official website
>> Development Guide
>> Reddit to join developer discussions
>> GitHub to download the sample code
>> Stack Overflow to solve integration problems
Follow our official account for the latest HMS Core-related news and updates.

Categories

Resources