在android中使用BaseActivity的不同活动中的通用标题

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11579635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 08:08:02  来源:igfitidea点击:

Common Header in different activities using BaseActivity in android

androidandroid-layoutextends

提问by ADB

I want write code once and use in different activities. I have created a Base Activity classfor that . Also the header of all the layouts in different activities are same. I have done that with the help of the <include layout >tag.

我想编写一次代码并在不同的活动中使用。我Base Activity class为此创建了一个. 不同活动中所有布局的标题也是相同的。我在<include layout >标签的帮助下做到了这一点。

Now the Problem is my BaseActivitycode is not running. I am trying this first time se don't have much idea about that.

现在问题是我的BaseActivity代码没有运行。我第一次尝试,对此我不太了解。

1.)The BaseActivity code is below :

1.) BaseActivity 代码如下:

package com.waheguru.app;

import android.R.integer;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.Toast;

public abstract class BaseActivityMenu extends Activity {
    //action id
    private static final int ID_UP     = 1;
    private static final int ID_DOWN   = 2;
    private static final int ID_SEARCH = 3;
    private static final int ID_INFO   = 4;
    private static final int ID_ERASE  = 5; 
    private static final int ID_OK     = 6;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.header);

        ActionItem nextItem     = new ActionItem(ID_DOWN, "Book", getResources().getDrawable(R.drawable.menu_down_arrow));
        ActionItem prevItem     = new ActionItem(ID_UP, "Bookmark", getResources().getDrawable(R.drawable.menu_up_arrow));
        ActionItem searchItem   = new ActionItem(ID_SEARCH, "Find", getResources().getDrawable(R.drawable.menu_search));
        ActionItem infoItem     = new ActionItem(ID_INFO, "Info", getResources().getDrawable(R.drawable.menu_info));
        ActionItem eraseItem    = new ActionItem(ID_ERASE, "Clear", getResources().getDrawable(R.drawable.menu_eraser));
        ActionItem okItem       = new ActionItem(ID_OK, "OK", getResources().getDrawable(R.drawable.menu_ok));

        //use setSticky(true) to disable QuickAction dialog being dismissed after an item is clicked
        prevItem.setSticky(true);
        nextItem.setSticky(true);

        //create QuickAction. Use QuickAction.VERTICAL or QuickAction.HORIZONTAL param to define layout 
        //orientation
        final QuickAction quickAction = new QuickAction(this, QuickAction.VERTICAL);

        //add action items into QuickAction
        quickAction.addActionItem(nextItem);
        quickAction.addActionItem(prevItem);
        quickAction.addActionItem(searchItem);
        quickAction.addActionItem(infoItem);
        quickAction.addActionItem(eraseItem);
        quickAction.addActionItem(okItem);

        //Set listener for action item clicked
        quickAction.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {          
            public void onItemClick(QuickAction source, int pos, int actionId) {                
                ActionItem actionItem = quickAction.getActionItem(pos);

                //here we can filter which action item was clicked with pos or actionId parameter
                if (actionId == ID_SEARCH) {
                    Toast.makeText(getApplicationContext(), "Let's do some search action", Toast.LENGTH_SHORT).show();
                } else if (actionId == ID_INFO) {
                    Toast.makeText(getApplicationContext(), "I have no info this time", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), actionItem.getTitle() + " selected", Toast.LENGTH_SHORT).show();
                }
            }
        });

        //set listnener for on dismiss event, this listener will be called only if QuickAction dialog was dismissed
        //by clicking the area outside the dialog.
        quickAction.setOnDismissListener(new QuickAction.OnDismissListener() {          
            public void onDismiss() {
                Toast.makeText(getApplicationContext(), "Dismissed", Toast.LENGTH_SHORT).show();
            }
        });
        Button books=(Button)findViewById(R.id.book);
        books.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                Intent intent=new Intent(ExampleActivity.this,List_of_books.class);
                startActivityForResult(intent, 0);
            }
        });
        //show on btn1
        Button btn1 = (Button) this.findViewById(R.id.menu);
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                quickAction.show(v);
            }
        });
    }
}

2.) The Activity extended the Base Activity

2.) Activity扩展了Base Activity

package com.waheguru.app;

import android.app.Activity;
import android.os.Bundle;

public class ABCActivity extends BaseActivityMenu  {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
    }
}

So can any one help me where I am doing something wrong.

