我知道已經有這方面的問題,但是我爲我的代碼遵循的格式不同,所以我無法找到問題的答案。 當我點擊包含TextView和ImageView的RecyclerView項目時,我想在DetailActivity中顯示圖像。圖片點擊RecyclerView
activity_main.xml中
<?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"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/framelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pritish.sawant.com.photogallery.MainActivity">
</FrameLayout>
fragment_photo_gallery.xml
<RelativeLayout
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pritish.sawant.com.photogallery.PhotoGalleryFragment">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:id="@+id/recyclerview"
android:layout_height="match_parent"></android.support.v7.widget.RecyclerView>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/loading_indicator"
style="@style/Widget.AppCompat.ProgressBar"
android:layout_centerInParent="true"/>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/textview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:text="Hi" />
<ImageView
android:id="@+id/imageview"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
tools:src="@drawable/image1">
</ImageView>
</LinearLayout>
activity_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="pritish.sawant.com.photogallery.DetailActivity">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/detailimageview"
tools:src="@drawable/image1"/>
</LinearLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
private FragmentManager fragmentManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Photo Gallery");
fragmentManager=getSupportFragmentManager();
Fragment fragment=fragmentManager.findFragmentById(R.id.framelayout);
if(fragment==null){
fragment=new PhotoGalleryFragment();
fragmentManager.beginTransaction().add(R.id.framelayout,fragment).commit();
}
}
}
Photo.java
package pritish.sawant.com.photogallery;
public class Photo {
private String title;
private String author;
private String authorId;
private String link;
private String image;
private String tag;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getAuthorId() {
return authorId;
}
public void setAuthorId(String authorId) {
this.authorId = authorId;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getTag() {
return tag;
}
public void setTag(String tag) {
this.tag = tag;
}
@Override
public String toString() {
return "Photo{" +
"title='" + title + '\'' +
", author='" + author + '\'' +
", authorId='" + authorId + '\'' +
", link='" + link + '\'' +
", image='" + image + '\'' +
", tag='" + tag + '\'' +
'}';
}
}
FlickrFetchr.java
package pritish.sawant.com.photogallery;
import android.net.Uri;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class FlickrFetchr {
private static final String TAG = "FlickrFetchr";
private List<Photo> photoList = null;
private String baseUrl="https://api.flickr.com/services/feeds/photos_public.gne";
public String getData(String url){
BufferedReader bufferedReader=null;
try {
URL url1=new URL(url);
HttpURLConnection httpURLConnection=(HttpURLConnection)url1.openConnection();
StringBuilder stringBuilder=new StringBuilder();
bufferedReader=new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String line;
while ((line=bufferedReader.readLine())!=null){
stringBuilder.append(line+"\n");
}
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
}
finally {
if(bufferedReader!=null){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
private String buildURL(String searchPhoto, String lang, boolean match){
return Uri.parse(baseUrl).buildUpon().appendQueryParameter("tags", searchPhoto)
.appendQueryParameter("tagmode", match ? "ALL" : "ANY")
.appendQueryParameter("format", "json")
.appendQueryParameter("lang", lang)
.appendQueryParameter("nojsoncallback", "1").build().toString();
}
public List<Photo> fetchPhotos(String searchPhoto,String language,boolean matchAll){
String url=buildURL(searchPhoto,language,matchAll);
return downloadGalleyItem(url);
}
//To receive the json format
public List<Photo> downloadGalleyItem(String url){
photoList=new ArrayList<>();
Photo photo=new Photo();
String jsonString=getData(url);
try {
JSONObject jsonObject=new JSONObject(jsonString);
JSONArray jsonArray=jsonObject.getJSONArray("items");
for(int i=0;i<jsonArray.length();i++){
JSONObject jsonObject1=jsonArray.getJSONObject(i);
photo.setTitle(jsonObject1.getString("title"));
photo.setAuthor(jsonObject1.getString("author"));
photo.setAuthorId(jsonObject1.getString("author_id"));
photo.setTag(jsonObject1.getString("tags"));
JSONObject jsonMedia =jsonObject1.getJSONObject("media");
String imageUrl=jsonMedia.getString("m");
photo.setImage(jsonMedia.getString("m"));
//we are changing _m to _b so that when image is tapped we get biigger image
photo.setLink(imageUrl.replaceAll("_m.","_b."));
photoList.add(photo);
}
} catch (Exception e) {
e.printStackTrace();
}
return photoList;
}
}
RecyclerItemClickListener.java
public class RecyclerItemClickListener extends RecyclerView.SimpleOnItemTouchListener {
private static final String TAG = "RecyclerItemClickListen";
interface OnRecyclerClickListener{
void onItemClick(View view,int position);
void onItemLongClick(View view,int position);
}
private final OnRecyclerClickListener listener;
private final GestureDetectorCompat gestureDetectorCompat;
public RecyclerItemClickListener(Context context, final RecyclerView recyclerView, final OnRecyclerClickListener listener) {
this.listener = listener;
gestureDetectorCompat=new GestureDetectorCompat(context,new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onSingleTapUp(MotionEvent e) {
View childView=recyclerView.findChildViewUnder(e.getX(),e.getY());
if(childView!=null && listener!=null){
listener.onItemClick(childView,recyclerView.getChildAdapterPosition(childView));
}
return true;
}
@Override
public void onLongPress(MotionEvent e) {
View childView=recyclerView.findChildViewUnder(e.getX(),e.getY());
if(childView!=null && listener!=null){
listener.onItemLongClick(childView,recyclerView.getChildAdapterPosition(childView));
}
}
});
}
public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent){
if (gestureDetectorCompat!=null){
boolean result=gestureDetectorCompat.onTouchEvent(motionEvent);
return result;
}else{
return false;
}
}
}
PhotoGalleryFragment.java
public class PhotoGalleryFragment extends Fragment implements RecyclerItemClickListener.OnRecyclerClickListener{
private RecyclerView recyclerView;
public ProgressBar progressBar;
public List<Photo> photos = new ArrayList<>();
public PhotoGalleryFragment() {
// Required empty public constructor
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_photo_gallery, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.loading_indicator);
recyclerView = (RecyclerView) view.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(),recyclerView,this));
progressBar.setVisibility(View.GONE);
setUpAdapter();
new FetchTask().execute();
return view;
}
private void setUpAdapter() {
//isAdded checks whether fragment has been added to the activity
if (isAdded()) {
recyclerView.setAdapter(new PhotoAdapter(photos));
}
}
@Override
public void onItemClick(View view, int position) {
Toast.makeText(getActivity(),"Item Clicked",Toast.LENGTH_LONG).show();
Intent intent=new Intent(getActivity(),DetailActivity.class);
//what should i pass in putExtra of intent
//intent.putExtra("IMAGE",photo.getLink());
startActivity(intent);
}
@Override
public void onItemLongClick(View view, int position) {
Toast.makeText(getActivity(),"Item Long Clicked",Toast.LENGTH_LONG).show();
}
private class PhotoHolder extends RecyclerView.ViewHolder {
private ImageView imageView;
private TextView textView;
public PhotoHolder(View itemView) {
super(itemView);
imageView = (ImageView) itemView.findViewById(R.id.imageview);
textView = (TextView) itemView.findViewById(R.id.textview);
}
public void bindItems(Photo photos1) {
Picasso.with(getActivity()).load(photos1.getImage()).into(imageView);
textView.setText(photos1.getTitle());
// Glide.with(getActivity()).load(photos1.getImage()).into(imageView);
}
}
private class PhotoAdapter extends RecyclerView.Adapter<PhotoHolder> {
private List<Photo> galleryItems;
public PhotoAdapter(List<Photo> galleryItems) {
this.galleryItems = galleryItems;
}
@Override
public PhotoHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item, parent, false);
return new PhotoHolder(view);
}
@Override
public void onBindViewHolder(PhotoHolder holder, int position) {
Photo photos2 = galleryItems.get(position);
holder.bindItems(photos2);
}
@Override
public int getItemCount() {
return galleryItems.size();
}
}
private class FetchTask extends AsyncTask<Void, Void, List<Photo>> {
@Override
protected void onPreExecute() {
super.onPreExecute();
if (photos.size() == 0) {
progressBar.setVisibility(View.VISIBLE);
}
}
@Override
protected List<Photo> doInBackground(Void... params) {
return new FlickrFetchr().fetchPhotos("android", "en-us", false);
}
@Override
protected void onPostExecute(List<Photo> photos1) {
super.onPostExecute(photos);
progressBar.setVisibility(View.GONE);
photos = photos1;
setUpAdapter();
}
}
}
DetailActivity.java
public class DetailActivity extends AppCompatActivity {
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
imageView=(ImageView)findViewById(R.id.detailimageview);
int img_id;
if (savedInstanceState != null){
img_id = getIntent().getIntExtra("IMAGE",0);
imageView.setImageResource(img_id);
}
}
}
你的問題是找回? – BakaWaii
在onItemClick的PhotoGalleryFragment我應該在intent.putExtra中傳遞什麼信息,以及如何在DetailActivity的ImageView中檢索該信息 –