Add setOnClickListener on Android custom component - java

When making a custom component for Android, as far as I understood, I need:
one xml file with the layout for the component;
one java class.
Tried to make one, just for practice. Use two progressbars and one button in the XML, and create the class, than tried out in my main activity, worked fine.
But now I'm loking how to set OnClickListener on my button through the activity, and in this part I'm lost.
My loading_button.xml:
<merge
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RelativeLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="4dp"
android:progress="0"
android:id="#+id/pg_top" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/btn_ok"
android:background="#color/colorPrimary"
android:textColor="#ffffff"
android:layout_below="#+id/pg_top"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="5dp"
android:progress="0"
android:id="#+id/pg_bottom"
android:layout_below="#+id/btn_ok"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</merge>
Here the LoadingButton.java:
public class LoadingButton extends RelativeLayout{
private ProgressBar pbTop;
private ProgressBar pbBottom;
private Button btnOk;
private int pbTopProgress = 0;
private int pbBottomProgress = 0;
public LoadingButton(Context context, AttributeSet attrs) {
super(context, attrs);
View view = View.inflate(context, R.layout.loading_button, this);
btnOk = (Button) view.findViewById(R.id.btn_ok);
pbTop = (ProgressBar) view.findViewById(R.id.pg_top);
pbBottom = (ProgressBar) view.findViewById(R.id.pg_bottom);
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Doing stuff ok
}
});
}// LoadingButton
}
The setOnClickListener in the class works, but how can I set it from my main activity?
MainActivity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// My new component (it's id in activity_main.xml is 'lb')
LoadingButton lb = (LoadingButton) findViewById(R.id.lb);
// QUESTION - how to make something like this with btnOk:
lb.btnOkSetOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Do stuff
}
});
}
}
If this is possible, how?
If not, what is the right approach to make a custom component and set clickListeners on specific element of this component?

Best approach to handle all view click in LoadingButton (For custom view). And create interface.
public class LoadingButton extends RelativeLayout {
public interface OnLoadingButtonClickListener{
void onLoadingButtonClickListener();
}
private ProgressBar pbTop;
private ProgressBar pbBottom;
private Button btnOk;
private int pbTopProgress = 0;
private int pbBottomProgress = 0;
private OnLoadingButtonClickListener mONOnLoadingButtonClickListener;
public LoadingButton(Context context, AttributeSet attrs) {
super(context, attrs);
View view = View.inflate(context, R.layout.loading_button, this);
btnOk = (Button) view.findViewById(R.id.btn_ok);
pbTop = (ProgressBar) view.findViewById(R.id.pg_top);
pbBottom = (ProgressBar) view.findViewById(R.id.pg_bottom);
btnOk.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mONOnLoadingButtonClickListener != null){
mONOnLoadingButtonClickListener.onLoadingButtonClickListener();
}
}
});
}// LoadingButton
public void setOnLoadingClickListener(OnLoadingButtonClickListener onLoadingClickListener){
mONOnLoadingButtonClickListener = onLoadingClickListener;
}
}
And implement OnLoadingButtonClickListener in your activity.
public class MainActivity extends AppCompatActivity implements LoadingButton.OnLoadingButtonClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// My new component (it's id in activity_main.xml is 'lb')
LoadingButton lb = (LoadingButton) findViewById(R.id.lb);
lb.setOnLoadingClickListener(this);
}
#Override
public void onLoadingButtonClickListener() {
//do your stuff on ok button click
}
}

Override setOnClickListener(OnClickListener listener) in your custom Java class. Inside it, write:
btnOk.setOnClickListener(listener);
where listener is an argument of your custom view's setOnClickListener() function.
That will make your whole view clickable and click on your button will be performed. Of couse add android:clickable="true" to your custom view's root layout.

