Android 使用片段中的图像实现列表视图时出错
我是android的初学者。我正在尝试用片段中的图像制作listview。但还没有完成。 这是我的密码 ListoneFragment.java:(这里name1和name2是我的strings.xml文件中的字符串数组名) 它在ListoneFragment.java行中显示建议Android 使用片段中的图像实现列表视图时出错,android,listview,android-fragments,constructor,Android,Listview,Android Fragments,Constructor,我是android的初学者。我正在尝试用片段中的图像制作listview。但还没有完成。 这是我的密码 ListoneFragment.java:(这里name1和name2是我的strings.xml文件中的字符串数组名) 它在ListoneFragment.java行中显示建议 MyAdapter=新的MyAdapter(此、标题、图像、缩写) 那个 将方法“MyAdapter”的第一个参数从上下文更改为“ListoneFragment” 当我这样做时,它会在MyAdapter类的构造函数中
MyAdapter=新的MyAdapter(此、标题、图像、缩写)参数中的strong> 那个 将方法“MyAdapter”的第一个参数从上下文更改为“ListoneFragment” 当我这样做时,它会在MyAdapter类的构造函数中出错。
我应该怎么做,是否有任何更正或其他实现方法。请帮助?使用活动
上下文
初始化适配器类:
在您的ListOneFragment
中,使用:
MyAdapter adapter=new MyAdapter(getActivity(), titles, images,shortforms);
谢谢你,伙计。它起作用了。但是你能告诉我为什么以前写的“this”作为参数不起作用吗?片段是活动的一部分…所以对于适配器内的上下文,你需要传递活动上下文:
getActivity()
和这个
关键字在你的活动中用于传递上下文。所以它在片段类中不起作用
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list1">
</ListView>
</FrameLayout>
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="72dp">
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@mipmap/ic_launcher_round" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toEndOf="@+id/imageView2"
android:layout_toRightOf="@+id/imageView2"
android:text="TextView" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textView1"
android:layout_toEndOf="@+id/imageView2"
android:layout_toRightOf="@+id/imageView2"
android:text="TextView" />
</RelativeLayout>
</FrameLayout>
Error:(37, 40) error: incompatible types: ListOneFragment cannot be converted to Context
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED
MyAdapter adapter=new MyAdapter(getActivity(), titles, images,shortforms);