ViewPager 未从代码、android、eclipse 更新
Posted
技术标签:
【中文标题】ViewPager 未从代码、android、eclipse 更新【英文标题】:ViewPager not updating from code, android, eclipse 【发布时间】:2015-06-21 05:20:06 【问题描述】:在这里搜索了很多答案后,我似乎无法解决我的问题。 首先,我在使用 findViewById 从片段中获取 listView 时遇到问题,为了解决这个问题,我必须先膨胀片段的布局并使用“mContainer.findViewById..”。
我不知道这是否是 viewpager 没有更新(或 listview 本身)的原因。
我的 OnCreate:
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myContainer = getLayoutInflater().inflate(R.layout.frag_links,null);
root = (RelativeLayout) findViewById(R.id.rootLayout);
root.post(new Runnable()
@Override
public void run()
Rect rect = new Rect();
Window win = getWindow(); // Get the Window
win.getDecorView().getWindowVisibleDisplayFrame(rect);
// Get the height of Status Bar
int statusBarHeight = rect.top;
// Get the height occupied by the decoration contents
int contentViewTop = win.findViewById(Window.ID_android_CONTENT).getTop();
// Calculate titleBarHeight by deducting statusBarHeight from contentViewTop
int titleBarHeight = contentViewTop - statusBarHeight;
Log.i("MY", "titleHeight = " + titleBarHeight + " statusHeight = " + statusBarHeight + " contentViewTop = " + contentViewTop);
// By now we got the height of titleBar & statusBar
// Now lets get the screen size
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
screenHeight = metrics.heightPixels;
screenWidth = metrics.widthPixels;
Log.i("MY", "Actual Screen Height = " + screenHeight + " Width = " + screenWidth);
// Now calculate the height that our layout can be set
// If you know that your application doesn't have statusBar added, then don't add here also. Same applies to application bar also
int layoutHeight = screenHeight - (titleBarHeight + statusBarHeight);
Log.i("MY", "Layout Height = " + layoutHeight);
// Lastly, set the height of the layout
// LinearLayout.LayoutParams rootParams = (android.widget.LinearLayout.LayoutParams)root.getLayoutParams();
// rootParams.height = layoutHeight;
// root.setLayoutParams(rootParams);
);
// (array => res/values/strings)
titulosMenu = getResources().getStringArray(R.array.drawer_items);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
lvdrawer = (ListView) findViewById(R.id.lvdrawer);
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
View header = getLayoutInflater().inflate(R.layout.header, null);
lvdrawer.addHeaderView(header);
itemsMenu = new ArrayList<ItemDrawer>();
for (int i = 0; i < titulosMenu.length; i++)
itemsMenu.add(new ItemDrawer(titulosMenu[i]));
AdaptadorDrawer adapter=new AdaptadorDrawer(this, R.layout.filaitem, itemsMenu);
lvdrawer.setAdapter(adapter);
lvdrawer.setOnItemClickListener(new OnItemClickListener()
@Override
public void onItemClick(AdapterView<?> a, View v, int posicion,
long id)
Intent intent;
switch (posicion)
// case 1:
// break;
// case 2:
// break;
case 3:
intent = new Intent(MainActivity.this, Contacto.class);
startActivity(intent);
break;
drawerLayout.closeDrawers();
);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
toggle = new ActionBarDrawerToggle(this, // Activity
drawerLayout, // Panel del Navigation Drawer
new Toolbar(MainActivity.this), // Icono que va a utilizar
R.string.menu, // Descripcion al abrir el drawer
R.string.app_name // Descripcion al cerrar el drawer
)
@Override
public void onDrawerOpened(View drawerView)
getActionBar().setTitle(R.string.menu);
invalidateOptionsMenu();
@Override
public void onDrawerClosed(View view)
getActionBar().setTitle(TITULOREEM);
invalidateOptionsMenu();
;
drawerLayout.setDrawerListener(toggle);
pager = (ViewPager)findViewById(R.id.viewPager);
pager.setAdapter(new AdaptadorPager(getSupportFragmentManager()));
TitlePageIndicator titleIndicator = (TitlePageIndicator)findViewById(R.id.titulo);
titleIndicator.setViewPager(pager);
LinearNews=(LinearLayout)findViewById(R.id.LinearNoticias);
putLinks();
这就是问题所在,我调用了这个方法但没有任何反应。如果我不使用 myContainer.findViewById,程序将崩溃并显示 nullpointerexception,因为它找不到 ListView:
private void putLinks()
lvLinks = (ListView)myContainer.findViewById(R.id.lvlinksnuevo);
listaLinks = new ArrayList<Link>();
listaLinks.add(new Link("test", "test", "link_afijma"));
AdaptadorLinks adaplink = new AdaptadorLinks(MainActivity.this, R.layout.linealinks , listaLinks);
lvLinks.setAdapter(adaplink);
pager.getAdapter().notifyDataSetChanged();
我不知道你是否需要这个,但无论如何都在这里:
@Override
protected void onPostCreate(Bundle savedInstanceState)
super.onPostCreate(savedInstanceState);
toggle.syncState();
@Override
public boolean onCreateOptionsMenu(Menu menu)
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
@Override
public boolean onOptionsItemSelected(MenuItem item)
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (toggle.onOptionsItemSelected(item))
return true;
int id = item.getItemId();
if (id == R.id.menuDrawer)
drawerLayout.openDrawer(Gravity.START);
return true;
return super.onOptionsItemSelected(item);
这是我的寻呼机适配器(我也尝试过使用 FragmentStatePagerAdapter):
public class AdaptadorPager extends FragmentPagerAdapter
private final String[] titles = "Presentación", "Noticias", "Links";
public AdaptadorPager(FragmentManager fragmentManager)
super(fragmentManager);
@Override
public Fragment getItem(int index)
switch (index)
case 0:
return new FragmentoPresentacion();
case 1:
return new FragmentoNoticias();
case 2:
return new FragmentoLinks();
return null;
@Override
public int getCount()
return titles.length;
// 3º Poner en el adaptador el método que devuelve la cadena del titulo
// Devuelve el título segun nos coloquemos en uno u otro fragmento
@Override
public CharSequence getPageTitle(int position)
return titles[position];
这是我的 ListView 适配器:
public class AdaptadorLinks extends ArrayAdapter<Link>
private int layoutFila;
private LayoutInflater inflater;
private Context context;
public AdaptadorLinks(Context ctx, int resourceId, ArrayList<Link> objects)
super(ctx, resourceId, objects);
layoutFila = resourceId;
inflater = LayoutInflater.from(ctx);
context=ctx;
@Override
public View getView(int position, View fila, ViewGroup parent)
fila = inflater.inflate(layoutFila, null );
Link link = getItem(position);
ImageView iconfila=(ImageView) fila.findViewById(R.id.imageLineaLinks);
TextView titulofila = (TextView)fila.findViewById(R.id.tvLineaLinks1);
TextView urlfila = (TextView)fila.findViewById(R.id.tvLineaLinks2);
int id=context.getResources().getIdentifier(link.getImagen(), "drawable", context.getPackageName());
iconfila.setImageResource(id);
titulofila.setText(link.getTitulo());
urlfila.setText(link.getUrl());
return(fila);
设计的xmls是:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_
android:layout_>
<!-- Content -->
<RelativeLayout
android:id="@+id/rootLayout"
android:layout_
android:layout_
android:background="@drawable/background">
<HorizontalScrollView
android:id="@+id/horizontalScrollView1"
android:layout_
android:layout_
android:background="#70000000" >
<LinearLayout
android:id="@+id/LinearNoticias"
android:layout_
android:layout_
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
<com.viewpagerindicator.TitlePageIndicator
android:id="@+id/titulo"
android:layout_
android:layout_
android:layout_below="@id/horizontalScrollView1"
android:background="#95000000" />
<android.support.v4.view.ViewPager
android:id="@+id/viewPager"
android:layout_
android:layout_
android:layout_below="@id/titulo"
android:background="#80000000" />
</RelativeLayout>
<!-- Navigation Drawer -->
<ListView
android:id="@+id/lvdrawer"
android:layout_
android:layout_
android:layout_gravity="start"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
链接片段:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layoutFragLinks"
android:layout_
android:layout_ >
<ListView
android:id="@+id/lvlinksnuevo"
android:layout_
android:layout_
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:background="#90000000" >
</ListView>
</RelativeLayout>
以及用于 LV 适配器的线路:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_
android:layout_ >
<ImageView
android:id="@+id/imageLineaLinks"
android:layout_
android:layout_
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="@drawable/link_emmen" />
<TextView
android:id="@+id/tvLineaLinks1"
android:layout_
android:layout_
android:layout_alignParentTop="true"
android:layout_toEndOf="@+id/imageLineaLinks"
android:layout_toRightOf="@+id/imageLineaLinks"
android:gravity="center"
android:text="TextView"
android:textColor="@color/white"
android:textSize="15sp" />
<TextView
android:id="@+id/tvLineaLinks2"
android:layout_
android:layout_
android:layout_alignLeft="@+id/tvLineaLinks1"
android:layout_alignStart="@+id/tvLineaLinks1"
android:layout_below="@+id/tvLineaLinks1"
android:gravity="center"
android:text="TextView"
android:textColor="@color/white"
android:textSize="12sp" />
</RelativeLayout>
提前致谢。我希望有人可以帮助我。
我的新片段代码:
public class FragmentoLinks extends Fragment
private ListView lvLinks;
private ArrayList<Link> listaLinks;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
View layout = inflater.inflate(R.layout.frag_links, container, false);
lvLinks = (ListView)getActivity().findViewById(R.id.lvlinksnuevo);
listaLinks = new ArrayList<Link>();
listaLinks.add(new Link("test", "test", "link_afijma"));
AdaptadorLinks adaplink = new AdaptadorLinks(getActivity(), R.layout.linealinks , listaLinks);
lvLinks.setAdapter(adaplink);
return layout;
我尝试用 getView() 代替 getActivity() 结果相同。
这是我现在得到的错误:
04-15 12:44:41.192: E/AndroidRuntime(32713): FATAL EXCEPTION: main
04-15 12:44:41.192: E/AndroidRuntime(32713): Process: com.aeioumusica.aplireem, PID: 32713
04-15 12:44:41.192: E/AndroidRuntime(32713): java.lang.NullPointerException
04-15 12:44:41.192: E/AndroidRuntime(32713): at com.aeioumusica.aplireem.FragmentoLinks.onCreateView(FragmentoLinks.java:32)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:953)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1136)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1499)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:488)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.support.v4.view.ViewPager$3.run(ViewPager.java:249)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.view.Choreographer.doCallbacks(Choreographer.java:603)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.view.Choreographer.doFrame(Choreographer.java:572)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.os.Handler.handleCallback(Handler.java:733)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.os.Handler.dispatchMessage(Handler.java:95)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.os.Looper.loop(Looper.java:157)
04-15 12:44:41.192: E/AndroidRuntime(32713): at android.app.ActivityThread.main(ActivityThread.java:5356)
04-15 12:44:41.192: E/AndroidRuntime(32713): at java.lang.reflect.Method.invokeNative(Native Method)
04-15 12:44:41.192: E/AndroidRuntime(32713): at java.lang.reflect.Method.invoke(Method.java:515)
04-15 12:44:41.192: E/AndroidRuntime(32713): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
04-15 12:44:41.192: E/AndroidRuntime(32713): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
04-15 12:44:41.192: E/AndroidRuntime(32713): at dalvik.system.NativeStart.main(Native Method)
【问题讨论】:
你必须看看这个link 【参考方案1】:在片段中,您应该在onCreateView()
中进行视图设置,然后调用
getView().findViewById()
在其他地方。
这是因为片段的生命周期与活动不同。
更多信息请参见http://developer.android.com/guide/components/fragments.html#Creating。
【讨论】:
执行此操作后,我的应用程序崩溃,在片段的 onCreateView 方法上给我一个空指针异常。我唯一做的就是在片段中移动 putLink() 方法并使用 getView().findViewById... 还有什么我需要做的吗? 如果 lvlinks 是布局 frag_links 内的视图。然后你应该使用 layout.findViewById(R.id.lvlinksnuevo);因为它将搜索从该视图的 frag_links 布局创建的布局视图。【参考方案2】:myContainer = getLayoutInflater().inflate(R.layout.frag_links,null);
这将创建一个带有片段布局的新RelativeLayout
,它没有附加到任何地方,也不会显示在屏幕上。它肯定不会返回您要修改的组件,它是作为片段的一部分创建的。
从您的代码中,您想修改其中一个片段内的ListView
。但是,该特定片段甚至可能不会显示,因为ViewPager
决定何时创建您的片段。当您的代码执行时,该片段可能还不存在,或者它可能不在屏幕上。
然而,最重要的是,片段并不总是活动视图层次结构的一部分。因此,活动上的findViewById()
将找不到任何东西,因为视图可能根本不存在。
将您的链接更新代码移动到片段中,并在扩展片段布局后在片段内使用layout.findViewById()
。这会将ListAdapter
附加到片段内的正确ListView
从布局XML 膨胀后。
【讨论】:
执行此操作后,我的应用程序崩溃,在片段的 onCreateView 方法上给我一个空指针异常。我唯一做的就是在片段中移动 putLink() 方法并使用 getView().findViewById... 还有什么我需要做的吗? 很难说,因为您的问题不包含片段代码。您需要在片段的onCreateView()
内膨胀片段布局(并返回它)。
我用最新的片段代码编辑了问题。对不起,我之前忘了添加它
你应该可以在扩展布局后直接使用layout.findViewById()
。
谢谢,使用 layout.findViewById() 解决了所有问题。我还为适配器使用了 layout.getContext()。非常感谢。【参考方案3】:
虽然Fragment
被实现为一个独立于
一个Activity
并且可以在多个活动中使用,一个给定的
Fragment
的实例直接与包含
它。
具体来说,片段可以通过以下方式访问Activity
实例
getActivity()
并轻松执行任务,例如在
Activity
布局:
View listView = getActivity().findViewById(R.id.list);
同样,您的Activity
可以通过获取
从FragmentManager
引用Fragment
,使用findFragmentById()
或findFragmentByTag()
。例如:
ExampleFragment fragment = (ExampleFragment)
getFragmentManager().findFragmentById(R.id.example_fragment);
【讨论】:
请参考link以上是关于ViewPager 未从代码、android、eclipse 更新的主要内容,如果未能解决你的问题,请参考以下文章