In the component
class Example #JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0,
defStyleRes: Int = 0) : ConstraintLayout(context, attrs, defStyle) {
var clickListener: () -> Unit = { }
init { }
private fun initListeners() {
binding.button.onClick {
clickListener()
}
}
In the activity / fragment
component.clickListener = { }
And the best part, you can send data on the component and receive it in the landa

Related

Add a dynamic button to the view and save it permanently

I have a fragment with this view:
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:tag="general"
android:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#343535"
android:orientation="vertical"
tools:context=".fragments.GeneralFragment">
<Button
android:id="#+id/hello"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/hello" />
<Button
android:id="#+id/observed"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/observed" />
<Button
android:id="#+id/thanks"
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="#string/thanks" />
</LinearLayout>
There are 3 buttons. Whenever you click on one of them, its text will be displayed.
Now I would like to add another button but dynamically. It should be added before #+id/hello.
I have tried it with
LinearLayout root = (LinearLayout) view.findViewById(R.id.root);
root.addView();
but it looks completely wrong since some parameters are missing.
For instance, the new button should be like:
XML:
<Button
android:layout_width="match_parent"
android:layout_height="60dp"
android:gravity="center_vertical"
android:onClick="onClick"
android:text="I am a dynamic text" />
This button should be saved permanently in the app. How can I do this?
Update
I am using a dialog, so this is the class:
#SuppressLint("ValidFragment")
public class Dialog extends DialogFragment {
private final int _layout;
private TextInputEditText _customTextField;
#SuppressLint("ValidFragment")
public Dialog(int layout) {
_layout = layout;
}
public interface ICustomTts {
void customTts(String input, Activity activity);
}
public ICustomTts iCustomTts;
public interface ITarget {
void getTarget(String input);
}
public ITarget iTarget;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(_layout, container, false);
// Display fragment_custom
if (_layout == R.layout.fragment_custom) {
_customTextField = view.findViewById(R.id.customTextField);
Button _customBtn = view.findViewById(R.id.customCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of custom");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iCustomTts.customTts(input, getActivity());
_dismiss();
}
}
});
MaterialCheckBox customeSave = view.findViewById(R.id.customSave);
customeSave.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View v) {
Log.d(TAG, "customeSave was clicked!");
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(getContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);
}
});
}
// Display fragment_target
if (_layout == R.layout.fragment_target) {
_customTextField = view.findViewById(R.id.targetTextField);
Button _customBtn = view.findViewById(R.id.targetCta);
_customBtn.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Clicked on CTA of target");
String input = _customTextField.getText().toString();
if (!input.equals("")) {
iTarget.getTarget(input);
_dismiss();
}
}
});
}
return view;
}
/**
* Dismissing the dialog
*/
private void _dismiss() {
this.dismiss();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
if (_layout == R.layout.fragment_custom) {
iCustomTts = (ICustomTts) getActivity();
}
else if (_layout == R.layout.fragment_target) {
iTarget = (ITarget) getActivity();
}
}
catch (ClassCastException e) {
Log.e(TAG, "onAttach: ClassCastException: " + e.getMessage());
}
}
}
You need to use the two-argument version of addView() to determine the order (index) of the button inside the LinearLayout:
LinearLayout root = view.findViewById(R.id.root);
Button button = new Button(requireContext());
float heightInPixel = 60 * getResources().getDisplayMetrics().density;
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) heightInPixel);
params.gravity = Gravity.CENTER;
button.setText("I am a dynamic text");
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Do the stuff on the click
}
});
root.addView(button, 0);

Floating action button not showing in bottomsheetfragment collapsed state

