DataBinding: How to use BaseActivity / How to use Abstraction - android

I am trying to add DataBinding to my app. In my app, I have a BaseActivity which has a Toolbar and a FrameLayout. FrameLayout is container for activities' which extend the BaseActivity. How can I add databinding to both my BaseActivity and the extending activities?
I'll share my code without DataBinding:
Here is my BaseActivity.java:
public class BaseActivity extends AppCompatActivity {
#Override
public void setContentView(#LayoutRes int layoutResID) {
LinearLayout container = (LinearLayout) getLayoutInflater().inflate(R.layout.activity_base, null);
FrameLayout activityContent = (FrameLayout) container.findViewById(R.id.activityContent);
getLayoutInflater().inflate(layoutResID, activityContent, true);
super.setContentView(container);
Toolbar toolbar = (Toolbar) container.findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(menuItem);
}
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
Here is activity_base.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<include
android:id="#+id/toolbarLayout"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/activityContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</layout>
Here is the activity which extends BaseActivity: CardRecyclerViewActivity.java:
public class CardRecyclerViewActivity extends BaseActivity {
RecyclerView recyclerView;
ReplikAdapter adapter;
ArrayList<Replik> replikListesi;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_card_recyclerview);
replikListesiniDoldur();
adapter = new ReplikAdapter(replikListesi, this, R.layout.item_card_replik);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setAdapter(adapter);
setTitle(R.string.cardRecylerView);
}
public void replikListesiniDoldur() {
replikListesi = new ArrayList<Replik>();
replikListesi.add(new Replik(R.drawable.harvey1, "Ben ihtimallere oynamam. Adama oynarım.", "Harvey Specter"));
replikListesi.add(new Replik(R.drawable.harvey2, "Avukatlık doktorluğa çok benzer, acıtana kadar bastırırsın ve böylece nereye bakman gerektiğini anlarsın.", "Harvey Specter"));
replikListesi.add(new Replik(R.drawable.harvey3, "İşte aramızdaki fark bu; Sen küçük kaybetmek istiyorsun ben ise büyük kazanmak.", "Harvey Specter"));
replikListesi.add(new Replik(R.drawable.harvey4, "Benim hayallerim yok, hedeflerim var.", "Harvey Specter"));
}
}
Okey, I add DataBinding to my BaseActivity.java like that:
public class BaseActivity extends AppCompatActivity {
#Override
public void setContentView(#LayoutRes int layoutResID) {
ActivityBaseBinding binding = DataBindingUtil.inflate(getLayoutInflater(), R.layout.activity_base, null, false);
getLayoutInflater().inflate(layoutResID, binding.activityContent, true);
super.setContentView(binding.getRoot());
setSupportActionBar(binding.toolbarLayout.toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
if (menuItem.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(menuItem);
}
public void setTitle(String title) {
getSupportActionBar().setTitle(title);
}
}
activity_base.xml with DataBinding:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<include
android:id="#+id/toolbarLayout"
layout="#layout/toolbar" />
<FrameLayout
android:id="#+id/activityContent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</layout>
But I am not sure how to add DataBinding to my extending activities in this scenerio. Could you help me out, please?

Might be late for this question.
Your BaseActivity should looks like following.
public abstract class BaseActivity<B extends ViewDataBinding, T extends BaseViewModel> extends AppCompatActivity {
protected B dataBinding;
protected T baseViewModel;
protected void bindView(int layoutId) {
dataBinding = DataBindingUtil.setContentView(this, layoutId);
}
#Override
protected void onDestroy() {
baseViewModel.detachView();
super.onDestroy();
}
}
Your MainActivity should looks like following.
public class MainActivity extends BaseActivity<ActivityMainBinding, MainActivityViewModel> implements MainActivityView, View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bindView(R.layout.activity_main);
baseViewModel = new MainActivityViewModel();
baseViewModel.attachView(this);
dataBinding.btnPerformOperation.setOnClickListener(this);
}
#Override
public void OnDataLoad(String item) {
dataBinding.setIsLoading(false);
startActivity(new Intent(MainActivity.this, SecondActivity.class).putExtra("result", item));
}
#Override
public void OnError(Throwable throwable) {
}
#Override
public void onClick(View v) {
dataBinding.setIsLoading(true);
baseViewModel.loadNextData();
}
}
Reference source code can be download from here.
Hope this helps you.