因此,任何人都可以帮助我做错了什么。

回答by Kevin Adesara

For this you have to create one header.xml which will be included in each and every layout for your activities as follows

为此,您必须创建一个 header.xml,它将包含在您的活动的每个布局中,如下所示

header.xml

头文件

<RelativeLayout>
  <TextView android:id="@+id/txtHeading"
      .... />
</RelativeLayout>

activity_main.xml

活动_main.xml

<RelativeLayout>
  <!-- include your header here -->
  <include layout="@layout/header"
     ... />

  <!-- Rest of your views -->

</RelativeLayout>

BaseActivity

基本活动

abstract class BaseActivity extends Activity {
  protected TextView txtHeading;
  public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
  }


  protected void setHeading(int resId) {
     if(txtHeading == null)
     txtHeading = findViewById(R.id.txtHeading);
     if(txtHeading != null)
       txtHeading.setText(resId);
  }
}

MainActivity

主要活动

class MainActivity extends BaseActivity {
   public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      setHeading(R.string.heading_main);
   }
}

You can put as many views you want and manage common things in BaseActivity or BaseListActivity.

您可以放置​​任意数量的视图,并在 BaseActivity 或 BaseListActivity 中管理常见的事物。

回答by Niko

If you are making inheritance with activities and your base activity calls setContentView and after that the real activity calls setContentView the last call will set the layout for activity. So if you are looking for a solution where all activies have the same header component the are 2 ways.

如果您正在对活动进行继承,并且您的基本活动调用 setContentView,然后实际活动调用 setContentView,最后一次调用将为活动设置布局。因此,如果您正在寻找一种所有活动都具有相同标头组件的解决方案,则有两种方法。

  1. For each activity layout xml you include that component

  2. -You make function for baseActivity e.g. setContent(int layout_id) -You call that with your activity always. -Baseactivity inflates a root view with header and inflates layout_id view to that layout. -Then calls the actual setContentView with that component.

  1. 对于每个活动布局 xml,您都包含该组件

  2. - 你为 baseActivity 制作函数,例如 setContent(int layout_id) - 你总是用你的活动来调用它。-Baseactivity 将带有标题的根视图膨胀并将 layout_id 视图膨胀到该布局。- 然后使用该组件调用实际的 setContentView。

回答by Ankitkumar Makwana

I think you should achieve it using Fragment, this may helps you.

我认为您应该使用 来实现它Fragment,这可能会对您有所帮助。

1 - in main.xml, add:

1 - 在main.xml,添加:

<fragment
    android:id="@+id/header"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    class="com.package.name.HeaderPanel" />

//remaining is same 

2 - the BaseActivitywhich extends FragmentActivity:

2 -BaseActivity延伸FragmentActivity

public class BaseActivityMenu extends FragmentActivity {

    private static final String TAG = Default.class.getName() + " - ";
    private int mResLayoutId;

    public void onCreate(Bundle savedInstanceState, int resLayout){
        super.onCreate(savedInstanceState);
        setContentView(resLayout);
        mResLayoutId = resLayout;
        switch(mResLayoutId){
            // here change with your xml file
            case R.layout.home:
                // set here common control like header textview
                break;
            default:
                break;
        }
    }
}

3 - Now, you can extend your Activitywith the BaseActivity. This will allow the Activityto be extended by FragmentActivity:

3 - 现在,您可以Activity使用BaseActivity. 这将允许Activity扩展FragmentActivity

public class ABCActivity extends BaseActivityMenu {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState, R.layout.home);
    }
}

回答by waqaslam

In code, your base activity is called ExampleActivity, but in your child class you are extending BaseActivityMenu. Don't know where its coming from.

在代码中,您的基本活动称为ExampleActivity,但在您的子类中,您正在扩展BaseActivityMenu. 不知道它来自哪里。

Perhaps change:

也许改变:

public class ABCActivity extends BaseActivityMenu

To this:

对此:

public class ABCActivity extends ExampleActivity

Moreover, I would suggest you to define your base activity (ExampleActivity) as an Abstractclass. For example:

此外,我建议您将基本活动 ( ExampleActivity)定义为抽象类。例如:

public abstract class ExampleActivity extends Activity

Doing so will not define your base class as concrete and will make it easier to debug in case of problems.

这样做不会将您的基类定义为具体的,并且会更容易在出现问题时进行调试。