I have BottomSheetFragment with recyclerview and fab button. I am having issue in showing up Floating action button in BottomSheetBehavior.STATE_COLLAPSED. Fab button come up as soon as i expand bottom sheet to fullscreen i tried several method but none work.
I tried different fab option in layout to make it visible but no luck till now.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
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/topBarBottomSheet"
android:clipToPadding="true"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/topBarBottomSheet">
<include layout="#layout/progressbar_framelayout" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycleviewGallery"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:paddingTop="#dimen/list_item_spacing_half"
android:paddingBottom="#dimen/list_item_spacing_half"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:listitem="#layout/recycler_view_item_3"
tools:spanCount="3"
tools:layoutManager="GridLayoutManager" />
</FrameLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fabBottomSheet"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="16dp"
app:backgroundTint="#color/greenElaxer"
app:fabSize="normal"
app:srcCompat="#drawable/ic_check"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:overScrollMode="always"
>
</com.google.android.material.floatingactionbutton.FloatingActionButton>
</RelativeLayout>
BottomSheetFragment
public class BottomSheet extends BottomSheetDialogFragment {
FloatingActionButton fab;
RecyclerView recyclerView;
// TODO: Customize parameters
public static BottomSheet newInstance() {
/*final Bundle args = new Bundle();
args.putInt(ARG_ITEM_COUNT, itemCount);
fragment.setArguments(args);*/
return new BottomSheet();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bottemsheet_list_dialog, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
recyclerView = view.findViewById(R.id.recycleviewGallery);
fab = view.findViewById(R.id.fabBottomSheet);
BottomSheetAdapter bottomSheetAdapter = new BottomSheetAdapter();
GridLayoutManager gridLayoutManager=new GridLayoutManager(getActivity(),2);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setAdapter(bottomSheetAdapter);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialog) {
//Get the BottomSheetBehavior
BottomSheetDialog d = (BottomSheetDialog) dialog;
FrameLayout bottomSheet = d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
if (bottomSheet != null) {
bottomSheet.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
bottomSheet.setMinimumHeight(350);
bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View view, int i) {
switch (i){
case BottomSheetBehavior.STATE_COLLAPSED:
Log.d(TAG,"Collapsed");
break;
case BottomSheetBehavior.STATE_DRAGGING:
Log.d(TAG,"Dragging");
break;
case BottomSheetBehavior.STATE_EXPANDED:
Log.d(TAG,"Expanded");
break;
case BottomSheetBehavior.STATE_HALF_EXPANDED:
Log.d(TAG,"Half Expanded");
break;
case BottomSheetBehavior.STATE_HIDDEN:
Log.d(TAG,"Hidden");
dismiss();
break;
case BottomSheetBehavior.STATE_SETTLING:
Log.d(TAG,"Settling");
break;
}
}
#Override
public void onSlide(#NonNull View view, float v) {
}
});
}
}
});
return dialog;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
final Fragment parent = getParentFragment();
Log.d(TAG,"Parent = "+parent+" Context "+context);
if (parent != null) {
mListener = (Listener) parent;
} else {
mListener = (Listener) context;
}
}
#Override
public void onDetach() {
mListener = null;
super.onDetach();
}
}
Whenever i collapsed bottom sheet the fab button also make itself down with bottom sheet.i need to make my fab button stick to same place whether i expand or collapsed bottom sheet. Thanks in advance.
I need to stick to same layout(Relative layout)
You can't make an UI element from a certain fragment stick around when you're exiting that fragment. If a bottomsheet is collapsed, all its UI elements are collapsed. You can't make on stick around.
You could write a duplicate fab that shows after you closed the bottomsheet in the underlying fragment.
For example, I have this code in my bottomsheet to exit the bottomsheet dialog.
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mBottomSheetDialog.dismiss();
mTimePickerDialogController.show(0, 0, makeTimePickerDialogTag());
}});
When you dismiss the bottomsheet, you could use the following code to make a fab in the underlying fragment appear or disappear.
mFloatingActionButton.hide();
mFloatingActionButton.show();
Edit: A better solution for handling the second fab.
BottomSheetBehavior sheetBehavior;
sheetBehavior = BottomSheetBehavior.from(yourBottomSheet);
sheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
#Override
public void onStateChanged(#NonNull View bottomSheet, int newState) {
switch (newState) {
case BottomSheetBehavior.STATE_HIDDEN:
mFloatingActionButton.show();
case BottomSheetBehavior.STATE_EXPANDED: {
mFloatingActionButton.hide();
}
break;
case BottomSheetBehavior.STATE_COLLAPSED: {
mFloatingActionButton.show();
}
}
}

OnClickListener() crash in Fragment