how about this?
BaseActivityViewModel.java
public class BaseActivityViewModel {
public void onClick() {
Log.i("BaseActivityViewModel | onClick", "111111111111");
}
}
activity_base.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="model"
type="kr.changhoonjin.textmvvmwithextend.BaseActivityViewModel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{()->model.onClick()}"
android:text="base"/>
<FrameLayout
android:id="#+id/layout_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
</layout>
BaseActivity.java
public class BaseActivity extends AppCompatActivity {
private ActivityBaseBinding binding;
#Override protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_base);
binding.setModel(new BaseActivityViewModel());
}
protected <T extends ViewDataBinding> T putContentView(#LayoutRes int resId) {
return DataBindingUtil.inflate(getLayoutInflater(), resId, binding.layoutContainer, true);
}
}
MainActivityViewModel.java
public class MainActivityViewModel {
public void onClick2() {
Log.i("MainActivityViewModel | onClick2", "2222222222222");
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="model"
type="kr.changhoonjin.textmvvmwithextend.MainActivityViewModel"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="#{()->model.onClick2()}"
android:text="main"/>
</LinearLayout>
</layout>
MainActivity.java
public class MainActivity extends BaseActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityMainBinding binding = putContentView(R.layout.activity_main);
binding.setModel(new MainActivityViewModel());
}
}

It will be same as you have done in BaseActivity, instead of inflate just use setContentView
private ActivityCardRecyclerviewBinding binding;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.activity_card_recyclerview);
}

Related

App crash after adding another item - cwac-pager

