How to persist a View across Activities in Android

前端 未结 5 1405
遇见更好的自我
遇见更好的自我 2021-02-03 15:43

I\'m working on an Android application and I\'d like to maintain a top-bar of sorts in most of my Activities, as per the Twitter and Facebook applications. How is this done? I\'

相关标签:
5条回答
  • 2021-02-03 16:11

    I have some issues with the syntax highlight, but tried to provide an example of how to complete similar task:

    http://illusionsandroid.blogspot.com/2011/02/android-custom-tab-bar.html

    0 讨论(0)
  • 2021-02-03 16:13

    I think your best bet would be to define a custom view and re-use it wherever needed. Though I don't think you'd technically have the same instance across activities, you can produce the illusion by updating it whenever necessary. (Perhaps in the onResume() method of each activity.) To save the data you can use SharedPreferences, which do persist across activities in an application, and even between instances of the particular application.

    0 讨论(0)
  • 2021-02-03 16:14

    Break the title bar out into a separate layout, and use the include xml tag. I do that in a few of my apps. Each of your activities can inherit from a Base Activity that contains events for the included layout, e.g. if the title bar has buttons.

    Example pseudocode below.

    title.xml

    <LinearLayout>
    <TextView text="Some text"/><Button text="Some Button" onCLick="buttonClick"/>
    </LinearLayout>
    

    activity layouts for each layout

    <RelativeLayout>
        <include  layout="@layout/title" />
    </RelativeLayout>
    

    BaseActivity

    public class BaseActivity extends Activity {
         public void buttonClick(View v) {
              // do something interesting.
         }
    }
    
    public class OtherActivity extends BaseActivity {}
    
    0 讨论(0)
  • 2021-02-03 16:24

    Check out:

    • the include XML element
    • Layout Tricks: Creating Reusable UI Components
    0 讨论(0)
  • 2021-02-03 16:34

    GreenDroid has an excellent toolbar which I've found to be very useful, extensible and easy to implement (and its open source to boot).

    https://github.com/cyrilmottier/GreenDroid

    0 讨论(0)
提交回复
热议问题