Vergiliy
Vergiliy

Reputation: 1354

How to use Kotlin library in Java project?

I found a library that fits my purpose, but it is written on Kotlin. Can i use it in Java project?

Framework: https://github.com/mpetlyuk/initial_tips

Usage on Kotlin:

// Create view for your tip
val inflater = LayoutInflater.from(Context)
val tipView = DataBindingUtil.inflate<ViewDataBinding>(inflater, R.layout.item_tooltip, null, false).getRoot()

// Create tip
val tip = Tooltip.Builder()
    .attachTooltipView(tipView)
    .withEnterAnimation(AnimationComposer(FadeInAnimator()).duration(ANIM_DURATION))
    .withExitAnimation(AnimationComposer(FadeOutAnimator()).duration(ANIM_DURATION))
    .withGravity(TipVerticalGravity.BOTTOM, TipHorizontalGravity.LEFT)
    .withAnchorView(/* anchor view */)
    .build()

// Create a queue of tips
val tooltipsQueue = LinkedBlockingQueue<Tip>(listOf(tip))

// Create a queue of tips
TipsManager.showTips(binding.root as ViewGroup, ContextCompat.getColor(this, 0 /* your resource color for dimming */)) { tooltipsQueue }

Upvotes: 11

Views: 17002

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170909

You add the library as a dependency just as if it was Java. Kotlin is designed so it can be used from Java as easily as possible, even if you end up with less pretty code (see interoperation documentation). To translate specific examples, see How to convert a kotlin source file to a java source file.

Upvotes: 1

Tuan Luong
Tuan Luong

Reputation: 4162

You first need to add support Kotlin in your app. Just create temp kotlin file, android studio will guide you how to do it.

TextView tipView = (TextView) LayoutInflater.from(this).inflate(R.layout.item_tooltip, null, false).getRootView();
Tooltip tip = new Tooltip.Builder()
        .attachTooltipView(tipView)
        .withEnterAnimation(new AnimationComposer<BaseViewAnimator>(new FadeInAnimator()).duration(500))
        .withExitAnimation(new AnimationComposer<BaseViewAnimator>(new FadeOutAnimator()).duration(500))
        .withGravity(TipVerticalGravity.BOTTOM, TipHorizontalGravity.LEFT)
        .withAnchorView(loginButton)
        .build();

List<Tip> tips = new ArrayList<>();
tips.add(tip);
final LinkedBlockingQueue<Tip> tooltipsQueue = new LinkedBlockingQueue<>(tips);
TipsManager.showTips(rootView, R.color.colorAccent, new Function0<Queue<Tip>>() {
    @Override
    public Queue<Tip> invoke() {
        return tooltipsQueue;
    }
});

Upvotes: 5

Related Questions