I have two fragments which have a lot in common. Therefore, I have an abstract fragment with an "abstract" layout file for this, which is included in the other two layout files.
However, I am not sure, how to use Jetpack View Binding for the abstract fragment, because I don't know which layout file is used.
Here a simplified example of my problem:
Abstract fragment (ExampleAbstractFragment.kt):
abstract class ExampleAbstractFragment : Fragment() {
override fun doSomething() {
val abstractTextView = findViewById<TextView>(R.id.abstract_text_view)
// ^^ How to get this with View Binding
val abstractButton = findViewById<Button>(R.id.abstract_button)
// ^^ How to get this with View Binding
}
}
Layout file of abstract fragment (fragment_example_abstract.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/abstract_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/test" />
<Button
android:id="#+id/abstract_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/test" />
</LinearLayout>
--
First fragment (ExampleFragmentA.kt):
class ExampleFragmentA : ExampleAbstractFragment() {
private var _binding: FragmentAExampleBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentAExampleBinding?.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun doSomething() {
val textView = binding.fragmentAExampleTextView
val button = binding.fragmentAExampleButton
}
}
Layout file of first fragment (fragment_a_example.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/fragment_a_example_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/test" />
<include
layout="#layout/fragment_example_abstract"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/fragment_a_example_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/test" />
</LinearLayout>
--
Second fragment (ExampleFragmentB.kt):
class ExampleFragmentB : ExampleAbstractFragment() {
private var _binding: FragmentBExampleBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentBExampleBinding?.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun doSomething() {
val editText = binding.fragmentBExampleEditText
val imageView = binding.fragmentBExampleImageView
}
}
Layout file of second fragment (fragment_b_example.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:id="#+id/fragment_b_example_edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/test" />
<include
layout="#layout/fragment_example_abstract"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/fragment_b_image_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/test" />
</LinearLayout>
Related
I am trying to open a fragment by clicking on floating action button using material container transform animation. I have implemented the animation but it is not working as I expected.
When navigating from one fragment A to Fragment B, the floating action button is still visible (enlarged for a brief second) when Fragment B is being opened.
What changes do I make in the animation so that the transition from floating action button to Fragment B feels more smooth? or How do I hide the enlarged floating action button when navigating to Fragment B?
Below is the code of Fragments and layouts for reference.
Fragment A layout:
<androidx.coordinatorlayout.widget.CoordinatorLayout 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=".ui.home.HomeFragment">
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/create_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:transitionName="my_transition"
android:src="#drawable/ic_round_add_24"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/dimen_16"
android:contentDescription="New Task"
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Fragment A code:
class FragmentA : Fragment() {
private var _binding: FragmentABinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
exitTransition = Hold()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentABinding.inflate(inflater)
binding.createTask.setOnClickListener {
val extras = FragmentNavigatorExtras(binding.createTask to "my_transition")
findNavController().navigate(R.id.action_FragmentA_to_FragmentB,null,null,extras)
}
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
Fragment B layout:
<androidx.coordinatorlayout.widget.CoordinatorLayout 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"
android:transitionName="my_transition"
tools:context=".ui.edit.EditTaskFragment">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="#dimen/toolbar_size"
app:liftOnScroll="true">
<FrameLayout
android:layout_width="match_parent"
android:paddingHorizontal="#dimen/dimen_16"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_baseline_close_24"
android:background="?attr/selectableItemBackgroundBorderless"
android:layout_gravity="start|center_vertical"
app:tint="?attr/colorPrimary" />
<com.google.android.material.button.MaterialButton
android:id="#+id/save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|center_vertical"
style="#style/Widget.Material3.Button.TonalButton"
android:text="Save"
android:minWidth="0dp"
android:minHeight="0dp"/>
</FrameLayout>
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textAppearance="#style/TextAppearance.Material3.HeadlineSmall"
android:textAlignment="center"
android:text="This is new Fragment"/>
</androidx.core.widget.NestedScrollView>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
Fragment B code:
class FragmentB : Fragment() {
private var _binding: FragmentBBinding? = null
private val binding get() = _binding!!
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedElementEnterTransition = MaterialContainerTransform()
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentBBinding.inflate(inflater)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
Solved the problem!!
Just set startContainerColor and endContainerColor parameter in materialContainerTransform to surface color and then the fab transition is done more smoothly
Replace sharedElementEnterTransition in FragmentB with this:
sharedElementEnterTransition = MaterialContainerTransform().apply {
startContainerColor = requireContext().getColorFromAttr(com.google.android.material.R.attr.colorSurface)
endContainerColor = requireContext().getColorFromAttr(com.google.android.material.R.attr.colorSurface)
}
I am implementing a dialog and have a question. I set a timer for 10minutes. For 10 minutes, users cannot use the application. They can only see a dialog that tells them how long it is left. When they terminate and restart the application, they can only see the same dialog. How can I prevent a dialog from closing or show it again when a user restarts the application?
Thanks for the help.
My layout
<?xml version="1.0" encoding="utf-8"?>
<layout 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">
<data>
<variable
name="viewModel"
type="com.OtpTimeLimitViewModel" />
</data>
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/my_information_button">
<androidx.constraintlayout.widget.ConstraintLayout
android:id="#+id/layout_wrapper"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="15dp"
android:layout_marginBottom="20dp"
android:orientation="horizontal"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/title_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="message1"
android:textColor="#android:color/white"
android:textSize="#dimen/text_size_tab_bar"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/content_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center_vertical"
android:text="message2"
android:textColor="#color/dark_gray"
android:textSize="#dimen/text_size_helper"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/title_text" />
<androidx.appcompat.widget.AppCompatTextView
android:id="#+id/timeLimit_timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:text="#{viewModel.timeLimit}"
android:textColor="#color/white"
android:textSize="40sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/content_text" />
</androidx.constraintlayout.widget.ConstraintLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
Fragment
class OtpTimeLimitFragment : DialogFragment() {
private lateinit var binding: DialogOtpLimitBinding
private lateinit var viewModel: OtpTimeLimitViewModel
private lateinit var mContext: MainActivity
private val args : AgreementViewDialogArgs by navArgs()
override fun onAttach(context: Context) {
super.onAttach(context)
mContext = context as MainActivity
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(inflater, R.layout.dialog_otp_limit, container, false)
dialog?.setCanceledOnTouchOutside(false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.lifecycleOwner = viewLifecycleOwner
viewModel = ViewModelProvider(this).get(OtpTimeLimitViewModel::class.java)
binding.viewModel = viewModel
}
}
Here's a rough example of what you need to do :
First of all, Store value like this :
var pref: SharedPreferences? = requireContext().getSharedPreferences("otpTrialLimit", MODE_PRIVATE)
pref?.edit()?.putLong("endTime", endTime)
pref?.edit()?.commit()
When user reopens the application then in
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.lifecycleOwner = viewLifecycleOwner
viewModel = ViewModelProvider(this).get(OtpTimeLimitViewModel::class.java)
binding.viewModel = viewModel
val sharedPreference = getSharedPreferences("otpTrialLimit",Context.MODE_PRIVATE)
sharedPreference.getLong("endTime", 0)
if(System.currentTimeMillis() < endTime){
//Show dialog here
}
}
In MainActivity.kt, add the button function, it can't run.
How to solve?
Thank!
add the button function, it can't run.
binding.button1.setOnClickListener {
binding.text.text = "123"
}
drive.google.com
Source code
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:backgroundTint="#702020" />
<TextView
android:id="#+id/text"
android:text="text"
android:textSize="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<fragment
android:id="#+id/nav_host_fragment"
android:name="com.android.myapplication.Fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_"
/>
</LinearLayout>
fragment_.xml
<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"
tools:context=".Fragment">
</FrameLayout>
MainActivity.kt
class MainActivity : AppCompatActivity() {
val binding: ActivityMainBinding by viewbind()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
binding.button1.setOnClickListener {
binding.text.text = "123"
}
}
}
Fragment.kt
class Fragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_, container, false)
}
error code
enter image description here
Add below Gradle dependency
implementation "androidx.fragment:fragment-ktx:1.3.1"
Replace <fragment> with following code
<androidx.fragment.app.FragmentContainerView
android:id="#+id/nav_host_fragment"
android:name="com.android.myapplication.Fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout="#layout/fragment_" />
another replace in MainActivity.kt
class MainActivity : AppCompatActivity() {
val binding: ActivityMainBinding by viewbind()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.add(R.id.nav_host_fragment, com.android.myapplication.Fragment())
fragmentTransaction.show(com.android.myapplication.Fragment())
fragmentTransaction.commit()
binding.button1.setOnClickListener {
binding.text.text = "123"
}
Here's my XML Fragment:
fragment_leaderboards.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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"
android:background="#color/colorPrimary">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/leaderboards_list"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
and my custom view for the LayoutInflater of the ViewHolder:
leaderboard_item.xml
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/white"
android:baselineAligned="false"
android:orientation="horizontal"
android:padding="5dp">
<TextView
android:id="#+id/leaderboard_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:layout_weight="1"
android:text="Title"
android:textColor="#000000"
android:textSize="18sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/imgShare"
android:layout_width="30dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:src="#android:drawable/ic_menu_share"
android:tint="#eeeeee"/>
</LinearLayout>
The above XML will only show 1 item of my RecyclerView. It will also show only 1 item of RecyclerView if I put the CardView inside the LinearLayout: <LinearLayout><Cardview>...</Cardview></LinearLayout>
However, if I wrap the LinearLayoutin a CardView, it will show all items (which is 2 at the moment): <Cardview><LinearLayout>...</LinearLayout></Cardview>.
Why is this?
Here's my Kotlin code if you're curious:
fragment
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_leaderboards, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val viewManager: RecyclerView.LayoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
val viewAdapter: RecyclerView.Adapter<*> = LeaderboardsAdapter(arrayListOf(Player("James", 23, "male"), Player("Jane", 22, "female")))
val recyclerView: RecyclerView = leaderboards_list.apply {
adapter = viewAdapter
layoutManager = viewManager
setHasFixedSize(true)
}
}
LeaderboardsAdapter.kt
class LeaderboardsAdapter(private val players: ArrayList<Player>) : RecyclerView.Adapter<LeaderboardsAdapter.ViewHolder>(){
class ViewHolder(val v: View) : RecyclerView.ViewHolder(v)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LeaderboardsAdapter.ViewHolder {
Log.d("Viewgroup", "$parent.toString() $parent.")
val view = LayoutInflater.from(parent.context).inflate(R.layout.leaderboard_item, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: LeaderboardsAdapter.ViewHolder, position: Int) {
holder.v.leaderboard_name.text = players[position].name
}
override fun getItemCount(): Int = players.size
}
My LinearLayout had android:layout_height="match_parent" so the 1 item was taking up the whole screen - that was the problem.
Exactly, either you can set android:layout_height="wrap_content" or fix height as per your view requirement. See this is very common among android developers. Good Luck for next time.
I am an amateur to both, android studio and kotlin. I am implementing a scenario where I have some fragments, as and when we finish with one fragment, the progress is shown on the main layout. These fragments replace the main frame layout and switching from one fragment to next is done in the previous fragment using the setonclicklistener. However, the problem is that I am unable to see the update happening to the progressbar. By the way, I am not using any progress dialogue. All I need is to update the progress bar as I switch from one fragment to another. When I run the App, it doesn't crash but the update doesn't happen. The main_layout file as given below and the frame layout is replaced by the fragments.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/parentmain_progress"
android:layout_width="match_parent"
android:layout_height="25dp"
style="#style/Base.Widget.AppCompat.ProgressBar.Horizontal"
android:scaleY="2"/>
<FrameLayout
android:id="#+id/parentmain_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/parentmain_progress">
</FrameLayout>
</RelativeLayout>
One of the fragments where the progress is not updated:
class ParentChildInfoFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_parent_info_relation, container, false)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
headerparentrelation_text?.text= arguments?.getString("name")
parentmain_progress?.max=4
parentmain_progress?.setProgress(3)
val string = "Your Cild is a....\n Girl/Boy"
specifying_relation_txt?.text = string
relation_mom_image?.setImageResource(R.drawable.girl)
relation_dad_image?.setImageResource(R.drawable.boy)
val girlstring = "Girl"
mom_txt?.text = girlstring
val boystring = "Boy"
dad_txt?.text=boystring
nextbtn_parentrelation.setOnClickListener {
fragmentManager?.beginTransaction()?.replace(R.id.parentmain_frame,ParentInfoFragment())?.commit()
}
}
}
Any help appreciated.
Like that ?
On this example I use the new package structure : Androidx
If you do not use it yet, simply change
import androidx.fragment.app.FragmentTransaction
by
import android.app.FragmentTransaction
You will find the code on this deposit :
https://github.com/Amadou19/Android-Multiple-fragment-with-progressBar---Kotlin.git
/****************************/
fragment1.xml
/****************************/
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#c15d5d">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="30sp"
android:text="Fragment 1"/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Click Me"/>
</RelativeLayout>
/****************************/
Fragment1
/****************************/
class Fragment1 : Fragment() {
interface Fragment1Listner {
fun onClickFragment1()
}
var a1: Fragment1Listner? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment1, container, false)
view.findViewById<Button>(R.id.button).setOnClickListener {
Toast.makeText(activity, "Clicked", Toast.LENGTH_SHORT).show()
a1?.onClickFragment1()
}
return view
}
}
/****************************/
fragment2.xml
/****************************/
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#5d80c1">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="30sp"
android:text="Fragment 2"/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Click Me"/>
</RelativeLayout>
/****************************/
Fragment2
/****************************/
class Fragment2 : Fragment() {
interface Fragment2Listner {
fun onClickFragment2()
}
var a2: Fragment2Listner? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment2, container, false)
view.findViewById<Button>(R.id.button2).setOnClickListener {
Toast.makeText(activity, "Clicked", Toast.LENGTH_SHORT).show()
a2?.onClickFragment2()
}
return view }
}
/****************************/
fragment3.xml
/****************************/
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fab049">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="30sp"
android:text="Fragment 3"/>
</RelativeLayout>
/****************************/
Fragment3
/****************************/
class Fragment3 : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment3, container, false)
return view }
}
/****************************/
activity_main.xml
/****************************/
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.amadoutirera.progressbar2.MainActivity">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/Base.Widget.AppCompat.ProgressBar.Horizontal" />
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/progress_bar"/>
</RelativeLayout>
/****************************/
MainActivity
/****************************/
class MainActivity : AppCompatActivity(), Fragment1.Fragment1Listner, Fragment2.Fragment2Listner {
lateinit var progressBar : ProgressBar
private lateinit var fragment1: Fragment1
private lateinit var fragment2: Fragment2
private lateinit var fragment3: Fragment3
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/*------------------------------------------*/
progressBar = findViewById<ProgressBar>(R.id.progress_bar)
progressBar.max = 90
progressBar.progress = 30
/*------------------------------------------*/
fragment1 = Fragment1()
fragment2 = Fragment2()
fragment3 = Fragment3()
/*------------------------------------------*/
fragment1.a1 = this
fragment2.a2 = this
/*------------------------------------------*/
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment1)
.commit()
}
/*--------------- Onclik interface implementation -------------------*/
override fun onClickFragment1() {
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment2)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit()
progressBar.incrementProgressBy(30)
}
override fun onClickFragment2() {
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment3)
.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
.addToBackStack(null)
.commit()
progressBar.incrementProgressBy(30)
}
/*------------------------------------------*/
override fun onBackPressed() {
super.onBackPressed()
if(progressBar.progress ==60 || progressBar.progress ==90) progressBar.incrementProgressBy(-30)
}
}
try to Put your code in onCreateView() method.
Hope it works!!
Try
parentmain_progress?.post({
parentmain_progress?.progress = 3
})
instead of parentmain_progress?.setProgress(3)