For some reason, when I click on the Toolbar(toolbar) and Float button(button) in my app, the OnClickListener () method crashes the snippet and app
Although the ImageButton(OnOff) handler runs and does not crash the fragment
Fragment
public class ZnonkiFragment extends Fragment {
private SharedPreferences settings;
private ImageButton OnOff;
private ViewPager viewPager;
private DrawerLayout drawerLayout;
private MainActivity.PagerAdapter pagerAdapter;
private FloatingActionButton button;
final Context context = getActivity();
private androidx.appcompat.widget.Toolbar toolbar;
private TabLayout tabLayout;
private String ZvonOne, ZvonTwo;
private List<Fragment> list = new ArrayList<>();
private String url;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_znonki, container,
toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.menu));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context,"lel",Toast.LENGTH_LONG).show();
}
});
//...
addListenerOnButton(view);
return view;
}
public boolean checkString(String string) {
try {
Integer.parseInt(string);
} catch (Exception e) {
return false;
}
return true;
}
public void addListenerOnButton (final View viewOne){
OnOff = viewOne.findViewById(R.id.onOff);
button = viewOne.findViewById(R.id.floatingActionButton);
OnOff.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//...
});
button.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
//...
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//...
});
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ZnonkiFragment">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="?attr/actionBarTheme"
app:title="Звонки"
app:titleTextColor="#FFFFFF" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/floatingActionButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|right"
android:layout_margin="16dp"
android:clickable="true"
android:focusable="true"
app:backgroundTint="#color/colorAccent"
app:backgroundTintMode="src_atop"
app:srcCompat="#drawable/kek" />
<com.google.android.material.tabs.TabLayout
android:id="#+id/tabLayout4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:isScrollContainer="true"
app:tabIndicatorColor="#android:color/white"
app:tabIndicatorHeight="6dp"
app:tabMode="scrollable"
app:tabSelectedTextColor="#android:color/white"
app:tabTextColor="#E6E6FA">
</com.google.android.material.tabs.TabLayout>
<ImageButton
android:layout_margin="16dp"
android:id="#+id/onOff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="#null"
app:srcCompat="#drawable/on" />
<androidx.viewpager.widget.ViewPager
android:id="#+id/rager"
android:layout_width="match_parent"
android:layout_height="557dp"
android:layout_marginTop="105dp"
/>
</FrameLayout>
Although this code worked in the main activiti
I don't know why but there are no errors in debug mode
What Kundan has suggested is correct but the fix is much easier.
You don't need this:
final Context context = getActivity();
If you need to gain access to the context in a Fragment you can call requireContext() if you need access to the Activity you can call requireActivity()
So your toast message can become:
Toast.makeText(requireContext(),"lel",Toast.LENGTH_LONG).show();
I think main cause of this issue is
final Context context = getActivity();
which is used in
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context,"lel",Toast.LENGTH_LONG).show();
}
});
please note the getActivity() method returns the current activity with which this fragment is attached. and you are calling while the fragment object is creating before it is attached to activity.
you can change the above code to :
Context context;
and override the method as
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
Hope this answers your question.
The solution is simple
In your fragment class file, dont create custom function for calling click events rather you can use the android's defaul method by simply implementing them in your class file and then override it. Thats makes the code more simpler and reusable in future.
public class ZnonkiFragment extends Fragment implements View.OnClickListener, View.OnLongClickListener {
private SharedPreferences settings;
private ImageButton OnOff;
private ViewPager viewPager;
private DrawerLayout drawerLayout;
private FloatingActionButton button;
final Context context = getActivity();
private TabLayout tabLayout;
private String ZvonOne, ZvonTwo;
private List<Fragment> list = new ArrayList<>();
private String url;
private Toolbar mToolbar;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_znonki, container, false);
mToolbar = view.findViewById(R.id.toolbar);
mToolbar.setNavigationIcon(getResources().getDrawable(R.drawable.ic_launcher_background));
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, "lel", Toast.LENGTH_LONG).show();
}
});
//...
OnOff = view.findViewById(R.id.onOff);
OnOff.setOnClickListener(this);
OnOff.setOnLongClickListener(this);
button = view.findViewById(R.id.floatingActionButton);
return view;
}
public boolean checkString(String string) {
try {
Integer.parseInt(string);
} catch (Exception e) {
return false;
}
return true;
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.onOff:
//call your onclick function here...
break;
case R.id.floatingActionButton:
//call your onclick function here...
break;
}
}
#Override
public boolean onLongClick(View view) {
switch (view.getId()) {
case R.id.floatingActionButton:
//call your long click function here...
break;
}
return false;
}
}
I have left comments on particular Loc where you can add your code and check it. And the toolbar was crashing due to improper importing of the libraries. If you havent used the androidx library into your gradle file then you can go with simple toolbar which is of "import android.support.v7.widget.Toolbar". This will surely stop your onclick crash on toolbar.
If there is any issue, just let me know. Thank you.

