gpt4 book ai didi

java - Android 选项卡不工作

转载 作者:行者123 更新时间:2023-12-02 04:43:19 27 4
gpt4 key购买 nike

我正在学习有关 android 中选项卡的教程,并且所做的一切与视频中的完全一样。有一堆代码,但是我在其中一行 tab1.setTabListener(new ActionBar.TabListener(fragment1)); 中遇到错误它说“TabListener”是抽象的;无法实例化。我该如何解决这个问题?

这是 Activity 的完整代码,其中包含错误:

import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ProjectCreateScreen extends ActionBarActivity {

@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondary_layout1);

Toolbar toolbar = (Toolbar) findViewById(R.id.AwesomeBar);
setSupportActionBar(toolbar);

ActionBar.Tab tab1, tab2, tab3;

// Fragments that will load when the tabs are clicked
Fragment fragment1 = new TabFragment1();
Fragment fragment2 = new TabFragment2();
Fragment fragment3 = new TabFragment3();

ActionBar actionBar = getActionBar();

// Set the current navigation mode to tabs
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

// Add titles to tabs
tab1 = actionBar.newTab().setText("Tab1");
tab2 = actionBar.newTab().setText("Tab2");
tab3 = actionBar.newTab().setText("Tab3");

// Set tab listeners which provide callbacks for tab events
// A callback informs another class when an action occurs
tab1.setTabListener(new ActionBar.TabListener(fragment1));
tab2.setTabListener(new ActionBar.TabListener(fragment2));
tab3.setTabListener(new ActionBar.TabListener(fragment3));

// Adds tabs to the actionbar
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
}

最佳答案

您必须创建一个实现 TabListener 接口(interface)的类

protected class MyTabsListener implements ActionBar.TabListener{
private Fragment fragment;

public MyTabsListener(Fragment fragment){
this.fragment = fragment;
}
public void onTabSelected(Tab tab, FragmentTransaction ft){
ft.add(R.id.layout2, fragment, null);
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
}

然后设置tabListener

tab1.setTabListener(new MyTabsListener(fragment1));

关于java - Android 选项卡不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29928788/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com