I'm having trouble with adding another page to the cwac-pager's ArrayPagerAdapter (v4). I had to use that library because I wasn't able to add a new tab dynamically using the system PagerAdapter.
MainActivity.java:
public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener {
private ViewPager viewPager;
private ArrayPagerAdapter pagerAdapter;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setSupportActionBar((Toolbar) findViewById(R.id.app_toolbar));
tabLayout = findViewById(R.id.tab_layout);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = findViewById(R.id.pager);
pagerAdapter = new CustomPagerAdapter(getSupportFragmentManager(), new ArrayList<PageDescriptor>());
viewPager.setAdapter(pagerAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(this);
}
#Override
public void onStart() {
super.onStart();
pagerAdapter.add(new TestPageDescriptor());
tabLayout.addTab(tabLayout.newTab().setText("Hello"));
// Uncomment the following lines to make the app crash
pagerAdapter.add(new TestPageDescriptor()); // CRASH
tabLayout.addTab(tabLayout.newTab().setText("Hello2"));
}
#Override
public void onStop() {
super.onStop();
// Remove all the tabs (required in my main application, not in this test)
tabLayout.removeAllTabs();
for (int i = 0; i < pagerAdapter.getCount(); i++) {
pagerAdapter.remove(i);
}
}
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
private class CustomPagerAdapter extends ArrayPagerAdapter<Fragment> {
CustomPagerAdapter(FragmentManager fragmentManager, List<PageDescriptor> descriptors) {
super(fragmentManager, descriptors);
}
#Override
protected Fragment createFragment(PageDescriptor desc) {
return new TestFragment();
}
}
private class TestPageDescriptor extends SimplePageDescriptor {
TestPageDescriptor() {
super("Test","TestHey");
}
}
}
TestFragment.java:
public class TestFragment extends Fragment {
#Override
public View onCreateView(#NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.test_frag, container, false);
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="me.test.myapplication.MainActivity"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
android:id="#+id/app_toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light"
app:title="#string/app_name" />
<android.support.design.widget.TabLayout
android:id="#+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:minHeight="?attr/actionBarSize"/>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="fill_parent" />
</LinearLayout>
test_frag.xml: just a LinearLayout with a View, no matter which.
In MainActivity.java see the comments I added in onStart(): if you run the app with just one tab (last two lines of the method commented), the activity will start correctly. However, if you add another tab by uncommenting the lines, the app will crash immediately. What am I doing wrong?
Thanks
Edit: logcat
I/Process: Sending signal. PID: 3877 SIG: 9
Application terminated.
No exceptions, no errors.
The fragment tags need to be unique, as is covered in the library documentation. So, as Matt Clark pointed out, you need to use different tags for your different pages.
Note that you do not need to create your own subclass of SimplePageDescriptor, at least in the code from your question. You could just use SimplePageDescriptor directly.

Getting Youtube videos using RecyclerView and cardView with Firebase in Android studio

I have been working on an android project in which I have used YouTube API and Firebase as a database, I also used recyclerView in it but my videos from Firebase database are not showing in the application, I have implemented it correctly I guess but there is something wrong with it, please help.
I am using Android Studio
YouTube Firebase Adapter java class:
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.youtube_videos);
YDatabaseReference = FirebaseDatabase.getInstance().getReference().child("youT");
YouRecycler = (RecyclerView)findViewById(R.id.Youtube_recycler);
}
#Override
public void onStart() {
super.onStart();
FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<post2youtube, YoutubeViewHolder>(
post2youtube.class,
R.layout.youtube_videos_card,
YoutubeViewHolder.class,
YDatabaseReference
) {
#Override
protected void populateViewHolder(YoutubeViewHolder viewHolder, post2youtube model, int position) {
viewHolder.setYoutube(model.getYoutubing());
}
};
YouRecycler.setAdapter(firebaseRecyclerAdapter);
}
public static class YoutubeViewHolder extends RecyclerViewPager.ViewHolder {
View yView;
public YoutubeViewHolder(View itemView) {
super(itemView);
yView = itemView;
}
public void setYoutube(final String youtubing){
final YouTubePlayerView youPlay = (YouTubePlayerView) yView.findViewById(R.id.youtuber);
youPlay.initialize("SOME KEY",
new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
youTubePlayer.cueVideo(youtubing);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
Getter and setters class :
public class post2youtube {
private String youtubing;
public post2youtube(){
}
public post2youtube(String youtubing) {
this.youtubing = youtubing;
}
public String getYoutubing() {
return youtubing;
}
public void setYoutubing(String youtubing) {
this.youtubing = youtubing;
}
}
RecyclerView xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/Youtube_recycler"/>
</LinearLayout>
CardView xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtuber"
android:layout_width="match_parent"
android:layout_height="200dp" />
</LinearLayout>
</android.support.v7.widget.CardView>

Toolbar in BaseActivity

I have multiple activities and fragments. I would like to set toolbar in BaseActivity (so set it only once). But need an acces to the toolbar from fragment (method like - show, hide, changeTitle etc.)
Any suggestion?
I have tried solution below, but when I want to hide fragment, NPException is shown
public abstract class BaseActivity extends AppCompatActivity {
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
configureToolbar();
}
protected abstract int getLayoutResource();
private void configureToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
public void hideToolbar() {
toolbar.setVisibility(View.GONE);
}
My activity
public class MyActivity extends BaseActivity() {
}
I call hideToolbar in fragment like:
public class MyFragment extends Fragment() {
onCreate() {
((Myactivity)getActivity).hideToolbar();
}
I have include something like yours in my project. This is sample. You can take reference from it.
BaseActivity.java class:
public abstract class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
}
protected abstract int getLayoutResource();
}
ToolBarActivity.java class:
public abstract class ToolbarActivity extends BaseActivity {
protected Toolbar toolbar;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View contentView = findViewById(R.id.flToolbarContentContainer);
if (contentView instanceof ViewGroup) {
((ViewGroup) contentView)
.addView(LayoutInflater.from(this)
.inflate(getToolbarLayoutResource()
, (ViewGroup) contentView, false));
}
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
protected int getLayoutResource() {
return R.layout.activity_toolbar;
}
protected abstract int getToolbarLayoutResource();
public void showToolbar() {
toolbar.setVisibility(View.VISIBLE);
}
public void hideToolbar() {
toolbar.setVisibility(View.GONE);
}
}
activity_toolbar.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rlToolbarContainer"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:layout_toLeftOf="#+id/pbToolbarActivity"
android:background="#color/blue_panel_day_background"
android:theme="#style/ToolbarTheme" />
<FrameLayout
android:id="#+id/flToolbarContentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/toolbar" />
</RelativeLayout>
MainActivity.java class:
public class MainActivity extends ToolbarActivity {
#Override
protected int getToolbarLayoutResource() {
return R.layout.activity_main;
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
homeFragment = HomeFragment.newInstance();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.llMainActivityContainer, homeFragment)
.commit();
}
}
activity_main.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llMainActivityContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
</LinearLayout>
Now, in Fragment class, apply:
((ToolbarActivity) getActivity()).showToolbar();
((ToolbarActivity) getActivity()).hideToolbar();
From Fragment
getActivity().getSupportActionBar();
Use:
public abstract class BaseActivity extends AppCompatActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(getLayoutResource());
configureToolbar();
}
protected abstract int getLayoutResource();
private void configureToolbar() {
toolbar = (Toolbar) findViewById(R.id.toolbar);
// changes made here, try to find if getSupportActionBar() is null or not after setting it - setSupportActionBar
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
// How and where you calling this method ?
public void hideToolbar() {
toolbar.setVisibility(View.GONE);
}
To access ActionBar from Fragment try the below method
ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
You can now access all the methods of ActionBar

YouTubePlayerFragment not working(Playing) in CollapsingToolbarLayout

YouTubePlayerFragment not working(Playing) in CollapsingToolbarLayout.
I want to play youtube video from youtube android api. Inside CollapsingToolbarLayout, YouTubePlayerFragment does not play, only thumbnail comes and after 1 seconds it goes to stop.
I it work fine inside other layout. I want material design collapsing layout with youtube video. Please help me.
<android.support.design.widget.CoordinatorLayout
android:id="#+id/root_coordinator"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/app_bar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content">
android:fitsSystemWindows="true">
<android.support.design.widget.CollapsingToolbarLayout
android:id="#+id/collapsing_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentScrim="?attr/colorPrimary"
app:expandedTitleMarginEnd="64dp"
app:expandedTitleMarginStart="48dp"
app:layout_scrollFlags="scroll|exitUntilCollapsed">
<!--<ImageView
android:id="#+id/image"
android:layout_width="match_parent"
android:layout_height="250dp"
android:src="#drawable/ic_launcher"
android:visibility="visible"
app:layout_collapseMode="parallax" />-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layoutYoutube"
android:layout_width="match_parent"
android:layout_height="250dp"
android:visibility="visible"
app:layout_collapseMode="parallax">
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
<android.support.v7.widget.Toolbar
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_collapseMode="pin">
<include
layout="#layout/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.CollapsingToolbarLayout>
</android.support.design.widget.AppBarLayout>
<FrameLayout
android:id="#+id/frameContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="1dp"
android:background="#android:color/white"
android:paddingTop="2dp"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
</FrameLayout>
</android.support.design.widget.CoordinatorLayout>
The official documentation says:
Note that while videos are playing, this View has a minimum size of 200x110 dp. If you make the view any smaller, videos will automatically stop playing. Also, it is not permitted to overlay this fragment's view with other views while a video is playing.
So there is no way to get to work YouTubePlayerFragment and
YouTubePlayerView in CollapsingToolbarLayout.
PS: If someone managed to do it - share the solution. I had this same problem, but I could not solve it.
It would have been helpful if you had posted the logic code or java code and the error log. I am posting the java code, please take a look at this one might work for you too...
public class YoutubeActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener{
public static final String API_KEY = "xxxxxxxxxx";
public static final String VIDEO_ID = "xxxxxxx";
private YouTubePlayer youTubePlayer;
private YouTubePlayerFragment youTubePlayerFragment;
private TextView textVideoLog;
private Button btnViewFullScreen;
private static final int RQS_ErrorDialog = 1;
private MyPlayerStateChangeListener myPlayerStateChangeListener;
private MyPlaybackEventListener myPlaybackEventListener;
String log = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_youtube);
youTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager()
.findFragmentById(R.id.youtubeplayerfragment);
youTubePlayerFragment.initialize(API_KEY, this);
textVideoLog = (TextView)findViewById(R.id.videolog);
myPlayerStateChangeListener = new MyPlayerStateChangeListener();
myPlaybackEventListener = new MyPlaybackEventListener();
btnViewFullScreen = (Button)findViewById(R.id.btnviewfullscreen);
btnViewFullScreen.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View arg0) {
youTubePlayer.setFullscreen(true);
}});
Button btnPlay = (Button) findViewById(R.id.btnplay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(youTubePlayer.isPlaying())
youTubePlayer.pause();
else
youTubePlayer.play();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_splash_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
Log.e("id", id+"");
switch(item.getItemId()){
case R.id.action_share:
break;
case 16908332:
onBackPressed();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youtube, boolean b) {
youTubePlayer = youtube;
Toast.makeText(getApplicationContext(), "YouTubePlayer.onInitializationSuccess()", Toast.LENGTH_LONG).show();
youtube.setPlayerStateChangeListener(myPlayerStateChangeListener);
youtube.setPlaybackEventListener(myPlaybackEventListener);
if (!b) {
youTubePlayer.cueVideo(VIDEO_ID);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
if (youTubeInitializationResult.isUserRecoverableError()) {
youTubeInitializationResult.getErrorDialog(this, RQS_ErrorDialog).show();
} else {
Toast.makeText(this,"YouTubePlayer.onInitializationFailure(): " + youTubeInitializationResult.toString(),Toast.LENGTH_LONG).show();
}
}
private final class MyPlayerStateChangeListener implements YouTubePlayer.PlayerStateChangeListener {
private void updateLog(String prompt){
log += "MyPlayerStateChangeListener" + "\n" +prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onAdStarted() {
updateLog("onAdStarted()");
}
#Override
public void onError(
com.google.android.youtube.player.YouTubePlayer.ErrorReason arg0) {
updateLog("onError(): " + arg0.toString());
}
#Override
public void onLoaded(String arg0) {
updateLog("onLoaded(): " + arg0);
}
#Override
public void onLoading() {
updateLog("onLoading()");
}
#Override
public void onVideoEnded() {
updateLog("onVideoEnded()");
}
#Override
public void onVideoStarted() {
updateLog("onVideoStarted()");
}
}
private final class MyPlaybackEventListener implements YouTubePlayer.PlaybackEventListener {
private void updateLog(String prompt){
log += "MyPlaybackEventListener" + "\n-" +
prompt + "\n\n=====";
textVideoLog.setText(log);
};
#Override
public void onBuffering(boolean arg0) {
updateLog("onBuffering(): " + String.valueOf(arg0));
}
#Override
public void onPaused() {
updateLog("onPaused()");
}
#Override
public void onPlaying() {
updateLog("onPlaying()");
}
#Override
public void onSeekTo(int arg0) {
updateLog("onSeekTo(): " + String.valueOf(arg0));
}
#Override
public void onStopped() {
updateLog("onStopped()");
}
}

Zbar add floating View

Ok, so, i want to make something like this:
http://postimg.org/image/qs3okxitf/
Now, im using zbarscannerview like this:
public class BarKodScreen extends AppCompatActivity implements ZBarScannerView.ResultHandler {
private ZBarScannerView mView;
private BarcodeFormat barcodeFormatEAN13, barcodeFormatEAN8;
private List<BarcodeFormat> listaZaFormat = new ArrayList<BarcodeFormat>();
private ImageView img;
private LinearLayout lejout;
private View kamera;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barkod);
mView = new ZBarScannerView(this);
lejout = (LinearLayout) findViewById(R.id.cameraPreview);
img = (ImageView) findViewById(R.id.cameraImageView);
kamera = (View) findViewById(R.id.zaKameru);
kamera = mView;
lejout.addView(kamera);
lejout.addView(kamera);
lejout.removeView(img);
lejout.addView(img);
barcodeFormatEAN13 = BarcodeFormat.EAN13;
barcodeFormatEAN8 = BarcodeFormat.EAN8;
listaZaFormat.add(barcodeFormatEAN13);
listaZaFormat.add(barcodeFormatEAN8);
mView.setFormats(listaZaFormat);
}
#Override
public void onResume() {
super.onResume();
mView.setResultHandler(this); // Register ourselves as a handler for scan results.
mView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
Log.v("GetCOntent", rawResult.getContents()); // Prints scan results
barKodZahtev(rawResult.getContents());
}
}
and my xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/cameraPreview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<View
android:id="#+id/zaKameru"
android:layout_width="match_parent"
android:layout_height="150dp"/>
<ImageView
android:id="#+id/cameraImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:alpha="0.6"
android:src="#drawable/share" />
</LinearLayout>
What I dont understand is how to add the image(text from the screenshot) as a child view for my zbarscannerView.
Check out their rapository on github, they have something there.

Categories

Resources