How to disable Touch while video is playing

I am developing a Toddler(kids) app in which I have shown the YouTube videos thumbnails in a recyclerview and whenever the user clicks on any of the listed thumbnails that video plays in full screen YouTube intent( and all the videos after that plays in order automatically). I am succeed in doing so. The problem is now I want to disable the touch screen while the video is playing. I thought of making transparent layout and to show this transparent layout as upper layer on YouTube Full screen video intent but i dont know how to attach this layout with Youtube video intent.
Every kind of help is appreciated.
below is my code:
main_activity.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="2"
android:orientation="vertical"
tools:context="com.example.pc.fkidshell.Main4Activity">
<include layout="#layout/toolbar"
android:id="#+id/my_thirdtoolbar"/>
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/VideoList"
android:layout_below="#+id/my_thirdtoolbar"
android:paddingTop="20dp"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
video_row.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/thumbnailView"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
mainactivity.javaL
public class Main4Activity extends AppCompatActivity implements YouTubeThumbnailView.OnInitializedListener, YouTubeThumbnailLoader.OnThumbnailLoadedListener{
Toolbar third_toolbar;
YouTubeThumbnailView thumbnailView;
YouTubeThumbnailLoader thumbnailLoader;
RecyclerView VideoList;
RecyclerView.Adapter adapter;
List<Drawable> thumbnailViews;
List<String> VideoId;
String videoid;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main4);
third_toolbar = (Toolbar) findViewById(R.id.my_thirdtoolbar);
setSupportActionBar(third_toolbar);
getSupportActionBar().setTitle(R.string.sectitle);
getSupportActionBar().setIcon(R.drawable.tblogo);
thumbnailViews = new ArrayList<>();
VideoList = (RecyclerView) findViewById(R.id.VideoList);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(this);
VideoList.setLayoutManager(layoutManager);
adapter=new VideoListAdapter();
VideoList.setAdapter(adapter);
VideoId = new ArrayList<>();
thumbnailView = new YouTubeThumbnailView(this);
thumbnailView.initialize("API key", this);
}
#Override
public void onInitializationSuccess(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader youTubeThumbnailLoader) {
thumbnailLoader = youTubeThumbnailLoader;
youTubeThumbnailLoader.setOnThumbnailLoadedListener(Main4Activity.this);
thumbnailLoader.setPlaylist("PLXRActLQ03oY_6AQb-5EMuKFYQA_fDE40");
}
#Override
public void onInitializationFailure(YouTubeThumbnailView youTubeThumbnailView, YouTubeInitializationResult youTubeInitializationResult) {
}
public void add() {
adapter.notifyDataSetChanged();
if (thumbnailLoader.hasNext())
thumbnailLoader.next();
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView youTubeThumbnailView, String s) {
thumbnailViews.add(youTubeThumbnailView.getDrawable());
VideoId.add(s);
add();
}
#Override
public void onThumbnailError(YouTubeThumbnailView youTubeThumbnailView, YouTubeThumbnailLoader.ErrorReason errorReason) {
}
public class VideoListAdapter extends RecyclerView.Adapter<VideoListAdapter.MyView>{
public class MyView extends RecyclerView.ViewHolder{
ImageView imageView;
public MyView(View itemView) {
super(itemView);
imageView= (ImageView) itemView.findViewById(R.id.thumbnailView);
}
}
#Override
public VideoListAdapter.MyView onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.video_row, parent, false);
return new MyView(itemView);
}
#Override
public void onBindViewHolder(VideoListAdapter.MyView holder, final int position) {
holder.imageView.setImageDrawable(thumbnailViews.get(position));
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
videoid=VideoId.get(position);
//startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v="+videoid+"&list=PLXRActLQ03oY_6AQb-5EMuKFYQA_fDE40")));
Intent intent=new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.youtube.com/watch?v="+videoid+"&index="+position+"&list=PLXRActLQ03oY_6AQb-5EMuKFYQA_fDE40"));
intent.putExtra("force_fullscreen",true);
startActivity(intent);
// Intent intenwt=YouTubeIntents.createPlayVideoIntent(Main4Activity.this,VideoId.get(position));
// intent.putExtra("force_fullscreen",true);
//startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return thumbnailViews.size();
}
}
}
Try with following this will help you
https://stackoverflow.com/a/28429348/7234534
As stated in this thread, this is impossible as you cannot override the home button even if it is soft or hard button. However, you can use third party apps like Untouch which is a very popular one, and can be found in the play store. (Search for Untouch or touch block and it should come up.) You may also check on this blog that discussed some workaround for your issue. Hope this helps!

