将一段iOS代码转换为Android

时间:2013-06-19 14:29:01

标签: android objective-c android-animation porting

我认为从标题来看这个问题有点令人困惑,会吸引很多( - ),但你会发现它非常有趣。

我已经为iOS编写了一款不错的应用程序代码,并且我的朋友希望将其移植到 Android 中。除了一段代码外,一切都很顺利。

在我的iOS应用程序中,当UIWebview正在加载时,我会显示一个UIView,动画化它。当UIWebview完成加载时,我将其隐藏起来。 我使用animateWithDuration函数制作的动画。 我们在这里:

UIView:

@property (nonatomic,retain) IBOutlet UIView *animationLayer;
_animationLayer.hidden=YES;

在Viewdidload中初始化

_animationLayer = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    _animationLayer.backgroundColor=[UIColor colorWithRed:(arc4random() % 255)/255.0f green:(arc4random() % 255)/255.0f blue:(arc4random() % 255)/255.0f alpha:1.0f];
    _animationLayer.autoresizingMask=(UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth);

加载时显示UIView并开始设置动画:

- (void) webViewDidStartLoad:(UIWebView *)webView {
[UIView animateWithDuration:7.0
                      delay:0.0
                    options: UIViewAnimationOptionCurveEaseOut
                 animations:^{ _animationLayer.backgroundColor=[UIColor colorWithRed:(arc4random() % 255)/255.0 green:(arc4random() % 255)/255.0 blue:(arc4random() % 255)/255.0 alpha:1.0f];}
                 completion:nil];
}

在完成加载时隐藏

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    _animationLayer.hidden=YES;
}

以下是我认为可以在Android中制作的内容。 在加载时显示自定义的进度条,并在完成后隐藏它。可以在全屏画布中自定义进度条,改变它的颜色,就像上面的iOS代码一样。但没有运气! :( 有任何建议或简单方法吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

好的是,为了在进行Web调用时在后台获取Android动画,请使用AsyncTask。看起来像这样

   private class WebCallOperation extends AsyncTask<String, Void, String>
        {
            private final ProgressDialog dialog = new ProgressDialog(context);

            @Override
            protected String doInBackground(String... params)
            {

                //web call code here

                //response returned here
                return "";
            }

            @SuppressWarnings("rawtypes")
            @Override
            protected void onPostExecute(String result)
            {
                if (this.dialog.isShowing())
                {
                    this.dialog.dismiss();
                }
            }

            @Override


protected void onPreExecute()
        {
            this.dialog.setMessage("Loading");
            this.dialog.show();
        }
    }

在我刚刚给出的示例代码中,我添加了ProgressDialog,这通常是我在进行Web调用时使用的内容,但是您可以将其替换为您想要的任何内容。您可以添加自己的视图,并为其设置动画。在预执行方法中对其进行动画处理,然后在后执行方法中完成Web调用。

关于IOS应用程序的一些建议,我在评论中已经提到持续时间问题。我还认为您应该研究用于执行Web调用的块代码。如果您希望我能提供一些示例代码,那么您的生活会更轻松

编辑:

Objective-C分组代码。在这里创建这个类

接口类

#import <Foundation/Foundation.h>
#import "WebCall.h"

@interface WebCall : NSObject
{
    void(^webCallDidFinish)(NSString *response);

}

@property (nonatomic, retain) NSMutableData *responseData;

-(void)setWebCallDidFinish:(void (^)(NSString *))wcdf;

-(void)webServiceCall :(NSString *)sURL_p : (NSMutableArray *)valueList_p : (NSMutableArray *)keyList_p;

@end

实施班

#import "WebCall.h"
#import "AppDelegate.h"
@implementation WebCall

@synthesize responseData;

-(void)setWebCallDidFinish:(void (^)(NSString *))wcdf
{
    webCallDidFinish = [wcdf copy];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    int responseStatusCode = [httpResponse statusCode];

    NSLog(@"Response Code = %i", responseStatusCode);
    if(responseStatusCode < 200 || responseStatusCode > 300)
    {
        webCallDidFinish(@"failure");
    }



    [responseData setLength:0];
}

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{

    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];

    [challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data]; 
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    NSLog(@"WebCall Error: %@", error);
    webCallDidFinish(@"failure");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

        NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        response = [response stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        webCallDidFinish(response);

}

-(void)webServiceCall :(NSString *)sURL_p : (NSMutableArray *)valueList_p : (NSMutableArray *)keyList_p
{
    NSMutableString *sPost = [[NSMutableString alloc] init];

    //If any variables need passed in - append them to the POST
    //E.g. if keyList object is username and valueList object is adam will append like
    //http://test.jsp?username=adam
    if([valueList_p count] > 0)
    {
        for(int i = 0; i < [valueList_p count]; i++)
        {
            if(i == 0)
            {
                    [sPost appendFormat:@"%@=%@", [valueList_p objectAtIndex:i],[keyList_p objectAtIndex:i]];
            }
            else
            {

                    [sPost appendFormat:@"&%@=%@", [valueList_p objectAtIndex:i], [keyList_p objectAtIndex:i]];
            }
        }
    }


    NSData * postData = [sPost dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:NO];
    NSString * postLength = [NSString stringWithFormat:@"%d",[postData length]];



    NSURL * url = [NSURL URLWithString:sURL_p];
    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setHTTPBody:postData];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

    if (theConnection)
    {
        self.responseData = [NSMutableData data];
    }


}

@end

然后你进行这个网络电话,你就这样称呼它

 WebCall *webCall = [[WebCall alloc] init];


    [webCall setWebCallDidFinish:^(NSString *str){

        //This method is called as as soon as the web call is finished
        NSLog(@"%@", str);
    }];


    //Make web call here
    [webCall webServiceCall:@"http://www.bbc.co.uk/" :nil :nil];

请参阅setWebCallDidFinish方法,直到webcall完成后才会调用它。因此,如果您需要在Web调用完成后立即执行某些代码,例如停止动画,请在该方法中调用它。希望有所帮助

答案 1 :(得分:1)

尝试像Apportable这样的事情要容易得多。它使用clang并将所有objective-c编译为Android的本机ARM代码。你正在做的一切都将在Android上的SDK之上运行。

答案 2 :(得分:0)

您可以尝试 ObjC2J

ObjC2J是一个开源库工具,它将Objective-C(Mac OS X)代码转换为PC平台的Java。