Android - Saving Dynamically generated TextViews

I'm trying to make a To Do List app. When the screen rotates, all of the dynamically added textviews get removed. The textviews get added into a LinearLayout within a linearlayout, right above the add button.
MainActivity.Java
public class MainActivity extends Activity {
private LinearLayout mLayout;
private LinearLayout ListItems;
static final String counter_value = "int_value";
static final String toDoList_value = "toDolist";
private EditText mEditText;
private Button mButton;
private int counter;
private ArrayList<String> toDoList;
private ArrayList<String> keys;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//This makes it so that the keyboard appears only after you tap the EditText. Stackoverflow question by fixEdd Android on-screen keyboard auto popping up
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
// end code
if (toDoList != null){
System.out.println("Success!");
for(int i = 0; i< toDoList.size(); i++){
System.out.println(toDoList.get(i));
ListItems.addView(createNewTextView(toDoList.get(i)));
}
}
else{
System.out.println("Nope!");
toDoList = new ArrayList<String>();
}
counter = 1;
mLayout = (LinearLayout) findViewById(R.id.linearLayout);
ListItems = (LinearLayout) findViewById(R.id.listItems);
mEditText = (EditText) findViewById(R.id.editText);
mButton = (Button) findViewById(R.id.button);
mButton.setOnClickListener(onClick());
TextView textView = new TextView(this);
textView.setText("New text");
}
private View.OnClickListener onClick() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
ListItems.addView(createNewTextView(mEditText.getText().toString()));
}
};
}
private TextView createNewTextView(String text) {
final RadioGroup.LayoutParams lparams = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
final TextView textView = new TextView(this);
textView.setLayoutParams(lparams);
textView.setFreezesText(true);
textView.setText(counter + ":" + text);
textView.setId(counter);
System.out.println(textView.getId());
toDoList.add(text);
counter++;
return textView;
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt(counter_value);
toDoList = savedInstanceState.getStringArrayList("key");
//REad values from the savedInstanceState" -object and put them in your textview
}
#Override
protected void onSaveInstanceState(Bundle outState){
// Save the values you need from your textview into "outSTate" -object
// outState.putParcelableArrayList("key", toDoList);
outState.putInt(counter_value, counter);
outState.putStringArrayList("key", toDoList);
super.onSaveInstanceState(outState);
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/linearLayout"
android:weightSum="1">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:id="#+id/listItems"></LinearLayout>
<EditText
android:id="#+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add+"
/>
</LinearLayout>
Also I am not sure if readding the views is the best way to do this. It seems like it's a waste of operations. Is there a way to just keep the textviews in place?
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
counter = savedInstanceState.getInt(counter_value);
toDoList = savedInstanceState.getStringArrayList("key");
// Add this for-loop to restoring your list
for(String str : toDoList){
ListItems.addView(createNewTextView(str));
}
}
However, in my opinion, this is not a good approach. It's better to use a ListView
It's better if you implement your To Do list using a ListView with its Adapter. There are plenty of tutorials on the web, start for example from this one.

Categories

Resources